three.core.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '184';
  7. /**
  8. * Represents mouse buttons and interaction types in context of controls.
  9. *
  10. * @type {ConstantsMouse}
  11. * @constant
  12. */
  13. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  14. /**
  15. * Represents touch interaction types in context of controls.
  16. *
  17. * @type {ConstantsTouch}
  18. * @constant
  19. */
  20. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  21. /**
  22. * Disables face culling.
  23. *
  24. * @type {number}
  25. * @constant
  26. */
  27. const CullFaceNone = 0;
  28. /**
  29. * Culls back faces.
  30. *
  31. * @type {number}
  32. * @constant
  33. */
  34. const CullFaceBack = 1;
  35. /**
  36. * Culls front faces.
  37. *
  38. * @type {number}
  39. * @constant
  40. */
  41. const CullFaceFront = 2;
  42. /**
  43. * Culls both front and back faces.
  44. *
  45. * @type {number}
  46. * @constant
  47. */
  48. const CullFaceFrontBack = 3;
  49. /**
  50. * Gives unfiltered shadow maps - fastest, but lowest quality.
  51. *
  52. * @type {number}
  53. * @constant
  54. */
  55. const BasicShadowMap = 0;
  56. /**
  57. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  58. *
  59. * @type {number}
  60. * @constant
  61. */
  62. const PCFShadowMap = 1;
  63. /**
  64. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  65. * better soft shadows especially when using low-resolution shadow maps.
  66. *
  67. * @type {number}
  68. * @constant
  69. */
  70. const PCFSoftShadowMap = 2;
  71. /**
  72. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  73. * When using VSMShadowMap all shadow receivers will also cast shadows.
  74. *
  75. * @type {number}
  76. * @constant
  77. */
  78. const VSMShadowMap = 3;
  79. /**
  80. * Only front faces are rendered.
  81. *
  82. * @type {number}
  83. * @constant
  84. */
  85. const FrontSide = 0;
  86. /**
  87. * Only back faces are rendered.
  88. *
  89. * @type {number}
  90. * @constant
  91. */
  92. const BackSide = 1;
  93. /**
  94. * Both front and back faces are rendered.
  95. *
  96. * @type {number}
  97. * @constant
  98. */
  99. const DoubleSide = 2;
  100. /**
  101. * No blending is performed which effectively disables
  102. * alpha transparency.
  103. *
  104. * @type {number}
  105. * @constant
  106. */
  107. const NoBlending = 0;
  108. /**
  109. * The default blending.
  110. *
  111. * @type {number}
  112. * @constant
  113. */
  114. const NormalBlending = 1;
  115. /**
  116. * Represents additive blending.
  117. *
  118. * @type {number}
  119. * @constant
  120. */
  121. const AdditiveBlending = 2;
  122. /**
  123. * Represents subtractive blending.
  124. *
  125. * @type {number}
  126. * @constant
  127. */
  128. const SubtractiveBlending = 3;
  129. /**
  130. * Represents multiply blending.
  131. *
  132. * @type {number}
  133. * @constant
  134. */
  135. const MultiplyBlending = 4;
  136. /**
  137. * Represents custom blending.
  138. *
  139. * @type {number}
  140. * @constant
  141. */
  142. const CustomBlending = 5;
  143. /**
  144. * Represents material blending.
  145. *
  146. * @type {number}
  147. * @constant
  148. */
  149. const MaterialBlending = 6;
  150. /**
  151. * A `source + destination` blending equation.
  152. *
  153. * @type {number}
  154. * @constant
  155. */
  156. const AddEquation = 100;
  157. /**
  158. * A `source - destination` blending equation.
  159. *
  160. * @type {number}
  161. * @constant
  162. */
  163. const SubtractEquation = 101;
  164. /**
  165. * A `destination - source` blending equation.
  166. *
  167. * @type {number}
  168. * @constant
  169. */
  170. const ReverseSubtractEquation = 102;
  171. /**
  172. * A blend equation that uses the minimum of source and destination.
  173. *
  174. * @type {number}
  175. * @constant
  176. */
  177. const MinEquation = 103;
  178. /**
  179. * A blend equation that uses the maximum of source and destination.
  180. *
  181. * @type {number}
  182. * @constant
  183. */
  184. const MaxEquation = 104;
  185. /**
  186. * Multiplies all colors by `0`.
  187. *
  188. * @type {number}
  189. * @constant
  190. */
  191. const ZeroFactor = 200;
  192. /**
  193. * Multiplies all colors by `1`.
  194. *
  195. * @type {number}
  196. * @constant
  197. */
  198. const OneFactor = 201;
  199. /**
  200. * Multiplies all colors by the source colors.
  201. *
  202. * @type {number}
  203. * @constant
  204. */
  205. const SrcColorFactor = 202;
  206. /**
  207. * Multiplies all colors by `1` minus each source color.
  208. *
  209. * @type {number}
  210. * @constant
  211. */
  212. const OneMinusSrcColorFactor = 203;
  213. /**
  214. * Multiplies all colors by the source alpha value.
  215. *
  216. * @type {number}
  217. * @constant
  218. */
  219. const SrcAlphaFactor = 204;
  220. /**
  221. * Multiplies all colors by 1 minus the source alpha value.
  222. *
  223. * @type {number}
  224. * @constant
  225. */
  226. const OneMinusSrcAlphaFactor = 205;
  227. /**
  228. * Multiplies all colors by the destination alpha value.
  229. *
  230. * @type {number}
  231. * @constant
  232. */
  233. const DstAlphaFactor = 206;
  234. /**
  235. * Multiplies all colors by `1` minus the destination alpha value.
  236. *
  237. * @type {number}
  238. * @constant
  239. */
  240. const OneMinusDstAlphaFactor = 207;
  241. /**
  242. * Multiplies all colors by the destination color.
  243. *
  244. * @type {number}
  245. * @constant
  246. */
  247. const DstColorFactor = 208;
  248. /**
  249. * Multiplies all colors by `1` minus each destination color.
  250. *
  251. * @type {number}
  252. * @constant
  253. */
  254. const OneMinusDstColorFactor = 209;
  255. /**
  256. * Multiplies the RGB colors by the smaller of either the source alpha
  257. * value or the value of `1` minus the destination alpha value. The alpha
  258. * value is multiplied by `1`.
  259. *
  260. * @type {number}
  261. * @constant
  262. */
  263. const SrcAlphaSaturateFactor = 210;
  264. /**
  265. * Multiplies all colors by a constant color.
  266. *
  267. * @type {number}
  268. * @constant
  269. */
  270. const ConstantColorFactor = 211;
  271. /**
  272. * Multiplies all colors by `1` minus a constant color.
  273. *
  274. * @type {number}
  275. * @constant
  276. */
  277. const OneMinusConstantColorFactor = 212;
  278. /**
  279. * Multiplies all colors by a constant alpha value.
  280. *
  281. * @type {number}
  282. * @constant
  283. */
  284. const ConstantAlphaFactor = 213;
  285. /**
  286. * Multiplies all colors by 1 minus a constant alpha value.
  287. *
  288. * @type {number}
  289. * @constant
  290. */
  291. const OneMinusConstantAlphaFactor = 214;
  292. /**
  293. * Never pass.
  294. *
  295. * @type {number}
  296. * @constant
  297. */
  298. const NeverDepth = 0;
  299. /**
  300. * Always pass.
  301. *
  302. * @type {number}
  303. * @constant
  304. */
  305. const AlwaysDepth = 1;
  306. /**
  307. * Pass if the incoming value is less than the depth buffer value.
  308. *
  309. * @type {number}
  310. * @constant
  311. */
  312. const LessDepth = 2;
  313. /**
  314. * Pass if the incoming value is less than or equal to the depth buffer value.
  315. *
  316. * @type {number}
  317. * @constant
  318. */
  319. const LessEqualDepth = 3;
  320. /**
  321. * Pass if the incoming value equals the depth buffer value.
  322. *
  323. * @type {number}
  324. * @constant
  325. */
  326. const EqualDepth = 4;
  327. /**
  328. * Pass if the incoming value is greater than or equal to the depth buffer value.
  329. *
  330. * @type {number}
  331. * @constant
  332. */
  333. const GreaterEqualDepth = 5;
  334. /**
  335. * Pass if the incoming value is greater than the depth buffer value.
  336. *
  337. * @type {number}
  338. * @constant
  339. */
  340. const GreaterDepth = 6;
  341. /**
  342. * Pass if the incoming value is not equal to the depth buffer value.
  343. *
  344. * @type {number}
  345. * @constant
  346. */
  347. const NotEqualDepth = 7;
  348. /**
  349. * Multiplies the environment map color with the surface color.
  350. *
  351. * @type {number}
  352. * @constant
  353. */
  354. const MultiplyOperation = 0;
  355. /**
  356. * Uses reflectivity to blend between the two colors.
  357. *
  358. * @type {number}
  359. * @constant
  360. */
  361. const MixOperation = 1;
  362. /**
  363. * Adds the two colors.
  364. *
  365. * @type {number}
  366. * @constant
  367. */
  368. const AddOperation = 2;
  369. /**
  370. * No tone mapping is applied.
  371. *
  372. * @type {number}
  373. * @constant
  374. */
  375. const NoToneMapping = 0;
  376. /**
  377. * Linear tone mapping.
  378. *
  379. * @type {number}
  380. * @constant
  381. */
  382. const LinearToneMapping = 1;
  383. /**
  384. * Reinhard tone mapping.
  385. *
  386. * @type {number}
  387. * @constant
  388. */
  389. const ReinhardToneMapping = 2;
  390. /**
  391. * Cineon tone mapping.
  392. *
  393. * @type {number}
  394. * @constant
  395. */
  396. const CineonToneMapping = 3;
  397. /**
  398. * ACES Filmic tone mapping.
  399. *
  400. * @type {number}
  401. * @constant
  402. */
  403. const ACESFilmicToneMapping = 4;
  404. /**
  405. * Custom tone mapping.
  406. *
  407. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  408. *
  409. * @type {number}
  410. * @constant
  411. */
  412. const CustomToneMapping = 5;
  413. /**
  414. * AgX tone mapping.
  415. *
  416. * @type {number}
  417. * @constant
  418. */
  419. const AgXToneMapping = 6;
  420. /**
  421. * Neutral tone mapping.
  422. *
  423. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  424. *
  425. * @type {number}
  426. * @constant
  427. */
  428. const NeutralToneMapping = 7;
  429. /**
  430. * The skinned mesh shares the same world space as the skeleton.
  431. *
  432. * @type {string}
  433. * @constant
  434. */
  435. const AttachedBindMode = 'attached';
  436. /**
  437. * The skinned mesh does not share the same world space as the skeleton.
  438. * This is useful when a skeleton is shared across multiple skinned meshes.
  439. *
  440. * @type {string}
  441. * @constant
  442. */
  443. const DetachedBindMode = 'detached';
  444. /**
  445. * Maps textures using the geometry's UV coordinates.
  446. *
  447. * @type {number}
  448. * @constant
  449. */
  450. const UVMapping = 300;
  451. /**
  452. * Reflection mapping for cube textures.
  453. *
  454. * @type {number}
  455. * @constant
  456. */
  457. const CubeReflectionMapping = 301;
  458. /**
  459. * Refraction mapping for cube textures.
  460. *
  461. * @type {number}
  462. * @constant
  463. */
  464. const CubeRefractionMapping = 302;
  465. /**
  466. * Reflection mapping for equirectangular textures.
  467. *
  468. * @type {number}
  469. * @constant
  470. */
  471. const EquirectangularReflectionMapping = 303;
  472. /**
  473. * Refraction mapping for equirectangular textures.
  474. *
  475. * @type {number}
  476. * @constant
  477. */
  478. const EquirectangularRefractionMapping = 304;
  479. /**
  480. * Reflection mapping for PMREM textures.
  481. *
  482. * @type {number}
  483. * @constant
  484. */
  485. const CubeUVReflectionMapping = 306;
  486. /**
  487. * The texture will simply repeat to infinity.
  488. *
  489. * @type {number}
  490. * @constant
  491. */
  492. const RepeatWrapping = 1000;
  493. /**
  494. * The last pixel of the texture stretches to the edge of the mesh.
  495. *
  496. * @type {number}
  497. * @constant
  498. */
  499. const ClampToEdgeWrapping = 1001;
  500. /**
  501. * The texture will repeats to infinity, mirroring on each repeat.
  502. *
  503. * @type {number}
  504. * @constant
  505. */
  506. const MirroredRepeatWrapping = 1002;
  507. /**
  508. * Returns the value of the texture element that is nearest (in Manhattan distance)
  509. * to the specified texture coordinates.
  510. *
  511. * @type {number}
  512. * @constant
  513. */
  514. const NearestFilter = 1003;
  515. /**
  516. * Chooses the mipmap that most closely matches the size of the pixel being textured
  517. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  518. * to produce a texture value.
  519. *
  520. * @type {number}
  521. * @constant
  522. */
  523. const NearestMipmapNearestFilter = 1004;
  524. const NearestMipMapNearestFilter = 1004; // legacy
  525. /**
  526. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  527. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  528. * The final texture value is a weighted average of those two values.
  529. *
  530. * @type {number}
  531. * @constant
  532. */
  533. const NearestMipmapLinearFilter = 1005;
  534. const NearestMipMapLinearFilter = 1005; // legacy
  535. /**
  536. * Returns the weighted average of the four texture elements that are closest to the specified
  537. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  538. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  539. *
  540. * @type {number}
  541. * @constant
  542. */
  543. const LinearFilter = 1006;
  544. /**
  545. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  546. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  547. * center of the pixel) to produce a texture value.
  548. *
  549. * @type {number}
  550. * @constant
  551. */
  552. const LinearMipmapNearestFilter = 1007;
  553. const LinearMipMapNearestFilter = 1007; // legacy
  554. /**
  555. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  556. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  557. * is a weighted average of those two values.
  558. *
  559. * @type {number}
  560. * @constant
  561. */
  562. const LinearMipmapLinearFilter = 1008;
  563. const LinearMipMapLinearFilter = 1008; // legacy
  564. /**
  565. * An unsigned byte data type for textures.
  566. *
  567. * @type {number}
  568. * @constant
  569. */
  570. const UnsignedByteType = 1009;
  571. /**
  572. * A byte data type for textures.
  573. *
  574. * @type {number}
  575. * @constant
  576. */
  577. const ByteType = 1010;
  578. /**
  579. * A short data type for textures.
  580. *
  581. * @type {number}
  582. * @constant
  583. */
  584. const ShortType = 1011;
  585. /**
  586. * An unsigned short data type for textures.
  587. *
  588. * @type {number}
  589. * @constant
  590. */
  591. const UnsignedShortType = 1012;
  592. /**
  593. * An int data type for textures.
  594. *
  595. * @type {number}
  596. * @constant
  597. */
  598. const IntType = 1013;
  599. /**
  600. * An unsigned int data type for textures.
  601. *
  602. * @type {number}
  603. * @constant
  604. */
  605. const UnsignedIntType = 1014;
  606. /**
  607. * A float data type for textures.
  608. *
  609. * @type {number}
  610. * @constant
  611. */
  612. const FloatType = 1015;
  613. /**
  614. * A half float data type for textures.
  615. *
  616. * @type {number}
  617. * @constant
  618. */
  619. const HalfFloatType = 1016;
  620. /**
  621. * An unsigned short 4_4_4_4 (packed) data type for textures.
  622. *
  623. * @type {number}
  624. * @constant
  625. */
  626. const UnsignedShort4444Type = 1017;
  627. /**
  628. * An unsigned short 5_5_5_1 (packed) data type for textures.
  629. *
  630. * @type {number}
  631. * @constant
  632. */
  633. const UnsignedShort5551Type = 1018;
  634. /**
  635. * An unsigned int 24_8 data type for textures.
  636. *
  637. * @type {number}
  638. * @constant
  639. */
  640. const UnsignedInt248Type = 1020;
  641. /**
  642. * An unsigned int 5_9_9_9 (packed) data type for textures.
  643. *
  644. * @type {number}
  645. * @constant
  646. */
  647. const UnsignedInt5999Type = 35902;
  648. /**
  649. * An unsigned int 10_11_11 (packed) data type for textures.
  650. *
  651. * @type {number}
  652. * @constant
  653. */
  654. const UnsignedInt101111Type = 35899;
  655. /**
  656. * Discards the red, green and blue components and reads just the alpha component.
  657. *
  658. * @type {number}
  659. * @constant
  660. */
  661. const AlphaFormat = 1021;
  662. /**
  663. * Discards the alpha component and reads the red, green and blue component.
  664. *
  665. * @type {number}
  666. * @constant
  667. */
  668. const RGBFormat = 1022;
  669. /**
  670. * Reads the red, green, blue and alpha components.
  671. *
  672. * @type {number}
  673. * @constant
  674. */
  675. const RGBAFormat = 1023;
  676. /**
  677. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  678. *
  679. * @type {number}
  680. * @constant
  681. */
  682. const DepthFormat = 1026;
  683. /**
  684. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  685. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  686. *
  687. * @type {number}
  688. * @constant
  689. */
  690. const DepthStencilFormat = 1027;
  691. /**
  692. * Discards the green, blue and alpha components and reads just the red component.
  693. *
  694. * @type {number}
  695. * @constant
  696. */
  697. const RedFormat = 1028;
  698. /**
  699. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  700. *
  701. * @type {number}
  702. * @constant
  703. */
  704. const RedIntegerFormat = 1029;
  705. /**
  706. * Discards the alpha, and blue components and reads the red, and green components.
  707. *
  708. * @type {number}
  709. * @constant
  710. */
  711. const RGFormat = 1030;
  712. /**
  713. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  714. *
  715. * @type {number}
  716. * @constant
  717. */
  718. const RGIntegerFormat = 1031;
  719. /**
  720. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  721. *
  722. * @type {number}
  723. * @constant
  724. */
  725. const RGBIntegerFormat = 1032;
  726. /**
  727. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  728. *
  729. * @type {number}
  730. * @constant
  731. */
  732. const RGBAIntegerFormat = 1033;
  733. /**
  734. * A DXT1-compressed image in an RGB image format.
  735. *
  736. * @type {number}
  737. * @constant
  738. */
  739. const RGB_S3TC_DXT1_Format = 33776;
  740. /**
  741. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  742. *
  743. * @type {number}
  744. * @constant
  745. */
  746. const RGBA_S3TC_DXT1_Format = 33777;
  747. /**
  748. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  749. *
  750. * @type {number}
  751. * @constant
  752. */
  753. const RGBA_S3TC_DXT3_Format = 33778;
  754. /**
  755. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  756. * compression in how the alpha compression is done.
  757. *
  758. * @type {number}
  759. * @constant
  760. */
  761. const RGBA_S3TC_DXT5_Format = 33779;
  762. /**
  763. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  764. *
  765. * @type {number}
  766. * @constant
  767. */
  768. const RGB_PVRTC_4BPPV1_Format = 35840;
  769. /**
  770. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  771. *
  772. * @type {number}
  773. * @constant
  774. */
  775. const RGB_PVRTC_2BPPV1_Format = 35841;
  776. /**
  777. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  778. *
  779. * @type {number}
  780. * @constant
  781. */
  782. const RGBA_PVRTC_4BPPV1_Format = 35842;
  783. /**
  784. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  785. *
  786. * @type {number}
  787. * @constant
  788. */
  789. const RGBA_PVRTC_2BPPV1_Format = 35843;
  790. /**
  791. * ETC1 RGB format.
  792. *
  793. * @type {number}
  794. * @constant
  795. */
  796. const RGB_ETC1_Format = 36196;
  797. /**
  798. * ETC2 RGB format.
  799. *
  800. * @type {number}
  801. * @constant
  802. */
  803. const RGB_ETC2_Format = 37492;
  804. /**
  805. * ETC2 RGBA format.
  806. *
  807. * @type {number}
  808. * @constant
  809. */
  810. const RGBA_ETC2_EAC_Format = 37496;
  811. /**
  812. * EAC R11 UNORM format.
  813. *
  814. * @type {number}
  815. * @constant
  816. */
  817. const R11_EAC_Format = 37488; // 0x9270
  818. /**
  819. * EAC R11 SNORM format.
  820. *
  821. * @type {number}
  822. * @constant
  823. */
  824. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  825. /**
  826. * EAC RG11 UNORM format.
  827. *
  828. * @type {number}
  829. * @constant
  830. */
  831. const RG11_EAC_Format = 37490; // 0x9272
  832. /**
  833. * EAC RG11 SNORM format.
  834. *
  835. * @type {number}
  836. * @constant
  837. */
  838. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  839. /**
  840. * ASTC RGBA 4x4 format.
  841. *
  842. * @type {number}
  843. * @constant
  844. */
  845. const RGBA_ASTC_4x4_Format = 37808;
  846. /**
  847. * ASTC RGBA 5x4 format.
  848. *
  849. * @type {number}
  850. * @constant
  851. */
  852. const RGBA_ASTC_5x4_Format = 37809;
  853. /**
  854. * ASTC RGBA 5x5 format.
  855. *
  856. * @type {number}
  857. * @constant
  858. */
  859. const RGBA_ASTC_5x5_Format = 37810;
  860. /**
  861. * ASTC RGBA 6x5 format.
  862. *
  863. * @type {number}
  864. * @constant
  865. */
  866. const RGBA_ASTC_6x5_Format = 37811;
  867. /**
  868. * ASTC RGBA 6x6 format.
  869. *
  870. * @type {number}
  871. * @constant
  872. */
  873. const RGBA_ASTC_6x6_Format = 37812;
  874. /**
  875. * ASTC RGBA 8x5 format.
  876. *
  877. * @type {number}
  878. * @constant
  879. */
  880. const RGBA_ASTC_8x5_Format = 37813;
  881. /**
  882. * ASTC RGBA 8x6 format.
  883. *
  884. * @type {number}
  885. * @constant
  886. */
  887. const RGBA_ASTC_8x6_Format = 37814;
  888. /**
  889. * ASTC RGBA 8x8 format.
  890. *
  891. * @type {number}
  892. * @constant
  893. */
  894. const RGBA_ASTC_8x8_Format = 37815;
  895. /**
  896. * ASTC RGBA 10x5 format.
  897. *
  898. * @type {number}
  899. * @constant
  900. */
  901. const RGBA_ASTC_10x5_Format = 37816;
  902. /**
  903. * ASTC RGBA 10x6 format.
  904. *
  905. * @type {number}
  906. * @constant
  907. */
  908. const RGBA_ASTC_10x6_Format = 37817;
  909. /**
  910. * ASTC RGBA 10x8 format.
  911. *
  912. * @type {number}
  913. * @constant
  914. */
  915. const RGBA_ASTC_10x8_Format = 37818;
  916. /**
  917. * ASTC RGBA 10x10 format.
  918. *
  919. * @type {number}
  920. * @constant
  921. */
  922. const RGBA_ASTC_10x10_Format = 37819;
  923. /**
  924. * ASTC RGBA 12x10 format.
  925. *
  926. * @type {number}
  927. * @constant
  928. */
  929. const RGBA_ASTC_12x10_Format = 37820;
  930. /**
  931. * ASTC RGBA 12x12 format.
  932. *
  933. * @type {number}
  934. * @constant
  935. */
  936. const RGBA_ASTC_12x12_Format = 37821;
  937. /**
  938. * BPTC RGBA format.
  939. *
  940. * @type {number}
  941. * @constant
  942. */
  943. const RGBA_BPTC_Format = 36492;
  944. /**
  945. * BPTC Signed RGB format.
  946. *
  947. * @type {number}
  948. * @constant
  949. */
  950. const RGB_BPTC_SIGNED_Format = 36494;
  951. /**
  952. * BPTC Unsigned RGB format.
  953. *
  954. * @type {number}
  955. * @constant
  956. */
  957. const RGB_BPTC_UNSIGNED_Format = 36495;
  958. /**
  959. * RGTC1 Red format.
  960. *
  961. * @type {number}
  962. * @constant
  963. */
  964. const RED_RGTC1_Format = 36283;
  965. /**
  966. * RGTC1 Signed Red format.
  967. *
  968. * @type {number}
  969. * @constant
  970. */
  971. const SIGNED_RED_RGTC1_Format = 36284;
  972. /**
  973. * RGTC2 Red Green format.
  974. *
  975. * @type {number}
  976. * @constant
  977. */
  978. const RED_GREEN_RGTC2_Format = 36285;
  979. /**
  980. * RGTC2 Signed Red Green format.
  981. *
  982. * @type {number}
  983. * @constant
  984. */
  985. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  986. /**
  987. * Animations are played once.
  988. *
  989. * @type {number}
  990. * @constant
  991. */
  992. const LoopOnce = 2200;
  993. /**
  994. * Animations are played with a chosen number of repetitions, each time jumping from
  995. * the end of the clip directly to its beginning.
  996. *
  997. * @type {number}
  998. * @constant
  999. */
  1000. const LoopRepeat = 2201;
  1001. /**
  1002. * Animations are played with a chosen number of repetitions, alternately playing forward
  1003. * and backward.
  1004. *
  1005. * @type {number}
  1006. * @constant
  1007. */
  1008. const LoopPingPong = 2202;
  1009. /**
  1010. * Discrete interpolation mode for keyframe tracks.
  1011. *
  1012. * @type {number}
  1013. * @constant
  1014. */
  1015. const InterpolateDiscrete = 2300;
  1016. /**
  1017. * Linear interpolation mode for keyframe tracks.
  1018. *
  1019. * @type {number}
  1020. * @constant
  1021. */
  1022. const InterpolateLinear = 2301;
  1023. /**
  1024. * Smooth interpolation mode for keyframe tracks.
  1025. *
  1026. * @type {number}
  1027. * @constant
  1028. */
  1029. const InterpolateSmooth = 2302;
  1030. /**
  1031. * Bezier interpolation mode for keyframe tracks.
  1032. *
  1033. * Uses cubic Bezier curves with explicit 2D control points.
  1034. * Requires tangent data to be set on the track.
  1035. *
  1036. * @type {number}
  1037. * @constant
  1038. */
  1039. const InterpolateBezier = 2303;
  1040. /**
  1041. * Zero curvature ending for animations.
  1042. *
  1043. * @type {number}
  1044. * @constant
  1045. */
  1046. const ZeroCurvatureEnding = 2400;
  1047. /**
  1048. * Zero slope ending for animations.
  1049. *
  1050. * @type {number}
  1051. * @constant
  1052. */
  1053. const ZeroSlopeEnding = 2401;
  1054. /**
  1055. * Wrap around ending for animations.
  1056. *
  1057. * @type {number}
  1058. * @constant
  1059. */
  1060. const WrapAroundEnding = 2402;
  1061. /**
  1062. * Default animation blend mode.
  1063. *
  1064. * @type {number}
  1065. * @constant
  1066. */
  1067. const NormalAnimationBlendMode = 2500;
  1068. /**
  1069. * Additive animation blend mode. Can be used to layer motions on top of
  1070. * each other to build complex performances from smaller re-usable assets.
  1071. *
  1072. * @type {number}
  1073. * @constant
  1074. */
  1075. const AdditiveAnimationBlendMode = 2501;
  1076. /**
  1077. * For every three vertices draw a single triangle.
  1078. *
  1079. * @type {number}
  1080. * @constant
  1081. */
  1082. const TrianglesDrawMode = 0;
  1083. /**
  1084. * For each vertex draw a triangle from the last three vertices.
  1085. *
  1086. * @type {number}
  1087. * @constant
  1088. */
  1089. const TriangleStripDrawMode = 1;
  1090. /**
  1091. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1092. *
  1093. * @type {number}
  1094. * @constant
  1095. */
  1096. const TriangleFanDrawMode = 2;
  1097. /**
  1098. * The depth value is inverted (1.0 - z) for visualization purposes.
  1099. *
  1100. * @type {number}
  1101. * @constant
  1102. */
  1103. const BasicDepthPacking = 3200;
  1104. /**
  1105. * The depth value is packed into 32 bit RGBA.
  1106. *
  1107. * @type {number}
  1108. * @constant
  1109. */
  1110. const RGBADepthPacking = 3201;
  1111. /**
  1112. * The depth value is packed into 24 bit RGB.
  1113. *
  1114. * @type {number}
  1115. * @constant
  1116. */
  1117. const RGBDepthPacking = 3202;
  1118. /**
  1119. * The depth value is packed into 16 bit RG.
  1120. *
  1121. * @type {number}
  1122. * @constant
  1123. */
  1124. const RGDepthPacking = 3203;
  1125. /**
  1126. * Normal information is relative to the underlying surface.
  1127. *
  1128. * @type {number}
  1129. * @constant
  1130. */
  1131. const TangentSpaceNormalMap = 0;
  1132. /**
  1133. * Normal information is relative to the object orientation.
  1134. *
  1135. * @type {number}
  1136. * @constant
  1137. */
  1138. const ObjectSpaceNormalMap = 1;
  1139. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1140. /**
  1141. * No color space.
  1142. *
  1143. * @type {string}
  1144. * @constant
  1145. */
  1146. const NoColorSpace = '';
  1147. /**
  1148. * sRGB color space.
  1149. *
  1150. * @type {string}
  1151. * @constant
  1152. */
  1153. const SRGBColorSpace = 'srgb';
  1154. /**
  1155. * sRGB-linear color space.
  1156. *
  1157. * @type {string}
  1158. * @constant
  1159. */
  1160. const LinearSRGBColorSpace = 'srgb-linear';
  1161. /**
  1162. * Linear transfer function.
  1163. *
  1164. * @type {string}
  1165. * @constant
  1166. */
  1167. const LinearTransfer = 'linear';
  1168. /**
  1169. * sRGB transfer function.
  1170. *
  1171. * @type {string}
  1172. * @constant
  1173. */
  1174. const SRGBTransfer = 'srgb';
  1175. /**
  1176. * No normal map packing.
  1177. *
  1178. * @type {string}
  1179. * @constant
  1180. */
  1181. const NoNormalPacking = '';
  1182. /**
  1183. * Normal RG packing.
  1184. *
  1185. * @type {string}
  1186. * @constant
  1187. */
  1188. const NormalRGPacking = 'rg';
  1189. /**
  1190. * Normal GA packing.
  1191. *
  1192. * @type {string}
  1193. * @constant
  1194. */
  1195. const NormalGAPacking = 'ga';
  1196. /**
  1197. * Sets the stencil buffer value to `0`.
  1198. *
  1199. * @type {number}
  1200. * @constant
  1201. */
  1202. const ZeroStencilOp = 0;
  1203. /**
  1204. * Keeps the current value.
  1205. *
  1206. * @type {number}
  1207. * @constant
  1208. */
  1209. const KeepStencilOp = 7680;
  1210. /**
  1211. * Sets the stencil buffer value to the specified reference value.
  1212. *
  1213. * @type {number}
  1214. * @constant
  1215. */
  1216. const ReplaceStencilOp = 7681;
  1217. /**
  1218. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1219. *
  1220. * @type {number}
  1221. * @constant
  1222. */
  1223. const IncrementStencilOp = 7682;
  1224. /**
  1225. * Decrements the current stencil buffer value. Clamps to `0`.
  1226. *
  1227. * @type {number}
  1228. * @constant
  1229. */
  1230. const DecrementStencilOp = 7683;
  1231. /**
  1232. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1233. * the maximum representable unsigned value.
  1234. *
  1235. * @type {number}
  1236. * @constant
  1237. */
  1238. const IncrementWrapStencilOp = 34055;
  1239. /**
  1240. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1241. * unsigned value when decrementing a stencil buffer value of `0`.
  1242. *
  1243. * @type {number}
  1244. * @constant
  1245. */
  1246. const DecrementWrapStencilOp = 34056;
  1247. /**
  1248. * Inverts the current stencil buffer value bitwise.
  1249. *
  1250. * @type {number}
  1251. * @constant
  1252. */
  1253. const InvertStencilOp = 5386;
  1254. /**
  1255. * Will never return true.
  1256. *
  1257. * @type {number}
  1258. * @constant
  1259. */
  1260. const NeverStencilFunc = 512;
  1261. /**
  1262. * Will return true if the stencil reference value is less than the current stencil value.
  1263. *
  1264. * @type {number}
  1265. * @constant
  1266. */
  1267. const LessStencilFunc = 513;
  1268. /**
  1269. * Will return true if the stencil reference value is equal to the current stencil value.
  1270. *
  1271. * @type {number}
  1272. * @constant
  1273. */
  1274. const EqualStencilFunc = 514;
  1275. /**
  1276. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1277. *
  1278. * @type {number}
  1279. * @constant
  1280. */
  1281. const LessEqualStencilFunc = 515;
  1282. /**
  1283. * Will return true if the stencil reference value is greater than the current stencil value.
  1284. *
  1285. * @type {number}
  1286. * @constant
  1287. */
  1288. const GreaterStencilFunc = 516;
  1289. /**
  1290. * Will return true if the stencil reference value is not equal to the current stencil value.
  1291. *
  1292. * @type {number}
  1293. * @constant
  1294. */
  1295. const NotEqualStencilFunc = 517;
  1296. /**
  1297. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1298. *
  1299. * @type {number}
  1300. * @constant
  1301. */
  1302. const GreaterEqualStencilFunc = 518;
  1303. /**
  1304. * Will always return true.
  1305. *
  1306. * @type {number}
  1307. * @constant
  1308. */
  1309. const AlwaysStencilFunc = 519;
  1310. /**
  1311. * Never pass.
  1312. *
  1313. * @type {number}
  1314. * @constant
  1315. */
  1316. const NeverCompare = 512;
  1317. /**
  1318. * Pass if the incoming value is less than the texture value.
  1319. *
  1320. * @type {number}
  1321. * @constant
  1322. */
  1323. const LessCompare = 513;
  1324. /**
  1325. * Pass if the incoming value equals the texture value.
  1326. *
  1327. * @type {number}
  1328. * @constant
  1329. */
  1330. const EqualCompare = 514;
  1331. /**
  1332. * Pass if the incoming value is less than or equal to the texture value.
  1333. *
  1334. * @type {number}
  1335. * @constant
  1336. */
  1337. const LessEqualCompare = 515;
  1338. /**
  1339. * Pass if the incoming value is greater than the texture value.
  1340. *
  1341. * @type {number}
  1342. * @constant
  1343. */
  1344. const GreaterCompare = 516;
  1345. /**
  1346. * Pass if the incoming value is not equal to the texture value.
  1347. *
  1348. * @type {number}
  1349. * @constant
  1350. */
  1351. const NotEqualCompare = 517;
  1352. /**
  1353. * Pass if the incoming value is greater than or equal to the texture value.
  1354. *
  1355. * @type {number}
  1356. * @constant
  1357. */
  1358. const GreaterEqualCompare = 518;
  1359. /**
  1360. * Always pass.
  1361. *
  1362. * @type {number}
  1363. * @constant
  1364. */
  1365. const AlwaysCompare = 519;
  1366. /**
  1367. * The contents are intended to be specified once by the application, and used many
  1368. * times as the source for drawing and image specification commands.
  1369. *
  1370. * @type {number}
  1371. * @constant
  1372. */
  1373. const StaticDrawUsage = 35044;
  1374. /**
  1375. * The contents are intended to be respecified repeatedly by the application, and
  1376. * used many times as the source for drawing and image specification commands.
  1377. *
  1378. * @type {number}
  1379. * @constant
  1380. */
  1381. const DynamicDrawUsage = 35048;
  1382. /**
  1383. * The contents are intended to be specified once by the application, and used at most
  1384. * a few times as the source for drawing and image specification commands.
  1385. *
  1386. * @type {number}
  1387. * @constant
  1388. */
  1389. const StreamDrawUsage = 35040;
  1390. /**
  1391. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1392. * many times by the application.
  1393. *
  1394. * @type {number}
  1395. * @constant
  1396. */
  1397. const StaticReadUsage = 35045;
  1398. /**
  1399. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1400. * many times by the application.
  1401. *
  1402. * @type {number}
  1403. * @constant
  1404. */
  1405. const DynamicReadUsage = 35049;
  1406. /**
  1407. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1408. * a few times by the application
  1409. *
  1410. * @type {number}
  1411. * @constant
  1412. */
  1413. const StreamReadUsage = 35041;
  1414. /**
  1415. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1416. * the source for WebGL drawing and image specification commands.
  1417. *
  1418. * @type {number}
  1419. * @constant
  1420. */
  1421. const StaticCopyUsage = 35046;
  1422. /**
  1423. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1424. * as the source for WebGL drawing and image specification commands.
  1425. *
  1426. * @type {number}
  1427. * @constant
  1428. */
  1429. const DynamicCopyUsage = 35050;
  1430. /**
  1431. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1432. * as the source for WebGL drawing and image specification commands.
  1433. *
  1434. * @type {number}
  1435. * @constant
  1436. */
  1437. const StreamCopyUsage = 35042;
  1438. /**
  1439. * GLSL 1 shader code.
  1440. *
  1441. * @type {string}
  1442. * @constant
  1443. */
  1444. const GLSL1 = '100';
  1445. /**
  1446. * GLSL 3 shader code.
  1447. *
  1448. * @type {string}
  1449. * @constant
  1450. */
  1451. const GLSL3 = '300 es';
  1452. /**
  1453. * WebGL coordinate system.
  1454. *
  1455. * @type {number}
  1456. * @constant
  1457. */
  1458. const WebGLCoordinateSystem = 2000;
  1459. /**
  1460. * WebGPU coordinate system.
  1461. *
  1462. * @type {number}
  1463. * @constant
  1464. */
  1465. const WebGPUCoordinateSystem = 2001;
  1466. /**
  1467. * Represents the different timestamp query types.
  1468. *
  1469. * @type {ConstantsTimestampQuery}
  1470. * @constant
  1471. */
  1472. const TimestampQuery = {
  1473. COMPUTE: 'compute',
  1474. RENDER: 'render'
  1475. };
  1476. /**
  1477. * Represents mouse buttons and interaction types in context of controls.
  1478. *
  1479. * @type {ConstantsInterpolationSamplingType}
  1480. * @constant
  1481. */
  1482. const InterpolationSamplingType = {
  1483. PERSPECTIVE: 'perspective',
  1484. LINEAR: 'linear',
  1485. FLAT: 'flat'
  1486. };
  1487. /**
  1488. * Represents the different interpolation sampling modes.
  1489. *
  1490. * @type {ConstantsInterpolationSamplingMode}
  1491. * @constant
  1492. */
  1493. const InterpolationSamplingMode = {
  1494. NORMAL: 'normal',
  1495. CENTROID: 'centroid',
  1496. SAMPLE: 'sample',
  1497. FIRST: 'first',
  1498. EITHER: 'either'
  1499. };
  1500. /**
  1501. * Compatibility flags for features that may not be supported across all platforms.
  1502. *
  1503. * @type {Object}
  1504. * @constant
  1505. */
  1506. const Compatibility = {
  1507. TEXTURE_COMPARE: 'depthTextureCompare'
  1508. };
  1509. /**
  1510. * This type represents mouse buttons and interaction types in context of controls.
  1511. *
  1512. * @typedef {Object} ConstantsMouse
  1513. * @property {number} MIDDLE - The left mouse button.
  1514. * @property {number} LEFT - The middle mouse button.
  1515. * @property {number} RIGHT - The right mouse button.
  1516. * @property {number} ROTATE - A rotate interaction.
  1517. * @property {number} DOLLY - A dolly interaction.
  1518. * @property {number} PAN - A pan interaction.
  1519. **/
  1520. /**
  1521. * This type represents touch interaction types in context of controls.
  1522. *
  1523. * @typedef {Object} ConstantsTouch
  1524. * @property {number} ROTATE - A rotate interaction.
  1525. * @property {number} PAN - A pan interaction.
  1526. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1527. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1528. **/
  1529. /**
  1530. * This type represents the different timestamp query types.
  1531. *
  1532. * @typedef {Object} ConstantsTimestampQuery
  1533. * @property {string} COMPUTE - A `compute` timestamp query.
  1534. * @property {string} RENDER - A `render` timestamp query.
  1535. **/
  1536. /**
  1537. * Represents the different interpolation sampling types.
  1538. *
  1539. * @typedef {Object} ConstantsInterpolationSamplingType
  1540. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1541. * @property {string} LINEAR - Linear interpolation.
  1542. * @property {string} FLAT - Flat interpolation.
  1543. */
  1544. /**
  1545. * Represents the different interpolation sampling modes.
  1546. *
  1547. * @typedef {Object} ConstantsInterpolationSamplingMode
  1548. * @property {string} NORMAL - Normal sampling mode.
  1549. * @property {string} CENTROID - Centroid sampling mode.
  1550. * @property {string} SAMPLE - Sample-specific sampling mode.
  1551. * @property {string} FIRST - Flat interpolation using the first vertex.
  1552. * @property {string} EITHER - Flat interpolation using either vertex.
  1553. */
  1554. /**
  1555. * Checks if an array contains values that require Uint32 representation.
  1556. *
  1557. * This function determines whether the array contains any values >= 65535,
  1558. * which would require a Uint32Array rather than a Uint16Array for proper storage.
  1559. * The function iterates from the end of the array, assuming larger values are
  1560. * typically located at the end.
  1561. *
  1562. * @private
  1563. * @param {Array<number>} array - The array to check.
  1564. * @return {boolean} True if the array contains values >= 65535, false otherwise.
  1565. */
  1566. function arrayNeedsUint32( array ) {
  1567. // assumes larger values usually on last
  1568. for ( let i = array.length - 1; i >= 0; -- i ) {
  1569. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1570. }
  1571. return false;
  1572. }
  1573. /**
  1574. * Map of typed array constructor names to their constructors.
  1575. * This mapping enables dynamic creation of typed arrays based on string type names.
  1576. *
  1577. * @private
  1578. * @constant
  1579. * @type {Object<string, TypedArrayConstructor>}
  1580. */
  1581. const TYPED_ARRAYS = {
  1582. Int8Array: Int8Array,
  1583. Uint8Array: Uint8Array,
  1584. Uint8ClampedArray: Uint8ClampedArray,
  1585. Int16Array: Int16Array,
  1586. Uint16Array: Uint16Array,
  1587. Int32Array: Int32Array,
  1588. Uint32Array: Uint32Array,
  1589. Float32Array: Float32Array,
  1590. Float64Array: Float64Array
  1591. };
  1592. /**
  1593. * Creates a typed array of the specified type from the given buffer.
  1594. *
  1595. * @private
  1596. * @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array').
  1597. * @param {ArrayBuffer} buffer - The buffer to create the typed array from.
  1598. * @return {TypedArray} A new typed array of the specified type.
  1599. */
  1600. function getTypedArray( type, buffer ) {
  1601. return new TYPED_ARRAYS[ type ]( buffer );
  1602. }
  1603. /**
  1604. * Returns `true` if the given object is a typed array.
  1605. *
  1606. * @param {any} array - The object to check.
  1607. * @return {boolean} Whether the given object is a typed array.
  1608. */
  1609. function isTypedArray( array ) {
  1610. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1611. }
  1612. /**
  1613. * Creates an XHTML element with the specified tag name.
  1614. *
  1615. * This function uses the XHTML namespace to create DOM elements,
  1616. * ensuring proper element creation in XML-based contexts.
  1617. *
  1618. * @private
  1619. * @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div').
  1620. * @return {HTMLElement} The created XHTML element.
  1621. */
  1622. function createElementNS( name ) {
  1623. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1624. }
  1625. /**
  1626. * Creates a canvas element configured for block display.
  1627. *
  1628. * This is a convenience function that creates a canvas element with
  1629. * display style set to 'block', which is commonly used in three.js
  1630. * rendering contexts to avoid inline element spacing issues.
  1631. *
  1632. * @return {HTMLCanvasElement} A canvas element with display set to 'block'.
  1633. */
  1634. function createCanvasElement() {
  1635. const canvas = createElementNS( 'canvas' );
  1636. canvas.style.display = 'block';
  1637. return canvas;
  1638. }
  1639. /**
  1640. * Internal cache for tracking warning messages to prevent duplicate warnings.
  1641. *
  1642. * @private
  1643. * @type {Object<string, boolean>}
  1644. */
  1645. const _cache = {};
  1646. /**
  1647. * Custom console function handler for intercepting log, warn, and error calls.
  1648. *
  1649. * @private
  1650. * @type {Function|null}
  1651. */
  1652. let _setConsoleFunction = null;
  1653. /**
  1654. * Sets a custom function to handle console output.
  1655. *
  1656. * This allows external code to intercept and handle console.log, console.warn,
  1657. * and console.error calls made by three.js, which is useful for custom logging,
  1658. * testing, or debugging workflows.
  1659. *
  1660. * @param {Function} fn - The function to handle console output. Should accept
  1661. * (type, message, ...params) where type is 'log', 'warn', or 'error'.
  1662. */
  1663. function setConsoleFunction( fn ) {
  1664. _setConsoleFunction = fn;
  1665. }
  1666. /**
  1667. * Gets the currently set custom console function.
  1668. *
  1669. * @return {Function|null} The custom console function, or null if not set.
  1670. */
  1671. function getConsoleFunction() {
  1672. return _setConsoleFunction;
  1673. }
  1674. /**
  1675. * Logs an informational message with the 'THREE.' prefix.
  1676. *
  1677. * If a custom console function is set via setConsoleFunction(), it will be used
  1678. * instead of the native console.log. The first parameter is treated as the
  1679. * method name and is automatically prefixed with 'THREE.'.
  1680. *
  1681. * @param {...any} params - The message components. The first param is used as
  1682. * the method name and prefixed with 'THREE.'.
  1683. */
  1684. function log( ...params ) {
  1685. const message = 'THREE.' + params.shift();
  1686. if ( _setConsoleFunction ) {
  1687. _setConsoleFunction( 'log', message, ...params );
  1688. } else {
  1689. console.log( message, ...params );
  1690. }
  1691. }
  1692. /**
  1693. * Enhances log/warn/error messages related to TSL.
  1694. *
  1695. * @param {Array<any>} params - The original message parameters.
  1696. * @returns {Array<any>} The filtered and enhanced message parameters.
  1697. */
  1698. function enhanceLogMessage( params ) {
  1699. const message = params[ 0 ];
  1700. if ( typeof message === 'string' && message.startsWith( 'TSL:' ) ) {
  1701. const stackTrace = params[ 1 ];
  1702. if ( stackTrace && stackTrace.isStackTrace ) {
  1703. params[ 0 ] += ' ' + stackTrace.getLocation();
  1704. } else {
  1705. params[ 1 ] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.';
  1706. }
  1707. }
  1708. return params;
  1709. }
  1710. /**
  1711. * Logs a warning message with the 'THREE.' prefix.
  1712. *
  1713. * If a custom console function is set via setConsoleFunction(), it will be used
  1714. * instead of the native console.warn. The first parameter is treated as the
  1715. * method name and is automatically prefixed with 'THREE.'.
  1716. *
  1717. * @param {...any} params - The message components. The first param is used as
  1718. * the method name and prefixed with 'THREE.'.
  1719. */
  1720. function warn( ...params ) {
  1721. params = enhanceLogMessage( params );
  1722. const message = 'THREE.' + params.shift();
  1723. if ( _setConsoleFunction ) {
  1724. _setConsoleFunction( 'warn', message, ...params );
  1725. } else {
  1726. const stackTrace = params[ 0 ];
  1727. if ( stackTrace && stackTrace.isStackTrace ) {
  1728. console.warn( stackTrace.getError( message ) );
  1729. } else {
  1730. console.warn( message, ...params );
  1731. }
  1732. }
  1733. }
  1734. /**
  1735. * Logs an error message with the 'THREE.' prefix.
  1736. *
  1737. * If a custom console function is set via setConsoleFunction(), it will be used
  1738. * instead of the native console.error. The first parameter is treated as the
  1739. * method name and is automatically prefixed with 'THREE.'.
  1740. *
  1741. * @param {...any} params - The message components. The first param is used as
  1742. * the method name and prefixed with 'THREE.'.
  1743. */
  1744. function error( ...params ) {
  1745. params = enhanceLogMessage( params );
  1746. const message = 'THREE.' + params.shift();
  1747. if ( _setConsoleFunction ) {
  1748. _setConsoleFunction( 'error', message, ...params );
  1749. } else {
  1750. const stackTrace = params[ 0 ];
  1751. if ( stackTrace && stackTrace.isStackTrace ) {
  1752. console.error( stackTrace.getError( message ) );
  1753. } else {
  1754. console.error( message, ...params );
  1755. }
  1756. }
  1757. }
  1758. /**
  1759. * Logs a warning message only once, preventing duplicate warnings.
  1760. *
  1761. * This function maintains an internal cache of warning messages and will only
  1762. * output each unique warning message once. Useful for warnings that may be
  1763. * triggered repeatedly but should only be shown to the user once.
  1764. *
  1765. * @param {...any} params - The warning message components.
  1766. */
  1767. function warnOnce( ...params ) {
  1768. const message = params.join( ' ' );
  1769. if ( message in _cache ) return;
  1770. _cache[ message ] = true;
  1771. warn( ...params );
  1772. }
  1773. /**
  1774. * Yields execution to the main thread to allow rendering and other tasks.
  1775. * Uses scheduler.yield() when available (Chrome 115+), falls back to requestAnimationFrame.
  1776. *
  1777. * @return {Promise<void>}
  1778. */
  1779. function yieldToMain() {
  1780. if ( typeof self !== 'undefined' && typeof self.scheduler !== 'undefined' && typeof self.scheduler.yield !== 'undefined' ) {
  1781. return self.scheduler.yield();
  1782. }
  1783. return new Promise( resolve => {
  1784. requestAnimationFrame( resolve );
  1785. } );
  1786. }
  1787. /**
  1788. * Asynchronously probes for WebGL sync object completion.
  1789. *
  1790. * This function creates a promise that resolves when the WebGL sync object
  1791. * signals completion or rejects if the sync operation fails. It uses polling
  1792. * at the specified interval to check the sync status without blocking the
  1793. * main thread. This is useful for GPU-CPU synchronization in WebGL contexts.
  1794. *
  1795. * @private
  1796. * @param {WebGL2RenderingContext} gl - The WebGL rendering context.
  1797. * @param {WebGLSync} sync - The WebGL sync object to wait for.
  1798. * @param {number} interval - The polling interval in milliseconds.
  1799. * @return {Promise<void>} A promise that resolves when the sync completes or rejects if it fails.
  1800. */
  1801. function probeAsync( gl, sync, interval ) {
  1802. return new Promise( function ( resolve, reject ) {
  1803. function probe() {
  1804. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1805. case gl.WAIT_FAILED:
  1806. reject();
  1807. break;
  1808. case gl.TIMEOUT_EXPIRED:
  1809. setTimeout( probe, interval );
  1810. break;
  1811. default:
  1812. resolve();
  1813. }
  1814. }
  1815. setTimeout( probe, interval );
  1816. } );
  1817. }
  1818. /**
  1819. * Used to select the correct depth functions
  1820. * when reversed depth buffer is used.
  1821. *
  1822. * @private
  1823. * @type {Object}
  1824. */
  1825. const ReversedDepthFuncs = {
  1826. [ NeverDepth ]: AlwaysDepth,
  1827. [ LessDepth ]: GreaterDepth,
  1828. [ EqualDepth ]: NotEqualDepth,
  1829. [ LessEqualDepth ]: GreaterEqualDepth,
  1830. [ AlwaysDepth ]: NeverDepth,
  1831. [ GreaterDepth ]: LessDepth,
  1832. [ NotEqualDepth ]: EqualDepth,
  1833. [ GreaterEqualDepth ]: LessEqualDepth,
  1834. };
  1835. /**
  1836. * This modules allows to dispatch event objects on custom JavaScript objects.
  1837. *
  1838. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1839. *
  1840. * Code Example:
  1841. * ```js
  1842. * class Car extends EventDispatcher {
  1843. * start() {
  1844. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1845. * }
  1846. *};
  1847. *
  1848. * // Using events with the custom object
  1849. * const car = new Car();
  1850. * car.addEventListener( 'start', function ( event ) {
  1851. * alert( event.message );
  1852. * } );
  1853. *
  1854. * car.start();
  1855. * ```
  1856. */
  1857. class EventDispatcher {
  1858. /**
  1859. * Adds the given event listener to the given event type.
  1860. *
  1861. * @param {string} type - The type of event to listen to.
  1862. * @param {Function} listener - The function that gets called when the event is fired.
  1863. */
  1864. addEventListener( type, listener ) {
  1865. if ( this._listeners === undefined ) this._listeners = {};
  1866. const listeners = this._listeners;
  1867. if ( listeners[ type ] === undefined ) {
  1868. listeners[ type ] = [];
  1869. }
  1870. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1871. listeners[ type ].push( listener );
  1872. }
  1873. }
  1874. /**
  1875. * Returns `true` if the given event listener has been added to the given event type.
  1876. *
  1877. * @param {string} type - The type of event.
  1878. * @param {Function} listener - The listener to check.
  1879. * @return {boolean} Whether the given event listener has been added to the given event type.
  1880. */
  1881. hasEventListener( type, listener ) {
  1882. const listeners = this._listeners;
  1883. if ( listeners === undefined ) return false;
  1884. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1885. }
  1886. /**
  1887. * Removes the given event listener from the given event type.
  1888. *
  1889. * @param {string} type - The type of event.
  1890. * @param {Function} listener - The listener to remove.
  1891. */
  1892. removeEventListener( type, listener ) {
  1893. const listeners = this._listeners;
  1894. if ( listeners === undefined ) return;
  1895. const listenerArray = listeners[ type ];
  1896. if ( listenerArray !== undefined ) {
  1897. const index = listenerArray.indexOf( listener );
  1898. if ( index !== -1 ) {
  1899. listenerArray.splice( index, 1 );
  1900. }
  1901. }
  1902. }
  1903. /**
  1904. * Dispatches an event object.
  1905. *
  1906. * @param {Object} event - The event that gets fired.
  1907. */
  1908. dispatchEvent( event ) {
  1909. const listeners = this._listeners;
  1910. if ( listeners === undefined ) return;
  1911. const listenerArray = listeners[ event.type ];
  1912. if ( listenerArray !== undefined ) {
  1913. event.target = this;
  1914. // Make a copy, in case listeners are removed while iterating.
  1915. const array = listenerArray.slice( 0 );
  1916. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1917. array[ i ].call( this, event );
  1918. }
  1919. event.target = null;
  1920. }
  1921. }
  1922. }
  1923. 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' ];
  1924. let _seed = 1234567;
  1925. const DEG2RAD = Math.PI / 180;
  1926. const RAD2DEG = 180 / Math.PI;
  1927. /**
  1928. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1929. * (universally unique identifier).
  1930. *
  1931. * @return {string} The UUID.
  1932. */
  1933. function generateUUID() {
  1934. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1935. const d0 = Math.random() * 0xffffffff | 0;
  1936. const d1 = Math.random() * 0xffffffff | 0;
  1937. const d2 = Math.random() * 0xffffffff | 0;
  1938. const d3 = Math.random() * 0xffffffff | 0;
  1939. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1940. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1941. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1942. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1943. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1944. return uuid.toLowerCase();
  1945. }
  1946. /**
  1947. * Clamps the given value between min and max.
  1948. *
  1949. * @param {number} value - The value to clamp.
  1950. * @param {number} min - The min value.
  1951. * @param {number} max - The max value.
  1952. * @return {number} The clamped value.
  1953. */
  1954. function clamp( value, min, max ) {
  1955. return Math.max( min, Math.min( max, value ) );
  1956. }
  1957. /**
  1958. * Computes the Euclidean modulo of the given parameters that
  1959. * is `( ( n % m ) + m ) % m`.
  1960. *
  1961. * @param {number} n - The first parameter.
  1962. * @param {number} m - The second parameter.
  1963. * @return {number} The Euclidean modulo.
  1964. */
  1965. function euclideanModulo( n, m ) {
  1966. // https://en.wikipedia.org/wiki/Modulo_operation
  1967. return ( ( n % m ) + m ) % m;
  1968. }
  1969. /**
  1970. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1971. * for the given value. `a2` must be greater than `a1`.
  1972. *
  1973. * @param {number} x - The value to be mapped.
  1974. * @param {number} a1 - Minimum value for range A.
  1975. * @param {number} a2 - Maximum value for range A.
  1976. * @param {number} b1 - Minimum value for range B.
  1977. * @param {number} b2 - Maximum value for range B.
  1978. * @return {number} The mapped value.
  1979. */
  1980. function mapLinear( x, a1, a2, b1, b2 ) {
  1981. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1982. }
  1983. /**
  1984. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1985. * between the start and end point.
  1986. *
  1987. * @param {number} x - The start point
  1988. * @param {number} y - The end point.
  1989. * @param {number} value - A value between start and end.
  1990. * @return {number} The interpolation factor.
  1991. */
  1992. function inverseLerp( x, y, value ) {
  1993. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1994. if ( x !== y ) {
  1995. return ( value - x ) / ( y - x );
  1996. } else {
  1997. return 0;
  1998. }
  1999. }
  2000. /**
  2001. * Returns a value linearly interpolated from two known points based on the given interval -
  2002. * `t = 0` will return `x` and `t = 1` will return `y`.
  2003. *
  2004. * @param {number} x - The start point
  2005. * @param {number} y - The end point.
  2006. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2007. * @return {number} The interpolated value.
  2008. */
  2009. function lerp( x, y, t ) {
  2010. return ( 1 - t ) * x + t * y;
  2011. }
  2012. /**
  2013. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2014. * time to maintain frame rate independent movement. For details, see
  2015. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2016. *
  2017. * @param {number} x - The current point.
  2018. * @param {number} y - The target point.
  2019. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2020. * and a lower value will make the movement more gradual.
  2021. * @param {number} dt - Delta time in seconds.
  2022. * @return {number} The interpolated value.
  2023. */
  2024. function damp( x, y, lambda, dt ) {
  2025. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  2026. }
  2027. /**
  2028. * Returns a value that alternates between `0` and the given `length` parameter.
  2029. *
  2030. * @param {number} x - The value to pingpong.
  2031. * @param {number} [length=1] - The positive value the function will pingpong to.
  2032. * @return {number} The alternated value.
  2033. */
  2034. function pingpong( x, length = 1 ) {
  2035. // https://www.desmos.com/calculator/vcsjnyz7x4
  2036. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  2037. }
  2038. /**
  2039. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2040. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2041. * the `min` and `max`.
  2042. *
  2043. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2044. *
  2045. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2046. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2047. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2048. * @return {number} The alternated value.
  2049. */
  2050. function smoothstep( x, min, max ) {
  2051. if ( x <= min ) return 0;
  2052. if ( x >= max ) return 1;
  2053. x = ( x - min ) / ( max - min );
  2054. return x * x * ( 3 - 2 * x );
  2055. }
  2056. /**
  2057. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2058. * that has zero 1st and 2nd order derivatives at `x=0` and `x=1`.
  2059. *
  2060. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2061. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2062. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2063. * @return {number} The alternated value.
  2064. */
  2065. function smootherstep( x, min, max ) {
  2066. if ( x <= min ) return 0;
  2067. if ( x >= max ) return 1;
  2068. x = ( x - min ) / ( max - min );
  2069. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  2070. }
  2071. /**
  2072. * Returns a random integer from `<low, high>` interval.
  2073. *
  2074. * @param {number} low - The lower value boundary.
  2075. * @param {number} high - The upper value boundary
  2076. * @return {number} A random integer.
  2077. */
  2078. function randInt( low, high ) {
  2079. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2080. }
  2081. /**
  2082. * Returns a random float from `<low, high>` interval.
  2083. *
  2084. * @param {number} low - The lower value boundary.
  2085. * @param {number} high - The upper value boundary
  2086. * @return {number} A random float.
  2087. */
  2088. function randFloat( low, high ) {
  2089. return low + Math.random() * ( high - low );
  2090. }
  2091. /**
  2092. * Returns a random integer from `<-range/2, range/2>` interval.
  2093. *
  2094. * @param {number} range - Defines the value range.
  2095. * @return {number} A random float.
  2096. */
  2097. function randFloatSpread( range ) {
  2098. return range * ( 0.5 - Math.random() );
  2099. }
  2100. /**
  2101. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2102. *
  2103. * @param {number} [s] - The integer seed.
  2104. * @return {number} A random float.
  2105. */
  2106. function seededRandom( s ) {
  2107. if ( s !== undefined ) _seed = s;
  2108. // Mulberry32 generator
  2109. let t = _seed += 0x6D2B79F5;
  2110. t = Math.imul( t ^ t >>> 15, t | 1 );
  2111. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  2112. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  2113. }
  2114. /**
  2115. * Converts degrees to radians.
  2116. *
  2117. * @param {number} degrees - A value in degrees.
  2118. * @return {number} The converted value in radians.
  2119. */
  2120. function degToRad( degrees ) {
  2121. return degrees * DEG2RAD;
  2122. }
  2123. /**
  2124. * Converts radians to degrees.
  2125. *
  2126. * @param {number} radians - A value in radians.
  2127. * @return {number} The converted value in degrees.
  2128. */
  2129. function radToDeg( radians ) {
  2130. return radians * RAD2DEG;
  2131. }
  2132. /**
  2133. * Returns `true` if the given number is a power of two.
  2134. *
  2135. * @param {number} value - The value to check.
  2136. * @return {boolean} Whether the given number is a power of two or not.
  2137. */
  2138. function isPowerOfTwo( value ) {
  2139. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  2140. }
  2141. /**
  2142. * Returns the smallest power of two that is greater than or equal to the given number.
  2143. *
  2144. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2145. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2146. */
  2147. function ceilPowerOfTwo( value ) {
  2148. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  2149. }
  2150. /**
  2151. * Returns the largest power of two that is less than or equal to the given number.
  2152. *
  2153. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2154. * @return {number} The largest power of two that is less than or equal to the given number.
  2155. */
  2156. function floorPowerOfTwo( value ) {
  2157. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  2158. }
  2159. /**
  2160. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2161. * defined by the given angles and order.
  2162. *
  2163. * Rotations are applied to the axes in the order specified by order:
  2164. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2165. *
  2166. * @param {Quaternion} q - The quaternion to set.
  2167. * @param {number} a - The rotation applied to the first axis, in radians.
  2168. * @param {number} b - The rotation applied to the second axis, in radians.
  2169. * @param {number} c - The rotation applied to the third axis, in radians.
  2170. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2171. */
  2172. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  2173. const cos = Math.cos;
  2174. const sin = Math.sin;
  2175. const c2 = cos( b / 2 );
  2176. const s2 = sin( b / 2 );
  2177. const c13 = cos( ( a + c ) / 2 );
  2178. const s13 = sin( ( a + c ) / 2 );
  2179. const c1_3 = cos( ( a - c ) / 2 );
  2180. const s1_3 = sin( ( a - c ) / 2 );
  2181. const c3_1 = cos( ( c - a ) / 2 );
  2182. const s3_1 = sin( ( c - a ) / 2 );
  2183. switch ( order ) {
  2184. case 'XYX':
  2185. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  2186. break;
  2187. case 'YZY':
  2188. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  2189. break;
  2190. case 'ZXZ':
  2191. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  2192. break;
  2193. case 'XZX':
  2194. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  2195. break;
  2196. case 'YXY':
  2197. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  2198. break;
  2199. case 'ZYZ':
  2200. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  2201. break;
  2202. default:
  2203. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2204. }
  2205. }
  2206. /**
  2207. * Denormalizes the given value according to the given typed array.
  2208. *
  2209. * @param {number} value - The value to denormalize.
  2210. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2211. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2212. */
  2213. function denormalize( value, array ) {
  2214. switch ( array.constructor ) {
  2215. case Float32Array:
  2216. return value;
  2217. case Uint32Array:
  2218. return value / 4294967295.0;
  2219. case Uint16Array:
  2220. return value / 65535.0;
  2221. case Uint8Array:
  2222. return value / 255.0;
  2223. case Int32Array:
  2224. return Math.max( value / 2147483647.0, -1 );
  2225. case Int16Array:
  2226. return Math.max( value / 32767.0, -1 );
  2227. case Int8Array:
  2228. return Math.max( value / 127.0, -1 );
  2229. default:
  2230. throw new Error( 'Invalid component type.' );
  2231. }
  2232. }
  2233. /**
  2234. * Normalizes the given value according to the given typed array.
  2235. *
  2236. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2237. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2238. * @return {number} The normalize value.
  2239. */
  2240. function normalize( value, array ) {
  2241. switch ( array.constructor ) {
  2242. case Float32Array:
  2243. return value;
  2244. case Uint32Array:
  2245. return Math.round( value * 4294967295.0 );
  2246. case Uint16Array:
  2247. return Math.round( value * 65535.0 );
  2248. case Uint8Array:
  2249. return Math.round( value * 255.0 );
  2250. case Int32Array:
  2251. return Math.round( value * 2147483647.0 );
  2252. case Int16Array:
  2253. return Math.round( value * 32767.0 );
  2254. case Int8Array:
  2255. return Math.round( value * 127.0 );
  2256. default:
  2257. throw new Error( 'Invalid component type.' );
  2258. }
  2259. }
  2260. /**
  2261. * @class
  2262. * @classdesc A collection of math utility functions.
  2263. * @hideconstructor
  2264. */
  2265. const MathUtils = {
  2266. DEG2RAD: DEG2RAD,
  2267. RAD2DEG: RAD2DEG,
  2268. /**
  2269. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2270. * (universally unique identifier).
  2271. *
  2272. * @static
  2273. * @method
  2274. * @return {string} The UUID.
  2275. */
  2276. generateUUID: generateUUID,
  2277. /**
  2278. * Clamps the given value between min and max.
  2279. *
  2280. * @static
  2281. * @method
  2282. * @param {number} value - The value to clamp.
  2283. * @param {number} min - The min value.
  2284. * @param {number} max - The max value.
  2285. * @return {number} The clamped value.
  2286. */
  2287. clamp: clamp,
  2288. /**
  2289. * Computes the Euclidean modulo of the given parameters that
  2290. * is `( ( n % m ) + m ) % m`.
  2291. *
  2292. * @static
  2293. * @method
  2294. * @param {number} n - The first parameter.
  2295. * @param {number} m - The second parameter.
  2296. * @return {number} The Euclidean modulo.
  2297. */
  2298. euclideanModulo: euclideanModulo,
  2299. /**
  2300. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2301. * for the given value.
  2302. *
  2303. * @static
  2304. * @method
  2305. * @param {number} x - The value to be mapped.
  2306. * @param {number} a1 - Minimum value for range A.
  2307. * @param {number} a2 - Maximum value for range A.
  2308. * @param {number} b1 - Minimum value for range B.
  2309. * @param {number} b2 - Maximum value for range B.
  2310. * @return {number} The mapped value.
  2311. */
  2312. mapLinear: mapLinear,
  2313. /**
  2314. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2315. * between the start and end point.
  2316. *
  2317. * @static
  2318. * @method
  2319. * @param {number} x - The start point
  2320. * @param {number} y - The end point.
  2321. * @param {number} value - A value between start and end.
  2322. * @return {number} The interpolation factor.
  2323. */
  2324. inverseLerp: inverseLerp,
  2325. /**
  2326. * Returns a value linearly interpolated from two known points based on the given interval -
  2327. * `t = 0` will return `x` and `t = 1` will return `y`.
  2328. *
  2329. * @static
  2330. * @method
  2331. * @param {number} x - The start point
  2332. * @param {number} y - The end point.
  2333. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2334. * @return {number} The interpolated value.
  2335. */
  2336. lerp: lerp,
  2337. /**
  2338. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2339. * time to maintain frame rate independent movement. For details, see
  2340. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2341. *
  2342. * @static
  2343. * @method
  2344. * @param {number} x - The current point.
  2345. * @param {number} y - The target point.
  2346. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2347. * and a lower value will make the movement more gradual.
  2348. * @param {number} dt - Delta time in seconds.
  2349. * @return {number} The interpolated value.
  2350. */
  2351. damp: damp,
  2352. /**
  2353. * Returns a value that alternates between `0` and the given `length` parameter.
  2354. *
  2355. * @static
  2356. * @method
  2357. * @param {number} x - The value to pingpong.
  2358. * @param {number} [length=1] - The positive value the function will pingpong to.
  2359. * @return {number} The alternated value.
  2360. */
  2361. pingpong: pingpong,
  2362. /**
  2363. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2364. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2365. * the `min` and `max`.
  2366. *
  2367. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2368. *
  2369. * @static
  2370. * @method
  2371. * @param {number} x - The value to evaluate based on its position between min and max.
  2372. * @param {number} min - The min value. Any x value below min will be `0`.
  2373. * @param {number} max - The max value. Any x value above max will be `1`.
  2374. * @return {number} The alternated value.
  2375. */
  2376. smoothstep: smoothstep,
  2377. /**
  2378. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2379. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2380. *
  2381. * @static
  2382. * @method
  2383. * @param {number} x - The value to evaluate based on its position between min and max.
  2384. * @param {number} min - The min value. Any x value below min will be `0`.
  2385. * @param {number} max - The max value. Any x value above max will be `1`.
  2386. * @return {number} The alternated value.
  2387. */
  2388. smootherstep: smootherstep,
  2389. /**
  2390. * Returns a random integer from `<low, high>` interval.
  2391. *
  2392. * @static
  2393. * @method
  2394. * @param {number} low - The lower value boundary.
  2395. * @param {number} high - The upper value boundary
  2396. * @return {number} A random integer.
  2397. */
  2398. randInt: randInt,
  2399. /**
  2400. * Returns a random float from `<low, high>` interval.
  2401. *
  2402. * @static
  2403. * @method
  2404. * @param {number} low - The lower value boundary.
  2405. * @param {number} high - The upper value boundary
  2406. * @return {number} A random float.
  2407. */
  2408. randFloat: randFloat,
  2409. /**
  2410. * Returns a random integer from `<-range/2, range/2>` interval.
  2411. *
  2412. * @static
  2413. * @method
  2414. * @param {number} range - Defines the value range.
  2415. * @return {number} A random float.
  2416. */
  2417. randFloatSpread: randFloatSpread,
  2418. /**
  2419. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2420. *
  2421. * @static
  2422. * @method
  2423. * @param {number} [s] - The integer seed.
  2424. * @return {number} A random float.
  2425. */
  2426. seededRandom: seededRandom,
  2427. /**
  2428. * Converts degrees to radians.
  2429. *
  2430. * @static
  2431. * @method
  2432. * @param {number} degrees - A value in degrees.
  2433. * @return {number} The converted value in radians.
  2434. */
  2435. degToRad: degToRad,
  2436. /**
  2437. * Converts radians to degrees.
  2438. *
  2439. * @static
  2440. * @method
  2441. * @param {number} radians - A value in radians.
  2442. * @return {number} The converted value in degrees.
  2443. */
  2444. radToDeg: radToDeg,
  2445. /**
  2446. * Returns `true` if the given number is a power of two.
  2447. *
  2448. * @static
  2449. * @method
  2450. * @param {number} value - The value to check.
  2451. * @return {boolean} Whether the given number is a power of two or not.
  2452. */
  2453. isPowerOfTwo: isPowerOfTwo,
  2454. /**
  2455. * Returns the smallest power of two that is greater than or equal to the given number.
  2456. *
  2457. * @static
  2458. * @method
  2459. * @param {number} value - The value to find a POT for.
  2460. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2461. */
  2462. ceilPowerOfTwo: ceilPowerOfTwo,
  2463. /**
  2464. * Returns the largest power of two that is less than or equal to the given number.
  2465. *
  2466. * @static
  2467. * @method
  2468. * @param {number} value - The value to find a POT for.
  2469. * @return {number} The largest power of two that is less than or equal to the given number.
  2470. */
  2471. floorPowerOfTwo: floorPowerOfTwo,
  2472. /**
  2473. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2474. * defined by the given angles and order.
  2475. *
  2476. * Rotations are applied to the axes in the order specified by order:
  2477. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2478. *
  2479. * @static
  2480. * @method
  2481. * @param {Quaternion} q - The quaternion to set.
  2482. * @param {number} a - The rotation applied to the first axis, in radians.
  2483. * @param {number} b - The rotation applied to the second axis, in radians.
  2484. * @param {number} c - The rotation applied to the third axis, in radians.
  2485. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2486. */
  2487. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2488. /**
  2489. * Normalizes the given value according to the given typed array.
  2490. *
  2491. * @static
  2492. * @method
  2493. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2494. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2495. * @return {number} The normalize value.
  2496. */
  2497. normalize: normalize,
  2498. /**
  2499. * Denormalizes the given value according to the given typed array.
  2500. *
  2501. * @static
  2502. * @method
  2503. * @param {number} value - The value to denormalize.
  2504. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2505. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2506. */
  2507. denormalize: denormalize
  2508. };
  2509. /**
  2510. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2511. * (labeled x and y), which can be used to represent a number of things, such as:
  2512. *
  2513. * - A point in 2D space (i.e. a position on a plane).
  2514. * - A direction and length across a plane. In three.js the length will
  2515. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2516. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2517. * - Any arbitrary ordered pair of numbers.
  2518. *
  2519. * There are other things a 2D vector can be used to represent, such as
  2520. * momentum vectors, complex numbers and so on, however these are the most
  2521. * common uses in three.js.
  2522. *
  2523. * Iterating through a vector instance will yield its components `(x, y)` in
  2524. * the corresponding order.
  2525. * ```js
  2526. * const a = new THREE.Vector2( 0, 1 );
  2527. *
  2528. * //no arguments; will be initialised to (0, 0)
  2529. * const b = new THREE.Vector2( );
  2530. *
  2531. * const d = a.distanceTo( b );
  2532. * ```
  2533. */
  2534. class Vector2 {
  2535. static {
  2536. /**
  2537. * This flag can be used for type testing.
  2538. *
  2539. * @type {boolean}
  2540. * @readonly
  2541. * @default true
  2542. */
  2543. Vector2.prototype.isVector2 = true;
  2544. }
  2545. /**
  2546. * Constructs a new 2D vector.
  2547. *
  2548. * @param {number} [x=0] - The x value of this vector.
  2549. * @param {number} [y=0] - The y value of this vector.
  2550. */
  2551. constructor( x = 0, y = 0 ) {
  2552. /**
  2553. * The x value of this vector.
  2554. *
  2555. * @type {number}
  2556. */
  2557. this.x = x;
  2558. /**
  2559. * The y value of this vector.
  2560. *
  2561. * @type {number}
  2562. */
  2563. this.y = y;
  2564. }
  2565. /**
  2566. * Alias for {@link Vector2#x}.
  2567. *
  2568. * @type {number}
  2569. */
  2570. get width() {
  2571. return this.x;
  2572. }
  2573. set width( value ) {
  2574. this.x = value;
  2575. }
  2576. /**
  2577. * Alias for {@link Vector2#y}.
  2578. *
  2579. * @type {number}
  2580. */
  2581. get height() {
  2582. return this.y;
  2583. }
  2584. set height( value ) {
  2585. this.y = value;
  2586. }
  2587. /**
  2588. * Sets the vector components.
  2589. *
  2590. * @param {number} x - The value of the x component.
  2591. * @param {number} y - The value of the y component.
  2592. * @return {Vector2} A reference to this vector.
  2593. */
  2594. set( x, y ) {
  2595. this.x = x;
  2596. this.y = y;
  2597. return this;
  2598. }
  2599. /**
  2600. * Sets the vector components to the same value.
  2601. *
  2602. * @param {number} scalar - The value to set for all vector components.
  2603. * @return {Vector2} A reference to this vector.
  2604. */
  2605. setScalar( scalar ) {
  2606. this.x = scalar;
  2607. this.y = scalar;
  2608. return this;
  2609. }
  2610. /**
  2611. * Sets the vector's x component to the given value
  2612. *
  2613. * @param {number} x - The value to set.
  2614. * @return {Vector2} A reference to this vector.
  2615. */
  2616. setX( x ) {
  2617. this.x = x;
  2618. return this;
  2619. }
  2620. /**
  2621. * Sets the vector's y component to the given value
  2622. *
  2623. * @param {number} y - The value to set.
  2624. * @return {Vector2} A reference to this vector.
  2625. */
  2626. setY( y ) {
  2627. this.y = y;
  2628. return this;
  2629. }
  2630. /**
  2631. * Allows to set a vector component with an index.
  2632. *
  2633. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2634. * @param {number} value - The value to set.
  2635. * @return {Vector2} A reference to this vector.
  2636. */
  2637. setComponent( index, value ) {
  2638. switch ( index ) {
  2639. case 0: this.x = value; break;
  2640. case 1: this.y = value; break;
  2641. default: throw new Error( 'index is out of range: ' + index );
  2642. }
  2643. return this;
  2644. }
  2645. /**
  2646. * Returns the value of the vector component which matches the given index.
  2647. *
  2648. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2649. * @return {number} A vector component value.
  2650. */
  2651. getComponent( index ) {
  2652. switch ( index ) {
  2653. case 0: return this.x;
  2654. case 1: return this.y;
  2655. default: throw new Error( 'index is out of range: ' + index );
  2656. }
  2657. }
  2658. /**
  2659. * Returns a new vector with copied values from this instance.
  2660. *
  2661. * @return {Vector2} A clone of this instance.
  2662. */
  2663. clone() {
  2664. return new this.constructor( this.x, this.y );
  2665. }
  2666. /**
  2667. * Copies the values of the given vector to this instance.
  2668. *
  2669. * @param {Vector2} v - The vector to copy.
  2670. * @return {Vector2} A reference to this vector.
  2671. */
  2672. copy( v ) {
  2673. this.x = v.x;
  2674. this.y = v.y;
  2675. return this;
  2676. }
  2677. /**
  2678. * Adds the given vector to this instance.
  2679. *
  2680. * @param {Vector2} v - The vector to add.
  2681. * @return {Vector2} A reference to this vector.
  2682. */
  2683. add( v ) {
  2684. this.x += v.x;
  2685. this.y += v.y;
  2686. return this;
  2687. }
  2688. /**
  2689. * Adds the given scalar value to all components of this instance.
  2690. *
  2691. * @param {number} s - The scalar to add.
  2692. * @return {Vector2} A reference to this vector.
  2693. */
  2694. addScalar( s ) {
  2695. this.x += s;
  2696. this.y += s;
  2697. return this;
  2698. }
  2699. /**
  2700. * Adds the given vectors and stores the result in this instance.
  2701. *
  2702. * @param {Vector2} a - The first vector.
  2703. * @param {Vector2} b - The second vector.
  2704. * @return {Vector2} A reference to this vector.
  2705. */
  2706. addVectors( a, b ) {
  2707. this.x = a.x + b.x;
  2708. this.y = a.y + b.y;
  2709. return this;
  2710. }
  2711. /**
  2712. * Adds the given vector scaled by the given factor to this instance.
  2713. *
  2714. * @param {Vector2} v - The vector.
  2715. * @param {number} s - The factor that scales `v`.
  2716. * @return {Vector2} A reference to this vector.
  2717. */
  2718. addScaledVector( v, s ) {
  2719. this.x += v.x * s;
  2720. this.y += v.y * s;
  2721. return this;
  2722. }
  2723. /**
  2724. * Subtracts the given vector from this instance.
  2725. *
  2726. * @param {Vector2} v - The vector to subtract.
  2727. * @return {Vector2} A reference to this vector.
  2728. */
  2729. sub( v ) {
  2730. this.x -= v.x;
  2731. this.y -= v.y;
  2732. return this;
  2733. }
  2734. /**
  2735. * Subtracts the given scalar value from all components of this instance.
  2736. *
  2737. * @param {number} s - The scalar to subtract.
  2738. * @return {Vector2} A reference to this vector.
  2739. */
  2740. subScalar( s ) {
  2741. this.x -= s;
  2742. this.y -= s;
  2743. return this;
  2744. }
  2745. /**
  2746. * Subtracts the given vectors and stores the result in this instance.
  2747. *
  2748. * @param {Vector2} a - The first vector.
  2749. * @param {Vector2} b - The second vector.
  2750. * @return {Vector2} A reference to this vector.
  2751. */
  2752. subVectors( a, b ) {
  2753. this.x = a.x - b.x;
  2754. this.y = a.y - b.y;
  2755. return this;
  2756. }
  2757. /**
  2758. * Multiplies the given vector with this instance.
  2759. *
  2760. * @param {Vector2} v - The vector to multiply.
  2761. * @return {Vector2} A reference to this vector.
  2762. */
  2763. multiply( v ) {
  2764. this.x *= v.x;
  2765. this.y *= v.y;
  2766. return this;
  2767. }
  2768. /**
  2769. * Multiplies the given scalar value with all components of this instance.
  2770. *
  2771. * @param {number} scalar - The scalar to multiply.
  2772. * @return {Vector2} A reference to this vector.
  2773. */
  2774. multiplyScalar( scalar ) {
  2775. this.x *= scalar;
  2776. this.y *= scalar;
  2777. return this;
  2778. }
  2779. /**
  2780. * Divides this instance by the given vector.
  2781. *
  2782. * @param {Vector2} v - The vector to divide.
  2783. * @return {Vector2} A reference to this vector.
  2784. */
  2785. divide( v ) {
  2786. this.x /= v.x;
  2787. this.y /= v.y;
  2788. return this;
  2789. }
  2790. /**
  2791. * Divides this vector by the given scalar.
  2792. *
  2793. * @param {number} scalar - The scalar to divide.
  2794. * @return {Vector2} A reference to this vector.
  2795. */
  2796. divideScalar( scalar ) {
  2797. return this.multiplyScalar( 1 / scalar );
  2798. }
  2799. /**
  2800. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2801. * the given 3x3 matrix.
  2802. *
  2803. * @param {Matrix3} m - The matrix to apply.
  2804. * @return {Vector2} A reference to this vector.
  2805. */
  2806. applyMatrix3( m ) {
  2807. const x = this.x, y = this.y;
  2808. const e = m.elements;
  2809. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2810. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2811. return this;
  2812. }
  2813. /**
  2814. * If this vector's x or y value is greater than the given vector's x or y
  2815. * value, replace that value with the corresponding min value.
  2816. *
  2817. * @param {Vector2} v - The vector.
  2818. * @return {Vector2} A reference to this vector.
  2819. */
  2820. min( v ) {
  2821. this.x = Math.min( this.x, v.x );
  2822. this.y = Math.min( this.y, v.y );
  2823. return this;
  2824. }
  2825. /**
  2826. * If this vector's x or y value is less than the given vector's x or y
  2827. * value, replace that value with the corresponding max value.
  2828. *
  2829. * @param {Vector2} v - The vector.
  2830. * @return {Vector2} A reference to this vector.
  2831. */
  2832. max( v ) {
  2833. this.x = Math.max( this.x, v.x );
  2834. this.y = Math.max( this.y, v.y );
  2835. return this;
  2836. }
  2837. /**
  2838. * If this vector's x or y value is greater than the max vector's x or y
  2839. * value, it is replaced by the corresponding value.
  2840. * If this vector's x or y value is less than the min vector's x or y value,
  2841. * it is replaced by the corresponding value.
  2842. *
  2843. * @param {Vector2} min - The minimum x and y values.
  2844. * @param {Vector2} max - The maximum x and y values in the desired range.
  2845. * @return {Vector2} A reference to this vector.
  2846. */
  2847. clamp( min, max ) {
  2848. // assumes min < max, componentwise
  2849. this.x = clamp( this.x, min.x, max.x );
  2850. this.y = clamp( this.y, min.y, max.y );
  2851. return this;
  2852. }
  2853. /**
  2854. * If this vector's x or y values are greater than the max value, they are
  2855. * replaced by the max value.
  2856. * If this vector's x or y values are less than the min value, they are
  2857. * replaced by the min value.
  2858. *
  2859. * @param {number} minVal - The minimum value the components will be clamped to.
  2860. * @param {number} maxVal - The maximum value the components will be clamped to.
  2861. * @return {Vector2} A reference to this vector.
  2862. */
  2863. clampScalar( minVal, maxVal ) {
  2864. this.x = clamp( this.x, minVal, maxVal );
  2865. this.y = clamp( this.y, minVal, maxVal );
  2866. return this;
  2867. }
  2868. /**
  2869. * If this vector's length is greater than the max value, it is replaced by
  2870. * the max value.
  2871. * If this vector's length is less than the min value, it is replaced by the
  2872. * min value.
  2873. *
  2874. * @param {number} min - The minimum value the vector length will be clamped to.
  2875. * @param {number} max - The maximum value the vector length will be clamped to.
  2876. * @return {Vector2} A reference to this vector.
  2877. */
  2878. clampLength( min, max ) {
  2879. const length = this.length();
  2880. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2881. }
  2882. /**
  2883. * The components of this vector are rounded down to the nearest integer value.
  2884. *
  2885. * @return {Vector2} A reference to this vector.
  2886. */
  2887. floor() {
  2888. this.x = Math.floor( this.x );
  2889. this.y = Math.floor( this.y );
  2890. return this;
  2891. }
  2892. /**
  2893. * The components of this vector are rounded up to the nearest integer value.
  2894. *
  2895. * @return {Vector2} A reference to this vector.
  2896. */
  2897. ceil() {
  2898. this.x = Math.ceil( this.x );
  2899. this.y = Math.ceil( this.y );
  2900. return this;
  2901. }
  2902. /**
  2903. * The components of this vector are rounded to the nearest integer value
  2904. *
  2905. * @return {Vector2} A reference to this vector.
  2906. */
  2907. round() {
  2908. this.x = Math.round( this.x );
  2909. this.y = Math.round( this.y );
  2910. return this;
  2911. }
  2912. /**
  2913. * The components of this vector are rounded towards zero (up if negative,
  2914. * down if positive) to an integer value.
  2915. *
  2916. * @return {Vector2} A reference to this vector.
  2917. */
  2918. roundToZero() {
  2919. this.x = Math.trunc( this.x );
  2920. this.y = Math.trunc( this.y );
  2921. return this;
  2922. }
  2923. /**
  2924. * Inverts this vector - i.e. sets x = -x and y = -y.
  2925. *
  2926. * @return {Vector2} A reference to this vector.
  2927. */
  2928. negate() {
  2929. this.x = - this.x;
  2930. this.y = - this.y;
  2931. return this;
  2932. }
  2933. /**
  2934. * Calculates the dot product of the given vector with this instance.
  2935. *
  2936. * @param {Vector2} v - The vector to compute the dot product with.
  2937. * @return {number} The result of the dot product.
  2938. */
  2939. dot( v ) {
  2940. return this.x * v.x + this.y * v.y;
  2941. }
  2942. /**
  2943. * Calculates the cross product of the given vector with this instance.
  2944. *
  2945. * @param {Vector2} v - The vector to compute the cross product with.
  2946. * @return {number} The result of the cross product.
  2947. */
  2948. cross( v ) {
  2949. return this.x * v.y - this.y * v.x;
  2950. }
  2951. /**
  2952. * Computes the square of the Euclidean length (straight-line length) from
  2953. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2954. * compare the length squared instead as it is slightly more efficient to calculate.
  2955. *
  2956. * @return {number} The square length of this vector.
  2957. */
  2958. lengthSq() {
  2959. return this.x * this.x + this.y * this.y;
  2960. }
  2961. /**
  2962. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2963. *
  2964. * @return {number} The length of this vector.
  2965. */
  2966. length() {
  2967. return Math.sqrt( this.x * this.x + this.y * this.y );
  2968. }
  2969. /**
  2970. * Computes the Manhattan length of this vector.
  2971. *
  2972. * @return {number} The length of this vector.
  2973. */
  2974. manhattanLength() {
  2975. return Math.abs( this.x ) + Math.abs( this.y );
  2976. }
  2977. /**
  2978. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2979. * with the same direction as this one, but with a vector length of `1`.
  2980. *
  2981. * @return {Vector2} A reference to this vector.
  2982. */
  2983. normalize() {
  2984. return this.divideScalar( this.length() || 1 );
  2985. }
  2986. /**
  2987. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2988. *
  2989. * @return {number} The angle in radians.
  2990. */
  2991. angle() {
  2992. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2993. return angle;
  2994. }
  2995. /**
  2996. * Returns the angle between the given vector and this instance in radians.
  2997. *
  2998. * @param {Vector2} v - The vector to compute the angle with.
  2999. * @return {number} The angle in radians.
  3000. */
  3001. angleTo( v ) {
  3002. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  3003. if ( denominator === 0 ) return Math.PI / 2;
  3004. const theta = this.dot( v ) / denominator;
  3005. // clamp, to handle numerical problems
  3006. return Math.acos( clamp( theta, -1, 1 ) );
  3007. }
  3008. /**
  3009. * Computes the distance from the given vector to this instance.
  3010. *
  3011. * @param {Vector2} v - The vector to compute the distance to.
  3012. * @return {number} The distance.
  3013. */
  3014. distanceTo( v ) {
  3015. return Math.sqrt( this.distanceToSquared( v ) );
  3016. }
  3017. /**
  3018. * Computes the squared distance from the given vector to this instance.
  3019. * If you are just comparing the distance with another distance, you should compare
  3020. * the distance squared instead as it is slightly more efficient to calculate.
  3021. *
  3022. * @param {Vector2} v - The vector to compute the squared distance to.
  3023. * @return {number} The squared distance.
  3024. */
  3025. distanceToSquared( v ) {
  3026. const dx = this.x - v.x, dy = this.y - v.y;
  3027. return dx * dx + dy * dy;
  3028. }
  3029. /**
  3030. * Computes the Manhattan distance from the given vector to this instance.
  3031. *
  3032. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  3033. * @return {number} The Manhattan distance.
  3034. */
  3035. manhattanDistanceTo( v ) {
  3036. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  3037. }
  3038. /**
  3039. * Sets this vector to a vector with the same direction as this one, but
  3040. * with the specified length.
  3041. *
  3042. * @param {number} length - The new length of this vector.
  3043. * @return {Vector2} A reference to this vector.
  3044. */
  3045. setLength( length ) {
  3046. return this.normalize().multiplyScalar( length );
  3047. }
  3048. /**
  3049. * Linearly interpolates between the given vector and this instance, where
  3050. * alpha is the percent distance along the line - alpha = 0 will be this
  3051. * vector, and alpha = 1 will be the given one.
  3052. *
  3053. * @param {Vector2} v - The vector to interpolate towards.
  3054. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3055. * @return {Vector2} A reference to this vector.
  3056. */
  3057. lerp( v, alpha ) {
  3058. this.x += ( v.x - this.x ) * alpha;
  3059. this.y += ( v.y - this.y ) * alpha;
  3060. return this;
  3061. }
  3062. /**
  3063. * Linearly interpolates between the given vectors, where alpha is the percent
  3064. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3065. * be the second one. The result is stored in this instance.
  3066. *
  3067. * @param {Vector2} v1 - The first vector.
  3068. * @param {Vector2} v2 - The second vector.
  3069. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3070. * @return {Vector2} A reference to this vector.
  3071. */
  3072. lerpVectors( v1, v2, alpha ) {
  3073. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3074. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3075. return this;
  3076. }
  3077. /**
  3078. * Returns `true` if this vector is equal with the given one.
  3079. *
  3080. * @param {Vector2} v - The vector to test for equality.
  3081. * @return {boolean} Whether this vector is equal with the given one.
  3082. */
  3083. equals( v ) {
  3084. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  3085. }
  3086. /**
  3087. * Sets this vector's x value to be `array[ offset ]` and y
  3088. * value to be `array[ offset + 1 ]`.
  3089. *
  3090. * @param {Array<number>} array - An array holding the vector component values.
  3091. * @param {number} [offset=0] - The offset into the array.
  3092. * @return {Vector2} A reference to this vector.
  3093. */
  3094. fromArray( array, offset = 0 ) {
  3095. this.x = array[ offset ];
  3096. this.y = array[ offset + 1 ];
  3097. return this;
  3098. }
  3099. /**
  3100. * Writes the components of this vector to the given array. If no array is provided,
  3101. * the method returns a new instance.
  3102. *
  3103. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3104. * @param {number} [offset=0] - Index of the first element in the array.
  3105. * @return {Array<number>} The vector components.
  3106. */
  3107. toArray( array = [], offset = 0 ) {
  3108. array[ offset ] = this.x;
  3109. array[ offset + 1 ] = this.y;
  3110. return array;
  3111. }
  3112. /**
  3113. * Sets the components of this vector from the given buffer attribute.
  3114. *
  3115. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3116. * @param {number} index - The index into the attribute.
  3117. * @return {Vector2} A reference to this vector.
  3118. */
  3119. fromBufferAttribute( attribute, index ) {
  3120. this.x = attribute.getX( index );
  3121. this.y = attribute.getY( index );
  3122. return this;
  3123. }
  3124. /**
  3125. * Rotates this vector around the given center by the given angle.
  3126. *
  3127. * @param {Vector2} center - The point around which to rotate.
  3128. * @param {number} angle - The angle to rotate, in radians.
  3129. * @return {Vector2} A reference to this vector.
  3130. */
  3131. rotateAround( center, angle ) {
  3132. const c = Math.cos( angle ), s = Math.sin( angle );
  3133. const x = this.x - center.x;
  3134. const y = this.y - center.y;
  3135. this.x = x * c - y * s + center.x;
  3136. this.y = x * s + y * c + center.y;
  3137. return this;
  3138. }
  3139. /**
  3140. * Sets each component of this vector to a pseudo-random value between `0` and
  3141. * `1`, excluding `1`.
  3142. *
  3143. * @return {Vector2} A reference to this vector.
  3144. */
  3145. random() {
  3146. this.x = Math.random();
  3147. this.y = Math.random();
  3148. return this;
  3149. }
  3150. *[ Symbol.iterator ]() {
  3151. yield this.x;
  3152. yield this.y;
  3153. }
  3154. }
  3155. /**
  3156. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3157. *
  3158. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3159. * the corresponding order.
  3160. *
  3161. * Note that three.js expects Quaternions to be normalized.
  3162. * ```js
  3163. * const quaternion = new THREE.Quaternion();
  3164. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3165. *
  3166. * const vector = new THREE.Vector3( 1, 0, 0 );
  3167. * vector.applyQuaternion( quaternion );
  3168. * ```
  3169. */
  3170. class Quaternion {
  3171. /**
  3172. * Constructs a new quaternion.
  3173. *
  3174. * @param {number} [x=0] - The x value of this quaternion.
  3175. * @param {number} [y=0] - The y value of this quaternion.
  3176. * @param {number} [z=0] - The z value of this quaternion.
  3177. * @param {number} [w=1] - The w value of this quaternion.
  3178. */
  3179. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3180. /**
  3181. * This flag can be used for type testing.
  3182. *
  3183. * @type {boolean}
  3184. * @readonly
  3185. * @default true
  3186. */
  3187. this.isQuaternion = true;
  3188. this._x = x;
  3189. this._y = y;
  3190. this._z = z;
  3191. this._w = w;
  3192. }
  3193. /**
  3194. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3195. * quaternion data are managed in flat arrays.
  3196. *
  3197. * @param {Array<number>} dst - The destination array.
  3198. * @param {number} dstOffset - An offset into the destination array.
  3199. * @param {Array<number>} src0 - The source array of the first quaternion.
  3200. * @param {number} srcOffset0 - An offset into the first source array.
  3201. * @param {Array<number>} src1 - The source array of the second quaternion.
  3202. * @param {number} srcOffset1 - An offset into the second source array.
  3203. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3204. * @see {@link Quaternion#slerp}
  3205. */
  3206. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3207. let x0 = src0[ srcOffset0 + 0 ],
  3208. y0 = src0[ srcOffset0 + 1 ],
  3209. z0 = src0[ srcOffset0 + 2 ],
  3210. w0 = src0[ srcOffset0 + 3 ];
  3211. let x1 = src1[ srcOffset1 + 0 ],
  3212. y1 = src1[ srcOffset1 + 1 ],
  3213. z1 = src1[ srcOffset1 + 2 ],
  3214. w1 = src1[ srcOffset1 + 3 ];
  3215. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3216. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3217. if ( dot < 0 ) {
  3218. x1 = - x1;
  3219. y1 = - y1;
  3220. z1 = - z1;
  3221. w1 = - w1;
  3222. dot = - dot;
  3223. }
  3224. let s = 1 - t;
  3225. if ( dot < 0.9995 ) {
  3226. // slerp
  3227. const theta = Math.acos( dot );
  3228. const sin = Math.sin( theta );
  3229. s = Math.sin( s * theta ) / sin;
  3230. t = Math.sin( t * theta ) / sin;
  3231. x0 = x0 * s + x1 * t;
  3232. y0 = y0 * s + y1 * t;
  3233. z0 = z0 * s + z1 * t;
  3234. w0 = w0 * s + w1 * t;
  3235. } else {
  3236. // for small angles, lerp then normalize
  3237. x0 = x0 * s + x1 * t;
  3238. y0 = y0 * s + y1 * t;
  3239. z0 = z0 * s + z1 * t;
  3240. w0 = w0 * s + w1 * t;
  3241. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3242. x0 *= f;
  3243. y0 *= f;
  3244. z0 *= f;
  3245. w0 *= f;
  3246. }
  3247. }
  3248. dst[ dstOffset ] = x0;
  3249. dst[ dstOffset + 1 ] = y0;
  3250. dst[ dstOffset + 2 ] = z0;
  3251. dst[ dstOffset + 3 ] = w0;
  3252. }
  3253. /**
  3254. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3255. * in flat arrays.
  3256. *
  3257. * @param {Array<number>} dst - The destination array.
  3258. * @param {number} dstOffset - An offset into the destination array.
  3259. * @param {Array<number>} src0 - The source array of the first quaternion.
  3260. * @param {number} srcOffset0 - An offset into the first source array.
  3261. * @param {Array<number>} src1 - The source array of the second quaternion.
  3262. * @param {number} srcOffset1 - An offset into the second source array.
  3263. * @return {Array<number>} The destination array.
  3264. * @see {@link Quaternion#multiplyQuaternions}.
  3265. */
  3266. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3267. const x0 = src0[ srcOffset0 ];
  3268. const y0 = src0[ srcOffset0 + 1 ];
  3269. const z0 = src0[ srcOffset0 + 2 ];
  3270. const w0 = src0[ srcOffset0 + 3 ];
  3271. const x1 = src1[ srcOffset1 ];
  3272. const y1 = src1[ srcOffset1 + 1 ];
  3273. const z1 = src1[ srcOffset1 + 2 ];
  3274. const w1 = src1[ srcOffset1 + 3 ];
  3275. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3276. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3277. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3278. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3279. return dst;
  3280. }
  3281. /**
  3282. * The x value of this quaternion.
  3283. *
  3284. * @type {number}
  3285. * @default 0
  3286. */
  3287. get x() {
  3288. return this._x;
  3289. }
  3290. set x( value ) {
  3291. this._x = value;
  3292. this._onChangeCallback();
  3293. }
  3294. /**
  3295. * The y value of this quaternion.
  3296. *
  3297. * @type {number}
  3298. * @default 0
  3299. */
  3300. get y() {
  3301. return this._y;
  3302. }
  3303. set y( value ) {
  3304. this._y = value;
  3305. this._onChangeCallback();
  3306. }
  3307. /**
  3308. * The z value of this quaternion.
  3309. *
  3310. * @type {number}
  3311. * @default 0
  3312. */
  3313. get z() {
  3314. return this._z;
  3315. }
  3316. set z( value ) {
  3317. this._z = value;
  3318. this._onChangeCallback();
  3319. }
  3320. /**
  3321. * The w value of this quaternion.
  3322. *
  3323. * @type {number}
  3324. * @default 1
  3325. */
  3326. get w() {
  3327. return this._w;
  3328. }
  3329. set w( value ) {
  3330. this._w = value;
  3331. this._onChangeCallback();
  3332. }
  3333. /**
  3334. * Sets the quaternion components.
  3335. *
  3336. * @param {number} x - The x value of this quaternion.
  3337. * @param {number} y - The y value of this quaternion.
  3338. * @param {number} z - The z value of this quaternion.
  3339. * @param {number} w - The w value of this quaternion.
  3340. * @return {Quaternion} A reference to this quaternion.
  3341. */
  3342. set( x, y, z, w ) {
  3343. this._x = x;
  3344. this._y = y;
  3345. this._z = z;
  3346. this._w = w;
  3347. this._onChangeCallback();
  3348. return this;
  3349. }
  3350. /**
  3351. * Returns a new quaternion with copied values from this instance.
  3352. *
  3353. * @return {Quaternion} A clone of this instance.
  3354. */
  3355. clone() {
  3356. return new this.constructor( this._x, this._y, this._z, this._w );
  3357. }
  3358. /**
  3359. * Copies the values of the given quaternion to this instance.
  3360. *
  3361. * @param {Quaternion} quaternion - The quaternion to copy.
  3362. * @return {Quaternion} A reference to this quaternion.
  3363. */
  3364. copy( quaternion ) {
  3365. this._x = quaternion.x;
  3366. this._y = quaternion.y;
  3367. this._z = quaternion.z;
  3368. this._w = quaternion.w;
  3369. this._onChangeCallback();
  3370. return this;
  3371. }
  3372. /**
  3373. * Sets this quaternion from the rotation specified by the given
  3374. * Euler angles.
  3375. *
  3376. * @param {Euler} euler - The Euler angles.
  3377. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3378. * @return {Quaternion} A reference to this quaternion.
  3379. */
  3380. setFromEuler( euler, update = true ) {
  3381. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3382. // http://www.mathworks.com/matlabcentral/fileexchange/
  3383. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3384. // content/SpinCalc.m
  3385. const cos = Math.cos;
  3386. const sin = Math.sin;
  3387. const c1 = cos( x / 2 );
  3388. const c2 = cos( y / 2 );
  3389. const c3 = cos( z / 2 );
  3390. const s1 = sin( x / 2 );
  3391. const s2 = sin( y / 2 );
  3392. const s3 = sin( z / 2 );
  3393. switch ( order ) {
  3394. case 'XYZ':
  3395. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3396. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3397. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3398. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3399. break;
  3400. case 'YXZ':
  3401. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3402. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3403. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3404. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3405. break;
  3406. case 'ZXY':
  3407. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3408. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3409. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3410. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3411. break;
  3412. case 'ZYX':
  3413. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3414. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3415. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3416. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3417. break;
  3418. case 'YZX':
  3419. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3420. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3421. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3422. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3423. break;
  3424. case 'XZY':
  3425. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3426. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3427. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3428. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3429. break;
  3430. default:
  3431. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3432. }
  3433. if ( update === true ) this._onChangeCallback();
  3434. return this;
  3435. }
  3436. /**
  3437. * Sets this quaternion from the given axis and angle.
  3438. *
  3439. * @param {Vector3} axis - The normalized axis.
  3440. * @param {number} angle - The angle in radians.
  3441. * @return {Quaternion} A reference to this quaternion.
  3442. */
  3443. setFromAxisAngle( axis, angle ) {
  3444. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3445. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3446. this._x = axis.x * s;
  3447. this._y = axis.y * s;
  3448. this._z = axis.z * s;
  3449. this._w = Math.cos( halfAngle );
  3450. this._onChangeCallback();
  3451. return this;
  3452. }
  3453. /**
  3454. * Sets this quaternion from the given rotation matrix.
  3455. *
  3456. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3457. * @return {Quaternion} A reference to this quaternion.
  3458. */
  3459. setFromRotationMatrix( m ) {
  3460. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3461. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3462. const te = m.elements,
  3463. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3464. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3465. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3466. trace = m11 + m22 + m33;
  3467. if ( trace > 0 ) {
  3468. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3469. this._w = 0.25 / s;
  3470. this._x = ( m32 - m23 ) * s;
  3471. this._y = ( m13 - m31 ) * s;
  3472. this._z = ( m21 - m12 ) * s;
  3473. } else if ( m11 > m22 && m11 > m33 ) {
  3474. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3475. this._w = ( m32 - m23 ) / s;
  3476. this._x = 0.25 * s;
  3477. this._y = ( m12 + m21 ) / s;
  3478. this._z = ( m13 + m31 ) / s;
  3479. } else if ( m22 > m33 ) {
  3480. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3481. this._w = ( m13 - m31 ) / s;
  3482. this._x = ( m12 + m21 ) / s;
  3483. this._y = 0.25 * s;
  3484. this._z = ( m23 + m32 ) / s;
  3485. } else {
  3486. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3487. this._w = ( m21 - m12 ) / s;
  3488. this._x = ( m13 + m31 ) / s;
  3489. this._y = ( m23 + m32 ) / s;
  3490. this._z = 0.25 * s;
  3491. }
  3492. this._onChangeCallback();
  3493. return this;
  3494. }
  3495. /**
  3496. * Sets this quaternion to the rotation required to rotate the direction vector
  3497. * `vFrom` to the direction vector `vTo`.
  3498. *
  3499. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3500. * @param {Vector3} vTo - The second (normalized) direction vector.
  3501. * @return {Quaternion} A reference to this quaternion.
  3502. */
  3503. setFromUnitVectors( vFrom, vTo ) {
  3504. // assumes direction vectors vFrom and vTo are normalized
  3505. let r = vFrom.dot( vTo ) + 1;
  3506. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3507. // vFrom and vTo point in opposite directions
  3508. r = 0;
  3509. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3510. this._x = - vFrom.y;
  3511. this._y = vFrom.x;
  3512. this._z = 0;
  3513. this._w = r;
  3514. } else {
  3515. this._x = 0;
  3516. this._y = - vFrom.z;
  3517. this._z = vFrom.y;
  3518. this._w = r;
  3519. }
  3520. } else {
  3521. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3522. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3523. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3524. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3525. this._w = r;
  3526. }
  3527. return this.normalize();
  3528. }
  3529. /**
  3530. * Returns the angle between this quaternion and the given one in radians.
  3531. *
  3532. * @param {Quaternion} q - The quaternion to compute the angle with.
  3533. * @return {number} The angle in radians.
  3534. */
  3535. angleTo( q ) {
  3536. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3537. }
  3538. /**
  3539. * Rotates this quaternion by a given angular step to the given quaternion.
  3540. * The method ensures that the final quaternion will not overshoot `q`.
  3541. *
  3542. * @param {Quaternion} q - The target quaternion.
  3543. * @param {number} step - The angular step in radians.
  3544. * @return {Quaternion} A reference to this quaternion.
  3545. */
  3546. rotateTowards( q, step ) {
  3547. const angle = this.angleTo( q );
  3548. if ( angle === 0 ) return this;
  3549. const t = Math.min( 1, step / angle );
  3550. this.slerp( q, t );
  3551. return this;
  3552. }
  3553. /**
  3554. * Sets this quaternion to the identity quaternion; that is, to the
  3555. * quaternion that represents "no rotation".
  3556. *
  3557. * @return {Quaternion} A reference to this quaternion.
  3558. */
  3559. identity() {
  3560. return this.set( 0, 0, 0, 1 );
  3561. }
  3562. /**
  3563. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3564. * quaternion is assumed to have unit length.
  3565. *
  3566. * @return {Quaternion} A reference to this quaternion.
  3567. */
  3568. invert() {
  3569. return this.conjugate();
  3570. }
  3571. /**
  3572. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3573. * quaternion represents the same rotation in the opposite direction about
  3574. * the rotational axis.
  3575. *
  3576. * @return {Quaternion} A reference to this quaternion.
  3577. */
  3578. conjugate() {
  3579. this._x *= -1;
  3580. this._y *= -1;
  3581. this._z *= -1;
  3582. this._onChangeCallback();
  3583. return this;
  3584. }
  3585. /**
  3586. * Calculates the dot product of this quaternion and the given one.
  3587. *
  3588. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3589. * @return {number} The result of the dot product.
  3590. */
  3591. dot( v ) {
  3592. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3593. }
  3594. /**
  3595. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3596. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3597. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3598. * {@link Quaternion#length}.
  3599. *
  3600. * @return {number} The squared Euclidean length.
  3601. */
  3602. lengthSq() {
  3603. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3604. }
  3605. /**
  3606. * Computes the Euclidean length (straight-line length) of this quaternion,
  3607. * considered as a 4 dimensional vector.
  3608. *
  3609. * @return {number} The Euclidean length.
  3610. */
  3611. length() {
  3612. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3613. }
  3614. /**
  3615. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3616. * the same rotation as this one, but has a length equal to `1`.
  3617. *
  3618. * @return {Quaternion} A reference to this quaternion.
  3619. */
  3620. normalize() {
  3621. let l = this.length();
  3622. if ( l === 0 ) {
  3623. this._x = 0;
  3624. this._y = 0;
  3625. this._z = 0;
  3626. this._w = 1;
  3627. } else {
  3628. l = 1 / l;
  3629. this._x = this._x * l;
  3630. this._y = this._y * l;
  3631. this._z = this._z * l;
  3632. this._w = this._w * l;
  3633. }
  3634. this._onChangeCallback();
  3635. return this;
  3636. }
  3637. /**
  3638. * Multiplies this quaternion by the given one.
  3639. *
  3640. * @param {Quaternion} q - The quaternion.
  3641. * @return {Quaternion} A reference to this quaternion.
  3642. */
  3643. multiply( q ) {
  3644. return this.multiplyQuaternions( this, q );
  3645. }
  3646. /**
  3647. * Pre-multiplies this quaternion by the given one.
  3648. *
  3649. * @param {Quaternion} q - The quaternion.
  3650. * @return {Quaternion} A reference to this quaternion.
  3651. */
  3652. premultiply( q ) {
  3653. return this.multiplyQuaternions( q, this );
  3654. }
  3655. /**
  3656. * Multiplies the given quaternions and stores the result in this instance.
  3657. *
  3658. * @param {Quaternion} a - The first quaternion.
  3659. * @param {Quaternion} b - The second quaternion.
  3660. * @return {Quaternion} A reference to this quaternion.
  3661. */
  3662. multiplyQuaternions( a, b ) {
  3663. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3664. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3665. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3666. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3667. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3668. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3669. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3670. this._onChangeCallback();
  3671. return this;
  3672. }
  3673. /**
  3674. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3675. *
  3676. * @param {Quaternion} qb - The target quaternion.
  3677. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3678. * @return {Quaternion} A reference to this quaternion.
  3679. */
  3680. slerp( qb, t ) {
  3681. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3682. let dot = this.dot( qb );
  3683. if ( dot < 0 ) {
  3684. x = - x;
  3685. y = - y;
  3686. z = - z;
  3687. w = - w;
  3688. dot = - dot;
  3689. }
  3690. let s = 1 - t;
  3691. if ( dot < 0.9995 ) {
  3692. // slerp
  3693. const theta = Math.acos( dot );
  3694. const sin = Math.sin( theta );
  3695. s = Math.sin( s * theta ) / sin;
  3696. t = Math.sin( t * theta ) / sin;
  3697. this._x = this._x * s + x * t;
  3698. this._y = this._y * s + y * t;
  3699. this._z = this._z * s + z * t;
  3700. this._w = this._w * s + w * t;
  3701. this._onChangeCallback();
  3702. } else {
  3703. // for small angles, lerp then normalize
  3704. this._x = this._x * s + x * t;
  3705. this._y = this._y * s + y * t;
  3706. this._z = this._z * s + z * t;
  3707. this._w = this._w * s + w * t;
  3708. this.normalize(); // normalize calls _onChangeCallback()
  3709. }
  3710. return this;
  3711. }
  3712. /**
  3713. * Performs a spherical linear interpolation between the given quaternions
  3714. * and stores the result in this quaternion.
  3715. *
  3716. * @param {Quaternion} qa - The source quaternion.
  3717. * @param {Quaternion} qb - The target quaternion.
  3718. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3719. * @return {Quaternion} A reference to this quaternion.
  3720. */
  3721. slerpQuaternions( qa, qb, t ) {
  3722. return this.copy( qa ).slerp( qb, t );
  3723. }
  3724. /**
  3725. * Sets this quaternion to a uniformly random, normalized quaternion.
  3726. *
  3727. * @return {Quaternion} A reference to this quaternion.
  3728. */
  3729. random() {
  3730. // Ken Shoemake
  3731. // Uniform random rotations
  3732. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3733. const theta1 = 2 * Math.PI * Math.random();
  3734. const theta2 = 2 * Math.PI * Math.random();
  3735. const x0 = Math.random();
  3736. const r1 = Math.sqrt( 1 - x0 );
  3737. const r2 = Math.sqrt( x0 );
  3738. return this.set(
  3739. r1 * Math.sin( theta1 ),
  3740. r1 * Math.cos( theta1 ),
  3741. r2 * Math.sin( theta2 ),
  3742. r2 * Math.cos( theta2 ),
  3743. );
  3744. }
  3745. /**
  3746. * Returns `true` if this quaternion is equal with the given one.
  3747. *
  3748. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3749. * @return {boolean} Whether this quaternion is equal with the given one.
  3750. */
  3751. equals( quaternion ) {
  3752. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3753. }
  3754. /**
  3755. * Sets this quaternion's components from the given array.
  3756. *
  3757. * @param {Array<number>} array - An array holding the quaternion component values.
  3758. * @param {number} [offset=0] - The offset into the array.
  3759. * @return {Quaternion} A reference to this quaternion.
  3760. */
  3761. fromArray( array, offset = 0 ) {
  3762. this._x = array[ offset ];
  3763. this._y = array[ offset + 1 ];
  3764. this._z = array[ offset + 2 ];
  3765. this._w = array[ offset + 3 ];
  3766. this._onChangeCallback();
  3767. return this;
  3768. }
  3769. /**
  3770. * Writes the components of this quaternion to the given array. If no array is provided,
  3771. * the method returns a new instance.
  3772. *
  3773. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3774. * @param {number} [offset=0] - Index of the first element in the array.
  3775. * @return {Array<number>} The quaternion components.
  3776. */
  3777. toArray( array = [], offset = 0 ) {
  3778. array[ offset ] = this._x;
  3779. array[ offset + 1 ] = this._y;
  3780. array[ offset + 2 ] = this._z;
  3781. array[ offset + 3 ] = this._w;
  3782. return array;
  3783. }
  3784. /**
  3785. * Sets the components of this quaternion from the given buffer attribute.
  3786. *
  3787. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3788. * @param {number} index - The index into the attribute.
  3789. * @return {Quaternion} A reference to this quaternion.
  3790. */
  3791. fromBufferAttribute( attribute, index ) {
  3792. this._x = attribute.getX( index );
  3793. this._y = attribute.getY( index );
  3794. this._z = attribute.getZ( index );
  3795. this._w = attribute.getW( index );
  3796. this._onChangeCallback();
  3797. return this;
  3798. }
  3799. /**
  3800. * This methods defines the serialization result of this class. Returns the
  3801. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3802. *
  3803. * @return {Array<number>} The serialized quaternion.
  3804. */
  3805. toJSON() {
  3806. return this.toArray();
  3807. }
  3808. _onChange( callback ) {
  3809. this._onChangeCallback = callback;
  3810. return this;
  3811. }
  3812. _onChangeCallback() {}
  3813. *[ Symbol.iterator ]() {
  3814. yield this._x;
  3815. yield this._y;
  3816. yield this._z;
  3817. yield this._w;
  3818. }
  3819. }
  3820. /**
  3821. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3822. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3823. *
  3824. * - A point in 3D space.
  3825. * - A direction and length in 3D space. In three.js the length will
  3826. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3827. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3828. * - Any arbitrary ordered triplet of numbers.
  3829. *
  3830. * There are other things a 3D vector can be used to represent, such as
  3831. * momentum vectors and so on, however these are the most
  3832. * common uses in three.js.
  3833. *
  3834. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3835. * the corresponding order.
  3836. * ```js
  3837. * const a = new THREE.Vector3( 0, 1, 0 );
  3838. *
  3839. * //no arguments; will be initialised to (0, 0, 0)
  3840. * const b = new THREE.Vector3( );
  3841. *
  3842. * const d = a.distanceTo( b );
  3843. * ```
  3844. */
  3845. class Vector3 {
  3846. static {
  3847. /**
  3848. * This flag can be used for type testing.
  3849. *
  3850. * @type {boolean}
  3851. * @readonly
  3852. * @default true
  3853. */
  3854. Vector3.prototype.isVector3 = true;
  3855. }
  3856. /**
  3857. * Constructs a new 3D vector.
  3858. *
  3859. * @param {number} [x=0] - The x value of this vector.
  3860. * @param {number} [y=0] - The y value of this vector.
  3861. * @param {number} [z=0] - The z value of this vector.
  3862. */
  3863. constructor( x = 0, y = 0, z = 0 ) {
  3864. /**
  3865. * The x value of this vector.
  3866. *
  3867. * @type {number}
  3868. */
  3869. this.x = x;
  3870. /**
  3871. * The y value of this vector.
  3872. *
  3873. * @type {number}
  3874. */
  3875. this.y = y;
  3876. /**
  3877. * The z value of this vector.
  3878. *
  3879. * @type {number}
  3880. */
  3881. this.z = z;
  3882. }
  3883. /**
  3884. * Sets the vector components.
  3885. *
  3886. * @param {number} x - The value of the x component.
  3887. * @param {number} y - The value of the y component.
  3888. * @param {number} z - The value of the z component.
  3889. * @return {Vector3} A reference to this vector.
  3890. */
  3891. set( x, y, z ) {
  3892. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3893. this.x = x;
  3894. this.y = y;
  3895. this.z = z;
  3896. return this;
  3897. }
  3898. /**
  3899. * Sets the vector components to the same value.
  3900. *
  3901. * @param {number} scalar - The value to set for all vector components.
  3902. * @return {Vector3} A reference to this vector.
  3903. */
  3904. setScalar( scalar ) {
  3905. this.x = scalar;
  3906. this.y = scalar;
  3907. this.z = scalar;
  3908. return this;
  3909. }
  3910. /**
  3911. * Sets the vector's x component to the given value.
  3912. *
  3913. * @param {number} x - The value to set.
  3914. * @return {Vector3} A reference to this vector.
  3915. */
  3916. setX( x ) {
  3917. this.x = x;
  3918. return this;
  3919. }
  3920. /**
  3921. * Sets the vector's y component to the given value.
  3922. *
  3923. * @param {number} y - The value to set.
  3924. * @return {Vector3} A reference to this vector.
  3925. */
  3926. setY( y ) {
  3927. this.y = y;
  3928. return this;
  3929. }
  3930. /**
  3931. * Sets the vector's z component to the given value.
  3932. *
  3933. * @param {number} z - The value to set.
  3934. * @return {Vector3} A reference to this vector.
  3935. */
  3936. setZ( z ) {
  3937. this.z = z;
  3938. return this;
  3939. }
  3940. /**
  3941. * Allows to set a vector component with an index.
  3942. *
  3943. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3944. * @param {number} value - The value to set.
  3945. * @return {Vector3} A reference to this vector.
  3946. */
  3947. setComponent( index, value ) {
  3948. switch ( index ) {
  3949. case 0: this.x = value; break;
  3950. case 1: this.y = value; break;
  3951. case 2: this.z = value; break;
  3952. default: throw new Error( 'index is out of range: ' + index );
  3953. }
  3954. return this;
  3955. }
  3956. /**
  3957. * Returns the value of the vector component which matches the given index.
  3958. *
  3959. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3960. * @return {number} A vector component value.
  3961. */
  3962. getComponent( index ) {
  3963. switch ( index ) {
  3964. case 0: return this.x;
  3965. case 1: return this.y;
  3966. case 2: return this.z;
  3967. default: throw new Error( 'index is out of range: ' + index );
  3968. }
  3969. }
  3970. /**
  3971. * Returns a new vector with copied values from this instance.
  3972. *
  3973. * @return {Vector3} A clone of this instance.
  3974. */
  3975. clone() {
  3976. return new this.constructor( this.x, this.y, this.z );
  3977. }
  3978. /**
  3979. * Copies the values of the given vector to this instance.
  3980. *
  3981. * @param {Vector3} v - The vector to copy.
  3982. * @return {Vector3} A reference to this vector.
  3983. */
  3984. copy( v ) {
  3985. this.x = v.x;
  3986. this.y = v.y;
  3987. this.z = v.z;
  3988. return this;
  3989. }
  3990. /**
  3991. * Adds the given vector to this instance.
  3992. *
  3993. * @param {Vector3} v - The vector to add.
  3994. * @return {Vector3} A reference to this vector.
  3995. */
  3996. add( v ) {
  3997. this.x += v.x;
  3998. this.y += v.y;
  3999. this.z += v.z;
  4000. return this;
  4001. }
  4002. /**
  4003. * Adds the given scalar value to all components of this instance.
  4004. *
  4005. * @param {number} s - The scalar to add.
  4006. * @return {Vector3} A reference to this vector.
  4007. */
  4008. addScalar( s ) {
  4009. this.x += s;
  4010. this.y += s;
  4011. this.z += s;
  4012. return this;
  4013. }
  4014. /**
  4015. * Adds the given vectors and stores the result in this instance.
  4016. *
  4017. * @param {Vector3} a - The first vector.
  4018. * @param {Vector3} b - The second vector.
  4019. * @return {Vector3} A reference to this vector.
  4020. */
  4021. addVectors( a, b ) {
  4022. this.x = a.x + b.x;
  4023. this.y = a.y + b.y;
  4024. this.z = a.z + b.z;
  4025. return this;
  4026. }
  4027. /**
  4028. * Adds the given vector scaled by the given factor to this instance.
  4029. *
  4030. * @param {Vector3|Vector4} v - The vector.
  4031. * @param {number} s - The factor that scales `v`.
  4032. * @return {Vector3} A reference to this vector.
  4033. */
  4034. addScaledVector( v, s ) {
  4035. this.x += v.x * s;
  4036. this.y += v.y * s;
  4037. this.z += v.z * s;
  4038. return this;
  4039. }
  4040. /**
  4041. * Subtracts the given vector from this instance.
  4042. *
  4043. * @param {Vector3} v - The vector to subtract.
  4044. * @return {Vector3} A reference to this vector.
  4045. */
  4046. sub( v ) {
  4047. this.x -= v.x;
  4048. this.y -= v.y;
  4049. this.z -= v.z;
  4050. return this;
  4051. }
  4052. /**
  4053. * Subtracts the given scalar value from all components of this instance.
  4054. *
  4055. * @param {number} s - The scalar to subtract.
  4056. * @return {Vector3} A reference to this vector.
  4057. */
  4058. subScalar( s ) {
  4059. this.x -= s;
  4060. this.y -= s;
  4061. this.z -= s;
  4062. return this;
  4063. }
  4064. /**
  4065. * Subtracts the given vectors and stores the result in this instance.
  4066. *
  4067. * @param {Vector3} a - The first vector.
  4068. * @param {Vector3} b - The second vector.
  4069. * @return {Vector3} A reference to this vector.
  4070. */
  4071. subVectors( a, b ) {
  4072. this.x = a.x - b.x;
  4073. this.y = a.y - b.y;
  4074. this.z = a.z - b.z;
  4075. return this;
  4076. }
  4077. /**
  4078. * Multiplies the given vector with this instance.
  4079. *
  4080. * @param {Vector3} v - The vector to multiply.
  4081. * @return {Vector3} A reference to this vector.
  4082. */
  4083. multiply( v ) {
  4084. this.x *= v.x;
  4085. this.y *= v.y;
  4086. this.z *= v.z;
  4087. return this;
  4088. }
  4089. /**
  4090. * Multiplies the given scalar value with all components of this instance.
  4091. *
  4092. * @param {number} scalar - The scalar to multiply.
  4093. * @return {Vector3} A reference to this vector.
  4094. */
  4095. multiplyScalar( scalar ) {
  4096. this.x *= scalar;
  4097. this.y *= scalar;
  4098. this.z *= scalar;
  4099. return this;
  4100. }
  4101. /**
  4102. * Multiplies the given vectors and stores the result in this instance.
  4103. *
  4104. * @param {Vector3} a - The first vector.
  4105. * @param {Vector3} b - The second vector.
  4106. * @return {Vector3} A reference to this vector.
  4107. */
  4108. multiplyVectors( a, b ) {
  4109. this.x = a.x * b.x;
  4110. this.y = a.y * b.y;
  4111. this.z = a.z * b.z;
  4112. return this;
  4113. }
  4114. /**
  4115. * Applies the given Euler rotation to this vector.
  4116. *
  4117. * @param {Euler} euler - The Euler angles.
  4118. * @return {Vector3} A reference to this vector.
  4119. */
  4120. applyEuler( euler ) {
  4121. return this.applyQuaternion( _quaternion$5.setFromEuler( euler ) );
  4122. }
  4123. /**
  4124. * Applies a rotation specified by an axis and an angle to this vector.
  4125. *
  4126. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4127. * @param {number} angle - The angle in radians.
  4128. * @return {Vector3} A reference to this vector.
  4129. */
  4130. applyAxisAngle( axis, angle ) {
  4131. return this.applyQuaternion( _quaternion$5.setFromAxisAngle( axis, angle ) );
  4132. }
  4133. /**
  4134. * Multiplies this vector with the given 3x3 matrix.
  4135. *
  4136. * @param {Matrix3} m - The 3x3 matrix.
  4137. * @return {Vector3} A reference to this vector.
  4138. */
  4139. applyMatrix3( m ) {
  4140. const x = this.x, y = this.y, z = this.z;
  4141. const e = m.elements;
  4142. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4143. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4144. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4145. return this;
  4146. }
  4147. /**
  4148. * Multiplies this vector by the given normal matrix and normalizes
  4149. * the result.
  4150. *
  4151. * @param {Matrix3} m - The normal matrix.
  4152. * @return {Vector3} A reference to this vector.
  4153. */
  4154. applyNormalMatrix( m ) {
  4155. return this.applyMatrix3( m ).normalize();
  4156. }
  4157. /**
  4158. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4159. * divides by perspective.
  4160. *
  4161. * @param {Matrix4} m - The matrix to apply.
  4162. * @return {Vector3} A reference to this vector.
  4163. */
  4164. applyMatrix4( m ) {
  4165. const x = this.x, y = this.y, z = this.z;
  4166. const e = m.elements;
  4167. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4168. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4169. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4170. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4171. return this;
  4172. }
  4173. /**
  4174. * Applies the given Quaternion to this vector.
  4175. *
  4176. * @param {Quaternion} q - The Quaternion.
  4177. * @return {Vector3} A reference to this vector.
  4178. */
  4179. applyQuaternion( q ) {
  4180. // quaternion q is assumed to have unit length
  4181. const vx = this.x, vy = this.y, vz = this.z;
  4182. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4183. // t = 2 * cross( q.xyz, v );
  4184. const tx = 2 * ( qy * vz - qz * vy );
  4185. const ty = 2 * ( qz * vx - qx * vz );
  4186. const tz = 2 * ( qx * vy - qy * vx );
  4187. // v + q.w * t + cross( q.xyz, t );
  4188. this.x = vx + qw * tx + qy * tz - qz * ty;
  4189. this.y = vy + qw * ty + qz * tx - qx * tz;
  4190. this.z = vz + qw * tz + qx * ty - qy * tx;
  4191. return this;
  4192. }
  4193. /**
  4194. * Projects this vector from world space into the camera's normalized
  4195. * device coordinate (NDC) space.
  4196. *
  4197. * @param {Camera} camera - The camera.
  4198. * @return {Vector3} A reference to this vector.
  4199. */
  4200. project( camera ) {
  4201. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4202. }
  4203. /**
  4204. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4205. * space into world space.
  4206. *
  4207. * @param {Camera} camera - The camera.
  4208. * @return {Vector3} A reference to this vector.
  4209. */
  4210. unproject( camera ) {
  4211. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4212. }
  4213. /**
  4214. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4215. * subset of the given 4x4 matrix and then normalizes the result.
  4216. *
  4217. * @param {Matrix4} m - The matrix.
  4218. * @return {Vector3} A reference to this vector.
  4219. */
  4220. transformDirection( m ) {
  4221. // input: THREE.Matrix4 affine matrix
  4222. // vector interpreted as a direction
  4223. const x = this.x, y = this.y, z = this.z;
  4224. const e = m.elements;
  4225. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4226. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4227. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4228. return this.normalize();
  4229. }
  4230. /**
  4231. * Divides this instance by the given vector.
  4232. *
  4233. * @param {Vector3} v - The vector to divide.
  4234. * @return {Vector3} A reference to this vector.
  4235. */
  4236. divide( v ) {
  4237. this.x /= v.x;
  4238. this.y /= v.y;
  4239. this.z /= v.z;
  4240. return this;
  4241. }
  4242. /**
  4243. * Divides this vector by the given scalar.
  4244. *
  4245. * @param {number} scalar - The scalar to divide.
  4246. * @return {Vector3} A reference to this vector.
  4247. */
  4248. divideScalar( scalar ) {
  4249. return this.multiplyScalar( 1 / scalar );
  4250. }
  4251. /**
  4252. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4253. * value, replace that value with the corresponding min value.
  4254. *
  4255. * @param {Vector3} v - The vector.
  4256. * @return {Vector3} A reference to this vector.
  4257. */
  4258. min( v ) {
  4259. this.x = Math.min( this.x, v.x );
  4260. this.y = Math.min( this.y, v.y );
  4261. this.z = Math.min( this.z, v.z );
  4262. return this;
  4263. }
  4264. /**
  4265. * If this vector's x, y or z value is less than the given vector's x, y or z
  4266. * value, replace that value with the corresponding max value.
  4267. *
  4268. * @param {Vector3} v - The vector.
  4269. * @return {Vector3} A reference to this vector.
  4270. */
  4271. max( v ) {
  4272. this.x = Math.max( this.x, v.x );
  4273. this.y = Math.max( this.y, v.y );
  4274. this.z = Math.max( this.z, v.z );
  4275. return this;
  4276. }
  4277. /**
  4278. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4279. * value, it is replaced by the corresponding value.
  4280. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4281. * it is replaced by the corresponding value.
  4282. *
  4283. * @param {Vector3} min - The minimum x, y and z values.
  4284. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4285. * @return {Vector3} A reference to this vector.
  4286. */
  4287. clamp( min, max ) {
  4288. // assumes min < max, componentwise
  4289. this.x = clamp( this.x, min.x, max.x );
  4290. this.y = clamp( this.y, min.y, max.y );
  4291. this.z = clamp( this.z, min.z, max.z );
  4292. return this;
  4293. }
  4294. /**
  4295. * If this vector's x, y or z values are greater than the max value, they are
  4296. * replaced by the max value.
  4297. * If this vector's x, y or z values are less than the min value, they are
  4298. * replaced by the min value.
  4299. *
  4300. * @param {number} minVal - The minimum value the components will be clamped to.
  4301. * @param {number} maxVal - The maximum value the components will be clamped to.
  4302. * @return {Vector3} A reference to this vector.
  4303. */
  4304. clampScalar( minVal, maxVal ) {
  4305. this.x = clamp( this.x, minVal, maxVal );
  4306. this.y = clamp( this.y, minVal, maxVal );
  4307. this.z = clamp( this.z, minVal, maxVal );
  4308. return this;
  4309. }
  4310. /**
  4311. * If this vector's length is greater than the max value, it is replaced by
  4312. * the max value.
  4313. * If this vector's length is less than the min value, it is replaced by the
  4314. * min value.
  4315. *
  4316. * @param {number} min - The minimum value the vector length will be clamped to.
  4317. * @param {number} max - The maximum value the vector length will be clamped to.
  4318. * @return {Vector3} A reference to this vector.
  4319. */
  4320. clampLength( min, max ) {
  4321. const length = this.length();
  4322. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4323. }
  4324. /**
  4325. * The components of this vector are rounded down to the nearest integer value.
  4326. *
  4327. * @return {Vector3} A reference to this vector.
  4328. */
  4329. floor() {
  4330. this.x = Math.floor( this.x );
  4331. this.y = Math.floor( this.y );
  4332. this.z = Math.floor( this.z );
  4333. return this;
  4334. }
  4335. /**
  4336. * The components of this vector are rounded up to the nearest integer value.
  4337. *
  4338. * @return {Vector3} A reference to this vector.
  4339. */
  4340. ceil() {
  4341. this.x = Math.ceil( this.x );
  4342. this.y = Math.ceil( this.y );
  4343. this.z = Math.ceil( this.z );
  4344. return this;
  4345. }
  4346. /**
  4347. * The components of this vector are rounded to the nearest integer value
  4348. *
  4349. * @return {Vector3} A reference to this vector.
  4350. */
  4351. round() {
  4352. this.x = Math.round( this.x );
  4353. this.y = Math.round( this.y );
  4354. this.z = Math.round( this.z );
  4355. return this;
  4356. }
  4357. /**
  4358. * The components of this vector are rounded towards zero (up if negative,
  4359. * down if positive) to an integer value.
  4360. *
  4361. * @return {Vector3} A reference to this vector.
  4362. */
  4363. roundToZero() {
  4364. this.x = Math.trunc( this.x );
  4365. this.y = Math.trunc( this.y );
  4366. this.z = Math.trunc( this.z );
  4367. return this;
  4368. }
  4369. /**
  4370. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4371. *
  4372. * @return {Vector3} A reference to this vector.
  4373. */
  4374. negate() {
  4375. this.x = - this.x;
  4376. this.y = - this.y;
  4377. this.z = - this.z;
  4378. return this;
  4379. }
  4380. /**
  4381. * Calculates the dot product of the given vector with this instance.
  4382. *
  4383. * @param {Vector3} v - The vector to compute the dot product with.
  4384. * @return {number} The result of the dot product.
  4385. */
  4386. dot( v ) {
  4387. return this.x * v.x + this.y * v.y + this.z * v.z;
  4388. }
  4389. /**
  4390. * Computes the square of the Euclidean length (straight-line length) from
  4391. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4392. * compare the length squared instead as it is slightly more efficient to calculate.
  4393. *
  4394. * @return {number} The square length of this vector.
  4395. */
  4396. lengthSq() {
  4397. return this.x * this.x + this.y * this.y + this.z * this.z;
  4398. }
  4399. /**
  4400. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4401. *
  4402. * @return {number} The length of this vector.
  4403. */
  4404. length() {
  4405. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4406. }
  4407. /**
  4408. * Computes the Manhattan length of this vector.
  4409. *
  4410. * @return {number} The length of this vector.
  4411. */
  4412. manhattanLength() {
  4413. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4414. }
  4415. /**
  4416. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4417. * with the same direction as this one, but with a vector length of `1`.
  4418. *
  4419. * @return {Vector3} A reference to this vector.
  4420. */
  4421. normalize() {
  4422. return this.divideScalar( this.length() || 1 );
  4423. }
  4424. /**
  4425. * Sets this vector to a vector with the same direction as this one, but
  4426. * with the specified length.
  4427. *
  4428. * @param {number} length - The new length of this vector.
  4429. * @return {Vector3} A reference to this vector.
  4430. */
  4431. setLength( length ) {
  4432. return this.normalize().multiplyScalar( length );
  4433. }
  4434. /**
  4435. * Linearly interpolates between the given vector and this instance, where
  4436. * alpha is the percent distance along the line - alpha = 0 will be this
  4437. * vector, and alpha = 1 will be the given one.
  4438. *
  4439. * @param {Vector3} v - The vector to interpolate towards.
  4440. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4441. * @return {Vector3} A reference to this vector.
  4442. */
  4443. lerp( v, alpha ) {
  4444. this.x += ( v.x - this.x ) * alpha;
  4445. this.y += ( v.y - this.y ) * alpha;
  4446. this.z += ( v.z - this.z ) * alpha;
  4447. return this;
  4448. }
  4449. /**
  4450. * Linearly interpolates between the given vectors, where alpha is the percent
  4451. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4452. * be the second one. The result is stored in this instance.
  4453. *
  4454. * @param {Vector3} v1 - The first vector.
  4455. * @param {Vector3} v2 - The second vector.
  4456. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4457. * @return {Vector3} A reference to this vector.
  4458. */
  4459. lerpVectors( v1, v2, alpha ) {
  4460. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4461. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4462. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4463. return this;
  4464. }
  4465. /**
  4466. * Calculates the cross product of the given vector with this instance.
  4467. *
  4468. * @param {Vector3} v - The vector to compute the cross product with.
  4469. * @return {Vector3} The result of the cross product.
  4470. */
  4471. cross( v ) {
  4472. return this.crossVectors( this, v );
  4473. }
  4474. /**
  4475. * Calculates the cross product of the given vectors and stores the result
  4476. * in this instance.
  4477. *
  4478. * @param {Vector3} a - The first vector.
  4479. * @param {Vector3} b - The second vector.
  4480. * @return {Vector3} A reference to this vector.
  4481. */
  4482. crossVectors( a, b ) {
  4483. const ax = a.x, ay = a.y, az = a.z;
  4484. const bx = b.x, by = b.y, bz = b.z;
  4485. this.x = ay * bz - az * by;
  4486. this.y = az * bx - ax * bz;
  4487. this.z = ax * by - ay * bx;
  4488. return this;
  4489. }
  4490. /**
  4491. * Projects this vector onto the given one.
  4492. *
  4493. * @param {Vector3} v - The vector to project to.
  4494. * @return {Vector3} A reference to this vector.
  4495. */
  4496. projectOnVector( v ) {
  4497. const denominator = v.lengthSq();
  4498. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4499. const scalar = v.dot( this ) / denominator;
  4500. return this.copy( v ).multiplyScalar( scalar );
  4501. }
  4502. /**
  4503. * Projects this vector onto a plane by subtracting this
  4504. * vector projected onto the plane's normal from this vector.
  4505. *
  4506. * @param {Vector3} planeNormal - The plane normal.
  4507. * @return {Vector3} A reference to this vector.
  4508. */
  4509. projectOnPlane( planeNormal ) {
  4510. _vector$c.copy( this ).projectOnVector( planeNormal );
  4511. return this.sub( _vector$c );
  4512. }
  4513. /**
  4514. * Reflects this vector off a plane orthogonal to the given normal vector.
  4515. *
  4516. * @param {Vector3} normal - The (normalized) normal vector.
  4517. * @return {Vector3} A reference to this vector.
  4518. */
  4519. reflect( normal ) {
  4520. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4521. }
  4522. /**
  4523. * Returns the angle between the given vector and this instance in radians.
  4524. *
  4525. * @param {Vector3} v - The vector to compute the angle with.
  4526. * @return {number} The angle in radians.
  4527. */
  4528. angleTo( v ) {
  4529. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4530. if ( denominator === 0 ) return Math.PI / 2;
  4531. const theta = this.dot( v ) / denominator;
  4532. // clamp, to handle numerical problems
  4533. return Math.acos( clamp( theta, -1, 1 ) );
  4534. }
  4535. /**
  4536. * Computes the distance from the given vector to this instance.
  4537. *
  4538. * @param {Vector3} v - The vector to compute the distance to.
  4539. * @return {number} The distance.
  4540. */
  4541. distanceTo( v ) {
  4542. return Math.sqrt( this.distanceToSquared( v ) );
  4543. }
  4544. /**
  4545. * Computes the squared distance from the given vector to this instance.
  4546. * If you are just comparing the distance with another distance, you should compare
  4547. * the distance squared instead as it is slightly more efficient to calculate.
  4548. *
  4549. * @param {Vector3} v - The vector to compute the squared distance to.
  4550. * @return {number} The squared distance.
  4551. */
  4552. distanceToSquared( v ) {
  4553. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4554. return dx * dx + dy * dy + dz * dz;
  4555. }
  4556. /**
  4557. * Computes the Manhattan distance from the given vector to this instance.
  4558. *
  4559. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4560. * @return {number} The Manhattan distance.
  4561. */
  4562. manhattanDistanceTo( v ) {
  4563. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4564. }
  4565. /**
  4566. * Sets the vector components from the given spherical coordinates.
  4567. *
  4568. * @param {Spherical} s - The spherical coordinates.
  4569. * @return {Vector3} A reference to this vector.
  4570. */
  4571. setFromSpherical( s ) {
  4572. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4573. }
  4574. /**
  4575. * Sets the vector components from the given spherical coordinates.
  4576. *
  4577. * @param {number} radius - The radius.
  4578. * @param {number} phi - The phi angle in radians.
  4579. * @param {number} theta - The theta angle in radians.
  4580. * @return {Vector3} A reference to this vector.
  4581. */
  4582. setFromSphericalCoords( radius, phi, theta ) {
  4583. const sinPhiRadius = Math.sin( phi ) * radius;
  4584. this.x = sinPhiRadius * Math.sin( theta );
  4585. this.y = Math.cos( phi ) * radius;
  4586. this.z = sinPhiRadius * Math.cos( theta );
  4587. return this;
  4588. }
  4589. /**
  4590. * Sets the vector components from the given cylindrical coordinates.
  4591. *
  4592. * @param {Cylindrical} c - The cylindrical coordinates.
  4593. * @return {Vector3} A reference to this vector.
  4594. */
  4595. setFromCylindrical( c ) {
  4596. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4597. }
  4598. /**
  4599. * Sets the vector components from the given cylindrical coordinates.
  4600. *
  4601. * @param {number} radius - The radius.
  4602. * @param {number} theta - The theta angle in radians.
  4603. * @param {number} y - The y value.
  4604. * @return {Vector3} A reference to this vector.
  4605. */
  4606. setFromCylindricalCoords( radius, theta, y ) {
  4607. this.x = radius * Math.sin( theta );
  4608. this.y = y;
  4609. this.z = radius * Math.cos( theta );
  4610. return this;
  4611. }
  4612. /**
  4613. * Sets the vector components to the position elements of the
  4614. * given transformation matrix.
  4615. *
  4616. * @param {Matrix4} m - The 4x4 matrix.
  4617. * @return {Vector3} A reference to this vector.
  4618. */
  4619. setFromMatrixPosition( m ) {
  4620. const e = m.elements;
  4621. this.x = e[ 12 ];
  4622. this.y = e[ 13 ];
  4623. this.z = e[ 14 ];
  4624. return this;
  4625. }
  4626. /**
  4627. * Sets the vector components to the scale elements of the
  4628. * given transformation matrix.
  4629. *
  4630. * @param {Matrix4} m - The 4x4 matrix.
  4631. * @return {Vector3} A reference to this vector.
  4632. */
  4633. setFromMatrixScale( m ) {
  4634. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4635. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4636. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4637. this.x = sx;
  4638. this.y = sy;
  4639. this.z = sz;
  4640. return this;
  4641. }
  4642. /**
  4643. * Sets the vector components from the specified matrix column.
  4644. *
  4645. * @param {Matrix4} m - The 4x4 matrix.
  4646. * @param {number} index - The column index.
  4647. * @return {Vector3} A reference to this vector.
  4648. */
  4649. setFromMatrixColumn( m, index ) {
  4650. return this.fromArray( m.elements, index * 4 );
  4651. }
  4652. /**
  4653. * Sets the vector components from the specified matrix column.
  4654. *
  4655. * @param {Matrix3} m - The 3x3 matrix.
  4656. * @param {number} index - The column index.
  4657. * @return {Vector3} A reference to this vector.
  4658. */
  4659. setFromMatrix3Column( m, index ) {
  4660. return this.fromArray( m.elements, index * 3 );
  4661. }
  4662. /**
  4663. * Sets the vector components from the given Euler angles.
  4664. *
  4665. * @param {Euler} e - The Euler angles to set.
  4666. * @return {Vector3} A reference to this vector.
  4667. */
  4668. setFromEuler( e ) {
  4669. this.x = e._x;
  4670. this.y = e._y;
  4671. this.z = e._z;
  4672. return this;
  4673. }
  4674. /**
  4675. * Sets the vector components from the RGB components of the
  4676. * given color.
  4677. *
  4678. * @param {Color} c - The color to set.
  4679. * @return {Vector3} A reference to this vector.
  4680. */
  4681. setFromColor( c ) {
  4682. this.x = c.r;
  4683. this.y = c.g;
  4684. this.z = c.b;
  4685. return this;
  4686. }
  4687. /**
  4688. * Returns `true` if this vector is equal with the given one.
  4689. *
  4690. * @param {Vector3} v - The vector to test for equality.
  4691. * @return {boolean} Whether this vector is equal with the given one.
  4692. */
  4693. equals( v ) {
  4694. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4695. }
  4696. /**
  4697. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4698. * and z value to be `array[ offset + 2 ]`.
  4699. *
  4700. * @param {Array<number>} array - An array holding the vector component values.
  4701. * @param {number} [offset=0] - The offset into the array.
  4702. * @return {Vector3} A reference to this vector.
  4703. */
  4704. fromArray( array, offset = 0 ) {
  4705. this.x = array[ offset ];
  4706. this.y = array[ offset + 1 ];
  4707. this.z = array[ offset + 2 ];
  4708. return this;
  4709. }
  4710. /**
  4711. * Writes the components of this vector to the given array. If no array is provided,
  4712. * the method returns a new instance.
  4713. *
  4714. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4715. * @param {number} [offset=0] - Index of the first element in the array.
  4716. * @return {Array<number>} The vector components.
  4717. */
  4718. toArray( array = [], offset = 0 ) {
  4719. array[ offset ] = this.x;
  4720. array[ offset + 1 ] = this.y;
  4721. array[ offset + 2 ] = this.z;
  4722. return array;
  4723. }
  4724. /**
  4725. * Sets the components of this vector from the given buffer attribute.
  4726. *
  4727. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4728. * @param {number} index - The index into the attribute.
  4729. * @return {Vector3} A reference to this vector.
  4730. */
  4731. fromBufferAttribute( attribute, index ) {
  4732. this.x = attribute.getX( index );
  4733. this.y = attribute.getY( index );
  4734. this.z = attribute.getZ( index );
  4735. return this;
  4736. }
  4737. /**
  4738. * Sets each component of this vector to a pseudo-random value between `0` and
  4739. * `1`, excluding `1`.
  4740. *
  4741. * @return {Vector3} A reference to this vector.
  4742. */
  4743. random() {
  4744. this.x = Math.random();
  4745. this.y = Math.random();
  4746. this.z = Math.random();
  4747. return this;
  4748. }
  4749. /**
  4750. * Sets this vector to a uniformly random point on a unit sphere.
  4751. *
  4752. * @return {Vector3} A reference to this vector.
  4753. */
  4754. randomDirection() {
  4755. // https://mathworld.wolfram.com/SpherePointPicking.html
  4756. const theta = Math.random() * Math.PI * 2;
  4757. const u = Math.random() * 2 - 1;
  4758. const c = Math.sqrt( 1 - u * u );
  4759. this.x = c * Math.cos( theta );
  4760. this.y = u;
  4761. this.z = c * Math.sin( theta );
  4762. return this;
  4763. }
  4764. *[ Symbol.iterator ]() {
  4765. yield this.x;
  4766. yield this.y;
  4767. yield this.z;
  4768. }
  4769. }
  4770. const _vector$c = /*@__PURE__*/ new Vector3();
  4771. const _quaternion$5 = /*@__PURE__*/ new Quaternion();
  4772. /**
  4773. * Represents a 3x3 matrix.
  4774. *
  4775. * A Note on Row-Major and Column-Major Ordering:
  4776. *
  4777. * The constructor and {@link Matrix3#set} method take arguments in
  4778. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4779. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4780. * This means that calling:
  4781. * ```js
  4782. * const m = new THREE.Matrix();
  4783. * m.set( 11, 12, 13,
  4784. * 21, 22, 23,
  4785. * 31, 32, 33 );
  4786. * ```
  4787. * will result in the elements array containing:
  4788. * ```js
  4789. * m.elements = [ 11, 21, 31,
  4790. * 12, 22, 32,
  4791. * 13, 23, 33 ];
  4792. * ```
  4793. * and internally all calculations are performed using column-major ordering.
  4794. * However, as the actual ordering makes no difference mathematically and
  4795. * most people are used to thinking about matrices in row-major order, the
  4796. * three.js documentation shows matrices in row-major order. Just bear in
  4797. * mind that if you are reading the source code, you'll have to take the
  4798. * transpose of any matrices outlined here to make sense of the calculations.
  4799. */
  4800. class Matrix3 {
  4801. static {
  4802. /**
  4803. * This flag can be used for type testing.
  4804. *
  4805. * @type {boolean}
  4806. * @readonly
  4807. * @default true
  4808. */
  4809. Matrix3.prototype.isMatrix3 = true;
  4810. }
  4811. /**
  4812. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4813. * in row-major order. If no arguments are provided, the constructor
  4814. * initializes the matrix as an identity matrix.
  4815. *
  4816. * @param {number} [n11] - 1-1 matrix element.
  4817. * @param {number} [n12] - 1-2 matrix element.
  4818. * @param {number} [n13] - 1-3 matrix element.
  4819. * @param {number} [n21] - 2-1 matrix element.
  4820. * @param {number} [n22] - 2-2 matrix element.
  4821. * @param {number} [n23] - 2-3 matrix element.
  4822. * @param {number} [n31] - 3-1 matrix element.
  4823. * @param {number} [n32] - 3-2 matrix element.
  4824. * @param {number} [n33] - 3-3 matrix element.
  4825. */
  4826. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4827. /**
  4828. * A column-major list of matrix values.
  4829. *
  4830. * @type {Array<number>}
  4831. */
  4832. this.elements = [
  4833. 1, 0, 0,
  4834. 0, 1, 0,
  4835. 0, 0, 1
  4836. ];
  4837. if ( n11 !== undefined ) {
  4838. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4839. }
  4840. }
  4841. /**
  4842. * Sets the elements of the matrix.The arguments are supposed to be
  4843. * in row-major order.
  4844. *
  4845. * @param {number} [n11] - 1-1 matrix element.
  4846. * @param {number} [n12] - 1-2 matrix element.
  4847. * @param {number} [n13] - 1-3 matrix element.
  4848. * @param {number} [n21] - 2-1 matrix element.
  4849. * @param {number} [n22] - 2-2 matrix element.
  4850. * @param {number} [n23] - 2-3 matrix element.
  4851. * @param {number} [n31] - 3-1 matrix element.
  4852. * @param {number} [n32] - 3-2 matrix element.
  4853. * @param {number} [n33] - 3-3 matrix element.
  4854. * @return {Matrix3} A reference to this matrix.
  4855. */
  4856. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4857. const te = this.elements;
  4858. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4859. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4860. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4861. return this;
  4862. }
  4863. /**
  4864. * Sets this matrix to the 3x3 identity matrix.
  4865. *
  4866. * @return {Matrix3} A reference to this matrix.
  4867. */
  4868. identity() {
  4869. this.set(
  4870. 1, 0, 0,
  4871. 0, 1, 0,
  4872. 0, 0, 1
  4873. );
  4874. return this;
  4875. }
  4876. /**
  4877. * Copies the values of the given matrix to this instance.
  4878. *
  4879. * @param {Matrix3} m - The matrix to copy.
  4880. * @return {Matrix3} A reference to this matrix.
  4881. */
  4882. copy( m ) {
  4883. const te = this.elements;
  4884. const me = m.elements;
  4885. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4886. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4887. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4888. return this;
  4889. }
  4890. /**
  4891. * Extracts the basis of this matrix into the three axis vectors provided.
  4892. *
  4893. * @param {Vector3} xAxis - The basis's x axis.
  4894. * @param {Vector3} yAxis - The basis's y axis.
  4895. * @param {Vector3} zAxis - The basis's z axis.
  4896. * @return {Matrix3} A reference to this matrix.
  4897. */
  4898. extractBasis( xAxis, yAxis, zAxis ) {
  4899. xAxis.setFromMatrix3Column( this, 0 );
  4900. yAxis.setFromMatrix3Column( this, 1 );
  4901. zAxis.setFromMatrix3Column( this, 2 );
  4902. return this;
  4903. }
  4904. /**
  4905. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4906. *
  4907. * @param {Matrix4} m - The 4x4 matrix.
  4908. * @return {Matrix3} A reference to this matrix.
  4909. */
  4910. setFromMatrix4( m ) {
  4911. const me = m.elements;
  4912. this.set(
  4913. me[ 0 ], me[ 4 ], me[ 8 ],
  4914. me[ 1 ], me[ 5 ], me[ 9 ],
  4915. me[ 2 ], me[ 6 ], me[ 10 ]
  4916. );
  4917. return this;
  4918. }
  4919. /**
  4920. * Post-multiplies this matrix by the given 3x3 matrix.
  4921. *
  4922. * @param {Matrix3} m - The matrix to multiply with.
  4923. * @return {Matrix3} A reference to this matrix.
  4924. */
  4925. multiply( m ) {
  4926. return this.multiplyMatrices( this, m );
  4927. }
  4928. /**
  4929. * Pre-multiplies this matrix by the given 3x3 matrix.
  4930. *
  4931. * @param {Matrix3} m - The matrix to multiply with.
  4932. * @return {Matrix3} A reference to this matrix.
  4933. */
  4934. premultiply( m ) {
  4935. return this.multiplyMatrices( m, this );
  4936. }
  4937. /**
  4938. * Multiples the given 3x3 matrices and stores the result
  4939. * in this matrix.
  4940. *
  4941. * @param {Matrix3} a - The first matrix.
  4942. * @param {Matrix3} b - The second matrix.
  4943. * @return {Matrix3} A reference to this matrix.
  4944. */
  4945. multiplyMatrices( a, b ) {
  4946. const ae = a.elements;
  4947. const be = b.elements;
  4948. const te = this.elements;
  4949. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4950. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4951. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4952. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4953. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4954. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4955. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4956. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4957. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4958. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4959. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4960. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4961. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4962. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4963. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4964. return this;
  4965. }
  4966. /**
  4967. * Multiplies every component of the matrix by the given scalar.
  4968. *
  4969. * @param {number} s - The scalar.
  4970. * @return {Matrix3} A reference to this matrix.
  4971. */
  4972. multiplyScalar( s ) {
  4973. const te = this.elements;
  4974. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4975. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4976. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4977. return this;
  4978. }
  4979. /**
  4980. * Computes and returns the determinant of this matrix.
  4981. *
  4982. * @return {number} The determinant.
  4983. */
  4984. determinant() {
  4985. const te = this.elements;
  4986. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4987. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4988. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4989. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4990. }
  4991. /**
  4992. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4993. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4994. * a zero matrix instead.
  4995. *
  4996. * @return {Matrix3} A reference to this matrix.
  4997. */
  4998. invert() {
  4999. const te = this.elements,
  5000. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  5001. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  5002. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  5003. t11 = n33 * n22 - n32 * n23,
  5004. t12 = n32 * n13 - n33 * n12,
  5005. t13 = n23 * n12 - n22 * n13,
  5006. det = n11 * t11 + n21 * t12 + n31 * t13;
  5007. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  5008. const detInv = 1 / det;
  5009. te[ 0 ] = t11 * detInv;
  5010. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  5011. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  5012. te[ 3 ] = t12 * detInv;
  5013. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  5014. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  5015. te[ 6 ] = t13 * detInv;
  5016. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  5017. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  5018. return this;
  5019. }
  5020. /**
  5021. * Transposes this matrix in place.
  5022. *
  5023. * @return {Matrix3} A reference to this matrix.
  5024. */
  5025. transpose() {
  5026. let tmp;
  5027. const m = this.elements;
  5028. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5029. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5030. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5031. return this;
  5032. }
  5033. /**
  5034. * Computes the normal matrix which is the inverse transpose of the upper
  5035. * left 3x3 portion of the given 4x4 matrix.
  5036. *
  5037. * @param {Matrix4} matrix4 - The 4x4 matrix.
  5038. * @return {Matrix3} A reference to this matrix.
  5039. */
  5040. getNormalMatrix( matrix4 ) {
  5041. return this.setFromMatrix4( matrix4 ).invert().transpose();
  5042. }
  5043. /**
  5044. * Transposes this matrix into the supplied array, and returns itself unchanged.
  5045. *
  5046. * @param {Array<number>} r - An array to store the transposed matrix elements.
  5047. * @return {Matrix3} A reference to this matrix.
  5048. */
  5049. transposeIntoArray( r ) {
  5050. const m = this.elements;
  5051. r[ 0 ] = m[ 0 ];
  5052. r[ 1 ] = m[ 3 ];
  5053. r[ 2 ] = m[ 6 ];
  5054. r[ 3 ] = m[ 1 ];
  5055. r[ 4 ] = m[ 4 ];
  5056. r[ 5 ] = m[ 7 ];
  5057. r[ 6 ] = m[ 2 ];
  5058. r[ 7 ] = m[ 5 ];
  5059. r[ 8 ] = m[ 8 ];
  5060. return this;
  5061. }
  5062. /**
  5063. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  5064. *
  5065. * @param {number} tx - Offset x.
  5066. * @param {number} ty - Offset y.
  5067. * @param {number} sx - Repeat x.
  5068. * @param {number} sy - Repeat y.
  5069. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  5070. * @param {number} cx - Center x of rotation.
  5071. * @param {number} cy - Center y of rotation
  5072. * @return {Matrix3} A reference to this matrix.
  5073. */
  5074. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  5075. const c = Math.cos( rotation );
  5076. const s = Math.sin( rotation );
  5077. this.set(
  5078. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  5079. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  5080. 0, 0, 1
  5081. );
  5082. return this;
  5083. }
  5084. /**
  5085. * Scales this matrix with the given scalar values.
  5086. *
  5087. * @param {number} sx - The amount to scale in the X axis.
  5088. * @param {number} sy - The amount to scale in the Y axis.
  5089. * @return {Matrix3} A reference to this matrix.
  5090. */
  5091. scale( sx, sy ) {
  5092. this.premultiply( _m3.makeScale( sx, sy ) );
  5093. return this;
  5094. }
  5095. /**
  5096. * Rotates this matrix by the given angle.
  5097. *
  5098. * @param {number} theta - The rotation in radians.
  5099. * @return {Matrix3} A reference to this matrix.
  5100. */
  5101. rotate( theta ) {
  5102. this.premultiply( _m3.makeRotation( - theta ) );
  5103. return this;
  5104. }
  5105. /**
  5106. * Translates this matrix by the given scalar values.
  5107. *
  5108. * @param {number} tx - The amount to translate in the X axis.
  5109. * @param {number} ty - The amount to translate in the Y axis.
  5110. * @return {Matrix3} A reference to this matrix.
  5111. */
  5112. translate( tx, ty ) {
  5113. this.premultiply( _m3.makeTranslation( tx, ty ) );
  5114. return this;
  5115. }
  5116. // for 2D Transforms
  5117. /**
  5118. * Sets this matrix as a 2D translation transform.
  5119. *
  5120. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  5121. * @param {number} y - The amount to translate in the Y axis.
  5122. * @return {Matrix3} A reference to this matrix.
  5123. */
  5124. makeTranslation( x, y ) {
  5125. if ( x.isVector2 ) {
  5126. this.set(
  5127. 1, 0, x.x,
  5128. 0, 1, x.y,
  5129. 0, 0, 1
  5130. );
  5131. } else {
  5132. this.set(
  5133. 1, 0, x,
  5134. 0, 1, y,
  5135. 0, 0, 1
  5136. );
  5137. }
  5138. return this;
  5139. }
  5140. /**
  5141. * Sets this matrix as a 2D rotational transformation.
  5142. *
  5143. * @param {number} theta - The rotation in radians.
  5144. * @return {Matrix3} A reference to this matrix.
  5145. */
  5146. makeRotation( theta ) {
  5147. // counterclockwise
  5148. const c = Math.cos( theta );
  5149. const s = Math.sin( theta );
  5150. this.set(
  5151. c, - s, 0,
  5152. s, c, 0,
  5153. 0, 0, 1
  5154. );
  5155. return this;
  5156. }
  5157. /**
  5158. * Sets this matrix as a 2D scale transform.
  5159. *
  5160. * @param {number} x - The amount to scale in the X axis.
  5161. * @param {number} y - The amount to scale in the Y axis.
  5162. * @return {Matrix3} A reference to this matrix.
  5163. */
  5164. makeScale( x, y ) {
  5165. this.set(
  5166. x, 0, 0,
  5167. 0, y, 0,
  5168. 0, 0, 1
  5169. );
  5170. return this;
  5171. }
  5172. /**
  5173. * Returns `true` if this matrix is equal with the given one.
  5174. *
  5175. * @param {Matrix3} matrix - The matrix to test for equality.
  5176. * @return {boolean} Whether this matrix is equal with the given one.
  5177. */
  5178. equals( matrix ) {
  5179. const te = this.elements;
  5180. const me = matrix.elements;
  5181. for ( let i = 0; i < 9; i ++ ) {
  5182. if ( te[ i ] !== me[ i ] ) return false;
  5183. }
  5184. return true;
  5185. }
  5186. /**
  5187. * Sets the elements of the matrix from the given array.
  5188. *
  5189. * @param {Array<number>} array - The matrix elements in column-major order.
  5190. * @param {number} [offset=0] - Index of the first element in the array.
  5191. * @return {Matrix3} A reference to this matrix.
  5192. */
  5193. fromArray( array, offset = 0 ) {
  5194. for ( let i = 0; i < 9; i ++ ) {
  5195. this.elements[ i ] = array[ i + offset ];
  5196. }
  5197. return this;
  5198. }
  5199. /**
  5200. * Writes the elements of this matrix to the given array. If no array is provided,
  5201. * the method returns a new instance.
  5202. *
  5203. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5204. * @param {number} [offset=0] - Index of the first element in the array.
  5205. * @return {Array<number>} The matrix elements in column-major order.
  5206. */
  5207. toArray( array = [], offset = 0 ) {
  5208. const te = this.elements;
  5209. array[ offset ] = te[ 0 ];
  5210. array[ offset + 1 ] = te[ 1 ];
  5211. array[ offset + 2 ] = te[ 2 ];
  5212. array[ offset + 3 ] = te[ 3 ];
  5213. array[ offset + 4 ] = te[ 4 ];
  5214. array[ offset + 5 ] = te[ 5 ];
  5215. array[ offset + 6 ] = te[ 6 ];
  5216. array[ offset + 7 ] = te[ 7 ];
  5217. array[ offset + 8 ] = te[ 8 ];
  5218. return array;
  5219. }
  5220. /**
  5221. * Returns a matrix with copied values from this instance.
  5222. *
  5223. * @return {Matrix3} A clone of this instance.
  5224. */
  5225. clone() {
  5226. return new this.constructor().fromArray( this.elements );
  5227. }
  5228. }
  5229. const _m3 = /*@__PURE__*/ new Matrix3();
  5230. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5231. 0.4123908, 0.3575843, 0.1804808,
  5232. 0.2126390, 0.7151687, 0.0721923,
  5233. 0.0193308, 0.1191948, 0.9505322
  5234. );
  5235. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5236. 3.2409699, -1.5373832, -0.4986108,
  5237. -0.9692436, 1.8759675, 0.0415551,
  5238. 0.0556301, -0.203977, 1.0569715
  5239. );
  5240. function createColorManagement() {
  5241. const ColorManagement = {
  5242. enabled: true,
  5243. workingColorSpace: LinearSRGBColorSpace,
  5244. /**
  5245. * Implementations of supported color spaces.
  5246. *
  5247. * Required:
  5248. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5249. * - whitePoint: reference white [ x y ]
  5250. * - transfer: transfer function (pre-defined)
  5251. * - toXYZ: Matrix3 RGB to XYZ transform
  5252. * - fromXYZ: Matrix3 XYZ to RGB transform
  5253. * - luminanceCoefficients: RGB luminance coefficients
  5254. *
  5255. * Optional:
  5256. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5257. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5258. *
  5259. * Reference:
  5260. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5261. */
  5262. spaces: {},
  5263. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5264. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5265. return color;
  5266. }
  5267. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5268. color.r = SRGBToLinear( color.r );
  5269. color.g = SRGBToLinear( color.g );
  5270. color.b = SRGBToLinear( color.b );
  5271. }
  5272. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5273. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5274. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5275. }
  5276. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5277. color.r = LinearToSRGB( color.r );
  5278. color.g = LinearToSRGB( color.g );
  5279. color.b = LinearToSRGB( color.b );
  5280. }
  5281. return color;
  5282. },
  5283. workingToColorSpace: function ( color, targetColorSpace ) {
  5284. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5285. },
  5286. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5287. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5288. },
  5289. getPrimaries: function ( colorSpace ) {
  5290. return this.spaces[ colorSpace ].primaries;
  5291. },
  5292. getTransfer: function ( colorSpace ) {
  5293. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5294. return this.spaces[ colorSpace ].transfer;
  5295. },
  5296. getToneMappingMode: function ( colorSpace ) {
  5297. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5298. },
  5299. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5300. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5301. },
  5302. define: function ( colorSpaces ) {
  5303. Object.assign( this.spaces, colorSpaces );
  5304. },
  5305. // Internal APIs
  5306. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5307. return targetMatrix
  5308. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5309. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5310. },
  5311. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5312. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5313. },
  5314. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5315. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5316. },
  5317. // Deprecated
  5318. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5319. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5320. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5321. },
  5322. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5323. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5324. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5325. },
  5326. };
  5327. /******************************************************************************
  5328. * sRGB definitions
  5329. */
  5330. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5331. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5332. const D65 = [ 0.3127, 0.3290 ];
  5333. ColorManagement.define( {
  5334. [ LinearSRGBColorSpace ]: {
  5335. primaries: REC709_PRIMARIES,
  5336. whitePoint: D65,
  5337. transfer: LinearTransfer,
  5338. toXYZ: LINEAR_REC709_TO_XYZ,
  5339. fromXYZ: XYZ_TO_LINEAR_REC709,
  5340. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5341. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5342. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5343. },
  5344. [ SRGBColorSpace ]: {
  5345. primaries: REC709_PRIMARIES,
  5346. whitePoint: D65,
  5347. transfer: SRGBTransfer,
  5348. toXYZ: LINEAR_REC709_TO_XYZ,
  5349. fromXYZ: XYZ_TO_LINEAR_REC709,
  5350. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5351. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5352. },
  5353. } );
  5354. return ColorManagement;
  5355. }
  5356. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5357. function SRGBToLinear( c ) {
  5358. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5359. }
  5360. function LinearToSRGB( c ) {
  5361. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5362. }
  5363. let _canvas;
  5364. /**
  5365. * A class containing utility functions for images.
  5366. *
  5367. * @hideconstructor
  5368. */
  5369. class ImageUtils {
  5370. /**
  5371. * Returns a data URI containing a representation of the given image.
  5372. *
  5373. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5374. * @param {string} [type='image/png'] - Indicates the image format.
  5375. * @return {string} The data URI.
  5376. */
  5377. static getDataURL( image, type = 'image/png' ) {
  5378. if ( /^data:/i.test( image.src ) ) {
  5379. return image.src;
  5380. }
  5381. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5382. return image.src;
  5383. }
  5384. let canvas;
  5385. if ( image instanceof HTMLCanvasElement ) {
  5386. canvas = image;
  5387. } else {
  5388. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5389. _canvas.width = image.width;
  5390. _canvas.height = image.height;
  5391. const context = _canvas.getContext( '2d' );
  5392. if ( image instanceof ImageData ) {
  5393. context.putImageData( image, 0, 0 );
  5394. } else {
  5395. context.drawImage( image, 0, 0, image.width, image.height );
  5396. }
  5397. canvas = _canvas;
  5398. }
  5399. return canvas.toDataURL( type );
  5400. }
  5401. /**
  5402. * Converts the given sRGB image data to linear color space.
  5403. *
  5404. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5405. * @return {HTMLCanvasElement|Object} The converted image.
  5406. */
  5407. static sRGBToLinear( image ) {
  5408. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5409. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5410. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5411. const canvas = createElementNS( 'canvas' );
  5412. canvas.width = image.width;
  5413. canvas.height = image.height;
  5414. const context = canvas.getContext( '2d' );
  5415. context.drawImage( image, 0, 0, image.width, image.height );
  5416. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5417. const data = imageData.data;
  5418. for ( let i = 0; i < data.length; i ++ ) {
  5419. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5420. }
  5421. context.putImageData( imageData, 0, 0 );
  5422. return canvas;
  5423. } else if ( image.data ) {
  5424. const data = image.data.slice( 0 );
  5425. for ( let i = 0; i < data.length; i ++ ) {
  5426. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5427. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5428. } else {
  5429. // assuming float
  5430. data[ i ] = SRGBToLinear( data[ i ] );
  5431. }
  5432. }
  5433. return {
  5434. data: data,
  5435. width: image.width,
  5436. height: image.height
  5437. };
  5438. } else {
  5439. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5440. return image;
  5441. }
  5442. }
  5443. }
  5444. let _sourceId = 0;
  5445. /**
  5446. * Represents the data source of a texture.
  5447. *
  5448. * The main purpose of this class is to decouple the data definition from the texture
  5449. * definition so the same data can be used with multiple texture instances.
  5450. */
  5451. class Source {
  5452. /**
  5453. * Constructs a new video texture.
  5454. *
  5455. * @param {any} [data=null] - The data definition of a texture.
  5456. */
  5457. constructor( data = null ) {
  5458. /**
  5459. * This flag can be used for type testing.
  5460. *
  5461. * @type {boolean}
  5462. * @readonly
  5463. * @default true
  5464. */
  5465. this.isSource = true;
  5466. /**
  5467. * The ID of the source.
  5468. *
  5469. * @name Source#id
  5470. * @type {number}
  5471. * @readonly
  5472. */
  5473. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5474. /**
  5475. * The UUID of the source.
  5476. *
  5477. * @type {string}
  5478. * @readonly
  5479. */
  5480. this.uuid = generateUUID();
  5481. /**
  5482. * The data definition of a texture.
  5483. *
  5484. * @type {any}
  5485. */
  5486. this.data = data;
  5487. /**
  5488. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5489. * provides more control on how texture data should be processed. When `dataReady` is set
  5490. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5491. * the data into the GPU memory.
  5492. *
  5493. * @type {boolean}
  5494. * @default true
  5495. */
  5496. this.dataReady = true;
  5497. /**
  5498. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5499. *
  5500. * @type {number}
  5501. * @readonly
  5502. * @default 0
  5503. */
  5504. this.version = 0;
  5505. }
  5506. /**
  5507. * Returns the dimensions of the source into the given target vector.
  5508. *
  5509. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5510. * @return {(Vector2|Vector3)} The dimensions of the source.
  5511. */
  5512. getSize( target ) {
  5513. const data = this.data;
  5514. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5515. target.set( data.videoWidth, data.videoHeight, 0 );
  5516. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5517. target.set( data.displayWidth, data.displayHeight, 0 );
  5518. } else if ( data !== null ) {
  5519. target.set( data.width, data.height, data.depth || 0 );
  5520. } else {
  5521. target.set( 0, 0, 0 );
  5522. }
  5523. return target;
  5524. }
  5525. /**
  5526. * When the property is set to `true`, the engine allocates the memory
  5527. * for the texture (if necessary) and triggers the actual texture upload
  5528. * to the GPU next time the source is used.
  5529. *
  5530. * @type {boolean}
  5531. * @default false
  5532. * @param {boolean} value
  5533. */
  5534. set needsUpdate( value ) {
  5535. if ( value === true ) this.version ++;
  5536. }
  5537. /**
  5538. * Serializes the source into JSON.
  5539. *
  5540. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5541. * @return {Object} A JSON object representing the serialized source.
  5542. * @see {@link ObjectLoader#parse}
  5543. */
  5544. toJSON( meta ) {
  5545. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5546. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5547. return meta.images[ this.uuid ];
  5548. }
  5549. const output = {
  5550. uuid: this.uuid,
  5551. url: ''
  5552. };
  5553. const data = this.data;
  5554. if ( data !== null ) {
  5555. let url;
  5556. if ( Array.isArray( data ) ) {
  5557. // cube texture
  5558. url = [];
  5559. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5560. if ( data[ i ].isDataTexture ) {
  5561. url.push( serializeImage( data[ i ].image ) );
  5562. } else {
  5563. url.push( serializeImage( data[ i ] ) );
  5564. }
  5565. }
  5566. } else {
  5567. // texture
  5568. url = serializeImage( data );
  5569. }
  5570. output.url = url;
  5571. }
  5572. if ( ! isRootObject ) {
  5573. meta.images[ this.uuid ] = output;
  5574. }
  5575. return output;
  5576. }
  5577. }
  5578. function serializeImage( image ) {
  5579. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5580. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5581. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5582. // default images
  5583. return ImageUtils.getDataURL( image );
  5584. } else {
  5585. if ( image.data ) {
  5586. // images of DataTexture
  5587. return {
  5588. data: Array.from( image.data ),
  5589. width: image.width,
  5590. height: image.height,
  5591. type: image.data.constructor.name
  5592. };
  5593. } else {
  5594. warn( 'Texture: Unable to serialize Texture.' );
  5595. return {};
  5596. }
  5597. }
  5598. }
  5599. let _textureId = 0;
  5600. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5601. /**
  5602. * Base class for all textures.
  5603. *
  5604. * Note: After the initial use of a texture, its dimensions, format, and type
  5605. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5606. *
  5607. * @augments EventDispatcher
  5608. */
  5609. class Texture extends EventDispatcher {
  5610. /**
  5611. * Constructs a new texture.
  5612. *
  5613. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5614. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5615. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5616. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5617. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5618. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5619. * @param {number} [format=RGBAFormat] - The texture format.
  5620. * @param {number} [type=UnsignedByteType] - The texture type.
  5621. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5622. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5623. */
  5624. 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 ) {
  5625. super();
  5626. /**
  5627. * This flag can be used for type testing.
  5628. *
  5629. * @type {boolean}
  5630. * @readonly
  5631. * @default true
  5632. */
  5633. this.isTexture = true;
  5634. /**
  5635. * The ID of the texture.
  5636. *
  5637. * @name Texture#id
  5638. * @type {number}
  5639. * @readonly
  5640. */
  5641. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5642. /**
  5643. * The UUID of the texture.
  5644. *
  5645. * @type {string}
  5646. * @readonly
  5647. */
  5648. this.uuid = generateUUID();
  5649. /**
  5650. * The name of the texture.
  5651. *
  5652. * @type {string}
  5653. */
  5654. this.name = '';
  5655. /**
  5656. * The data definition of a texture. A reference to the data source can be
  5657. * shared across textures. This is often useful in context of spritesheets
  5658. * where multiple textures render the same data but with different texture
  5659. * transformations.
  5660. *
  5661. * @type {Source}
  5662. */
  5663. this.source = new Source( image );
  5664. /**
  5665. * An array holding user-defined mipmaps.
  5666. *
  5667. * @type {Array<Object>}
  5668. */
  5669. this.mipmaps = [];
  5670. /**
  5671. * How the texture is applied to the object. The value `UVMapping`
  5672. * is the default, where texture or uv coordinates are used to apply the map.
  5673. *
  5674. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5675. * @default UVMapping
  5676. */
  5677. this.mapping = mapping;
  5678. /**
  5679. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5680. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5681. *
  5682. * @type {number}
  5683. * @default 0
  5684. */
  5685. this.channel = 0;
  5686. /**
  5687. * This defines how the texture is wrapped horizontally and corresponds to
  5688. * *U* in UV mapping.
  5689. *
  5690. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5691. * @default ClampToEdgeWrapping
  5692. */
  5693. this.wrapS = wrapS;
  5694. /**
  5695. * This defines how the texture is wrapped horizontally and corresponds to
  5696. * *V* in UV mapping.
  5697. *
  5698. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5699. * @default ClampToEdgeWrapping
  5700. */
  5701. this.wrapT = wrapT;
  5702. /**
  5703. * How the texture is sampled when a texel covers more than one pixel.
  5704. *
  5705. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5706. * @default LinearFilter
  5707. */
  5708. this.magFilter = magFilter;
  5709. /**
  5710. * How the texture is sampled when a texel covers less than one pixel.
  5711. *
  5712. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5713. * @default LinearMipmapLinearFilter
  5714. */
  5715. this.minFilter = minFilter;
  5716. /**
  5717. * The number of samples taken along the axis through the pixel that has the
  5718. * highest density of texels. By default, this value is `1`. A higher value
  5719. * gives a less blurry result than a basic mipmap, at the cost of more
  5720. * texture samples being used.
  5721. *
  5722. * @type {number}
  5723. * @default Texture.DEFAULT_ANISOTROPY
  5724. */
  5725. this.anisotropy = anisotropy;
  5726. /**
  5727. * The format of the texture.
  5728. *
  5729. * @type {number}
  5730. * @default RGBAFormat
  5731. */
  5732. this.format = format;
  5733. /**
  5734. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5735. * defines how the texture data is going to be stored on the GPU.
  5736. *
  5737. * This property allows to overwrite the default format.
  5738. *
  5739. * @type {?string}
  5740. * @default null
  5741. */
  5742. this.internalFormat = null;
  5743. /**
  5744. * The data type of the texture.
  5745. *
  5746. * @type {number}
  5747. * @default UnsignedByteType
  5748. */
  5749. this.type = type;
  5750. /**
  5751. * How much a single repetition of the texture is offset from the beginning,
  5752. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5753. *
  5754. * @type {Vector2}
  5755. * @default (0,0)
  5756. */
  5757. this.offset = new Vector2( 0, 0 );
  5758. /**
  5759. * How many times the texture is repeated across the surface, in each
  5760. * direction U and V. If repeat is set greater than `1` in either direction,
  5761. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5762. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5763. *
  5764. * @type {Vector2}
  5765. * @default (1,1)
  5766. */
  5767. this.repeat = new Vector2( 1, 1 );
  5768. /**
  5769. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5770. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5771. *
  5772. * @type {Vector2}
  5773. * @default (0,0)
  5774. */
  5775. this.center = new Vector2( 0, 0 );
  5776. /**
  5777. * How much the texture is rotated around the center point, in radians.
  5778. * Positive values are counter-clockwise.
  5779. *
  5780. * @type {number}
  5781. * @default 0
  5782. */
  5783. this.rotation = 0;
  5784. /**
  5785. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5786. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5787. * {@link Texture#rotation}, and {@link Texture#center}.
  5788. *
  5789. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5790. *
  5791. * @type {boolean}
  5792. * @default true
  5793. */
  5794. this.matrixAutoUpdate = true;
  5795. /**
  5796. * The uv-transformation matrix of the texture.
  5797. *
  5798. * @type {Matrix3}
  5799. */
  5800. this.matrix = new Matrix3();
  5801. /**
  5802. * Whether to generate mipmaps (if possible) for a texture.
  5803. *
  5804. * Set this to `false` if you are creating mipmaps manually.
  5805. *
  5806. * @type {boolean}
  5807. * @default true
  5808. */
  5809. this.generateMipmaps = true;
  5810. /**
  5811. * If set to `true`, the alpha channel, if present, is multiplied into the
  5812. * color channels when the texture is uploaded to the GPU.
  5813. *
  5814. * Note that this property has no effect when using `ImageBitmap`. You need to
  5815. * configure premultiply alpha on bitmap creation instead.
  5816. *
  5817. * @type {boolean}
  5818. * @default false
  5819. */
  5820. this.premultiplyAlpha = false;
  5821. /**
  5822. * If set to `true`, the texture is flipped along the vertical axis when
  5823. * uploaded to the GPU.
  5824. *
  5825. * Note that this property has no effect when using `ImageBitmap`. You need to
  5826. * configure the flip on bitmap creation instead.
  5827. *
  5828. * @type {boolean}
  5829. * @default true
  5830. */
  5831. this.flipY = true;
  5832. /**
  5833. * Specifies the alignment requirements for the start of each pixel row in memory.
  5834. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5835. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5836. *
  5837. * @type {number}
  5838. * @default 4
  5839. */
  5840. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5841. /**
  5842. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5843. *
  5844. * @type {string}
  5845. * @default NoColorSpace
  5846. */
  5847. this.colorSpace = colorSpace;
  5848. /**
  5849. * An object that can be used to store custom data about the texture. It
  5850. * should not hold references to functions as these will not be cloned.
  5851. *
  5852. * @type {Object}
  5853. */
  5854. this.userData = {};
  5855. /**
  5856. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5857. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5858. *
  5859. * @type {Array<Object>}
  5860. */
  5861. this.updateRanges = [];
  5862. /**
  5863. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5864. *
  5865. * @type {number}
  5866. * @readonly
  5867. * @default 0
  5868. */
  5869. this.version = 0;
  5870. /**
  5871. * A callback function, called when the texture is updated (e.g., when
  5872. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5873. *
  5874. * @type {?Function}
  5875. * @default null
  5876. */
  5877. this.onUpdate = null;
  5878. /**
  5879. * An optional back reference to the textures render target.
  5880. *
  5881. * @type {?(RenderTarget|WebGLRenderTarget)}
  5882. * @default null
  5883. */
  5884. this.renderTarget = null;
  5885. /**
  5886. * Indicates whether a texture belongs to a render target or not.
  5887. *
  5888. * @type {boolean}
  5889. * @readonly
  5890. * @default false
  5891. */
  5892. this.isRenderTargetTexture = false;
  5893. /**
  5894. * Indicates if a texture should be handled like a texture array.
  5895. *
  5896. * @type {boolean}
  5897. * @readonly
  5898. * @default false
  5899. */
  5900. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5901. /**
  5902. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5903. * (only relevant for render target textures).
  5904. *
  5905. * @type {number}
  5906. * @readonly
  5907. * @default 0
  5908. */
  5909. this.pmremVersion = 0;
  5910. /**
  5911. * Whether the texture should use one of the 16 bit integer formats which are normalized
  5912. * to [0, 1] or [-1, 1] (depending on signed/unsigned) when sampled.
  5913. *
  5914. * @type {boolean}
  5915. * @default false
  5916. */
  5917. this.normalized = false;
  5918. }
  5919. /**
  5920. * The width of the texture in pixels.
  5921. */
  5922. get width() {
  5923. return this.source.getSize( _tempVec3 ).x;
  5924. }
  5925. /**
  5926. * The height of the texture in pixels.
  5927. */
  5928. get height() {
  5929. return this.source.getSize( _tempVec3 ).y;
  5930. }
  5931. /**
  5932. * The depth of the texture in pixels.
  5933. */
  5934. get depth() {
  5935. return this.source.getSize( _tempVec3 ).z;
  5936. }
  5937. /**
  5938. * The image object holding the texture data.
  5939. *
  5940. * @type {?Object}
  5941. */
  5942. get image() {
  5943. return this.source.data;
  5944. }
  5945. set image( value ) {
  5946. this.source.data = value;
  5947. }
  5948. /**
  5949. * Updates the texture transformation matrix from the properties {@link Texture#offset},
  5950. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5951. */
  5952. updateMatrix() {
  5953. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5954. }
  5955. /**
  5956. * Adds a range of data in the data texture to be updated on the GPU.
  5957. *
  5958. * @param {number} start - Position at which to start update.
  5959. * @param {number} count - The number of components to update.
  5960. */
  5961. addUpdateRange( start, count ) {
  5962. this.updateRanges.push( { start, count } );
  5963. }
  5964. /**
  5965. * Clears the update ranges.
  5966. */
  5967. clearUpdateRanges() {
  5968. this.updateRanges.length = 0;
  5969. }
  5970. /**
  5971. * Returns a new texture with copied values from this instance.
  5972. *
  5973. * @return {Texture} A clone of this instance.
  5974. */
  5975. clone() {
  5976. return new this.constructor().copy( this );
  5977. }
  5978. /**
  5979. * Copies the values of the given texture to this instance.
  5980. *
  5981. * @param {Texture} source - The texture to copy.
  5982. * @return {Texture} A reference to this instance.
  5983. */
  5984. copy( source ) {
  5985. this.name = source.name;
  5986. this.source = source.source;
  5987. this.mipmaps = source.mipmaps.slice( 0 );
  5988. this.mapping = source.mapping;
  5989. this.channel = source.channel;
  5990. this.wrapS = source.wrapS;
  5991. this.wrapT = source.wrapT;
  5992. this.magFilter = source.magFilter;
  5993. this.minFilter = source.minFilter;
  5994. this.anisotropy = source.anisotropy;
  5995. this.format = source.format;
  5996. this.internalFormat = source.internalFormat;
  5997. this.type = source.type;
  5998. this.normalized = source.normalized;
  5999. this.offset.copy( source.offset );
  6000. this.repeat.copy( source.repeat );
  6001. this.center.copy( source.center );
  6002. this.rotation = source.rotation;
  6003. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6004. this.matrix.copy( source.matrix );
  6005. this.generateMipmaps = source.generateMipmaps;
  6006. this.premultiplyAlpha = source.premultiplyAlpha;
  6007. this.flipY = source.flipY;
  6008. this.unpackAlignment = source.unpackAlignment;
  6009. this.colorSpace = source.colorSpace;
  6010. this.renderTarget = source.renderTarget;
  6011. this.isRenderTargetTexture = source.isRenderTargetTexture;
  6012. this.isArrayTexture = source.isArrayTexture;
  6013. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6014. this.needsUpdate = true;
  6015. return this;
  6016. }
  6017. /**
  6018. * Sets this texture's properties based on `values`.
  6019. * @param {Object} values - A container with texture parameters.
  6020. */
  6021. setValues( values ) {
  6022. for ( const key in values ) {
  6023. const newValue = values[ key ];
  6024. if ( newValue === undefined ) {
  6025. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  6026. continue;
  6027. }
  6028. const currentValue = this[ key ];
  6029. if ( currentValue === undefined ) {
  6030. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  6031. continue;
  6032. }
  6033. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  6034. currentValue.copy( newValue );
  6035. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  6036. currentValue.copy( newValue );
  6037. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  6038. currentValue.copy( newValue );
  6039. } else {
  6040. this[ key ] = newValue;
  6041. }
  6042. }
  6043. }
  6044. /**
  6045. * Serializes the texture into JSON.
  6046. *
  6047. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  6048. * @return {Object} A JSON object representing the serialized texture.
  6049. * @see {@link ObjectLoader#parse}
  6050. */
  6051. toJSON( meta ) {
  6052. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  6053. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6054. return meta.textures[ this.uuid ];
  6055. }
  6056. const output = {
  6057. metadata: {
  6058. version: 4.7,
  6059. type: 'Texture',
  6060. generator: 'Texture.toJSON'
  6061. },
  6062. uuid: this.uuid,
  6063. name: this.name,
  6064. image: this.source.toJSON( meta ).uuid,
  6065. mapping: this.mapping,
  6066. channel: this.channel,
  6067. repeat: [ this.repeat.x, this.repeat.y ],
  6068. offset: [ this.offset.x, this.offset.y ],
  6069. center: [ this.center.x, this.center.y ],
  6070. rotation: this.rotation,
  6071. wrap: [ this.wrapS, this.wrapT ],
  6072. format: this.format,
  6073. internalFormat: this.internalFormat,
  6074. type: this.type,
  6075. normalized: this.normalized,
  6076. colorSpace: this.colorSpace,
  6077. minFilter: this.minFilter,
  6078. magFilter: this.magFilter,
  6079. anisotropy: this.anisotropy,
  6080. flipY: this.flipY,
  6081. generateMipmaps: this.generateMipmaps,
  6082. premultiplyAlpha: this.premultiplyAlpha,
  6083. unpackAlignment: this.unpackAlignment
  6084. };
  6085. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6086. if ( ! isRootObject ) {
  6087. meta.textures[ this.uuid ] = output;
  6088. }
  6089. return output;
  6090. }
  6091. /**
  6092. * Frees the GPU-related resources allocated by this instance. Call this
  6093. * method whenever this instance is no longer used in your app.
  6094. *
  6095. * @fires Texture#dispose
  6096. */
  6097. dispose() {
  6098. /**
  6099. * Fires when the texture has been disposed of.
  6100. *
  6101. * @event Texture#dispose
  6102. * @type {Object}
  6103. */
  6104. this.dispatchEvent( { type: 'dispose' } );
  6105. }
  6106. /**
  6107. * Transforms the given uv vector with the textures uv transformation matrix.
  6108. *
  6109. * @param {Vector2} uv - The uv vector.
  6110. * @return {Vector2} The transformed uv vector.
  6111. */
  6112. transformUv( uv ) {
  6113. if ( this.mapping !== UVMapping ) return uv;
  6114. uv.applyMatrix3( this.matrix );
  6115. if ( uv.x < 0 || uv.x > 1 ) {
  6116. switch ( this.wrapS ) {
  6117. case RepeatWrapping:
  6118. uv.x = uv.x - Math.floor( uv.x );
  6119. break;
  6120. case ClampToEdgeWrapping:
  6121. uv.x = uv.x < 0 ? 0 : 1;
  6122. break;
  6123. case MirroredRepeatWrapping:
  6124. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6125. uv.x = Math.ceil( uv.x ) - uv.x;
  6126. } else {
  6127. uv.x = uv.x - Math.floor( uv.x );
  6128. }
  6129. break;
  6130. }
  6131. }
  6132. if ( uv.y < 0 || uv.y > 1 ) {
  6133. switch ( this.wrapT ) {
  6134. case RepeatWrapping:
  6135. uv.y = uv.y - Math.floor( uv.y );
  6136. break;
  6137. case ClampToEdgeWrapping:
  6138. uv.y = uv.y < 0 ? 0 : 1;
  6139. break;
  6140. case MirroredRepeatWrapping:
  6141. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6142. uv.y = Math.ceil( uv.y ) - uv.y;
  6143. } else {
  6144. uv.y = uv.y - Math.floor( uv.y );
  6145. }
  6146. break;
  6147. }
  6148. }
  6149. if ( this.flipY ) {
  6150. uv.y = 1 - uv.y;
  6151. }
  6152. return uv;
  6153. }
  6154. /**
  6155. * Setting this property to `true` indicates the engine the texture
  6156. * must be updated in the next render. This triggers a texture upload
  6157. * to the GPU and ensures correct texture parameter configuration.
  6158. *
  6159. * @type {boolean}
  6160. * @default false
  6161. * @param {boolean} value
  6162. */
  6163. set needsUpdate( value ) {
  6164. if ( value === true ) {
  6165. this.version ++;
  6166. this.source.needsUpdate = true;
  6167. }
  6168. }
  6169. /**
  6170. * Setting this property to `true` indicates the engine the PMREM
  6171. * must be regenerated.
  6172. *
  6173. * @type {boolean}
  6174. * @default false
  6175. * @param {boolean} value
  6176. */
  6177. set needsPMREMUpdate( value ) {
  6178. if ( value === true ) {
  6179. this.pmremVersion ++;
  6180. }
  6181. }
  6182. }
  6183. /**
  6184. * The default image for all textures.
  6185. *
  6186. * @static
  6187. * @type {?Image}
  6188. * @default null
  6189. */
  6190. Texture.DEFAULT_IMAGE = null;
  6191. /**
  6192. * The default mapping for all textures.
  6193. *
  6194. * @static
  6195. * @type {number}
  6196. * @default UVMapping
  6197. */
  6198. Texture.DEFAULT_MAPPING = UVMapping;
  6199. /**
  6200. * The default anisotropy value for all textures.
  6201. *
  6202. * @static
  6203. * @type {number}
  6204. * @default 1
  6205. */
  6206. Texture.DEFAULT_ANISOTROPY = 1;
  6207. /**
  6208. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6209. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6210. *
  6211. * - A point in 4D space.
  6212. * - A direction and length in 4D space. In three.js the length will
  6213. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6214. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6215. * - Any arbitrary ordered quadruplet of numbers.
  6216. *
  6217. * There are other things a 4D vector can be used to represent, however these
  6218. * are the most common uses in *three.js*.
  6219. *
  6220. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6221. * the corresponding order.
  6222. * ```js
  6223. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6224. *
  6225. * //no arguments; will be initialised to (0, 0, 0, 1)
  6226. * const b = new THREE.Vector4( );
  6227. *
  6228. * const d = a.dot( b );
  6229. * ```
  6230. */
  6231. class Vector4 {
  6232. static {
  6233. /**
  6234. * This flag can be used for type testing.
  6235. *
  6236. * @type {boolean}
  6237. * @readonly
  6238. * @default true
  6239. */
  6240. Vector4.prototype.isVector4 = true;
  6241. }
  6242. /**
  6243. * Constructs a new 4D vector.
  6244. *
  6245. * @param {number} [x=0] - The x value of this vector.
  6246. * @param {number} [y=0] - The y value of this vector.
  6247. * @param {number} [z=0] - The z value of this vector.
  6248. * @param {number} [w=1] - The w value of this vector.
  6249. */
  6250. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6251. /**
  6252. * The x value of this vector.
  6253. *
  6254. * @type {number}
  6255. */
  6256. this.x = x;
  6257. /**
  6258. * The y value of this vector.
  6259. *
  6260. * @type {number}
  6261. */
  6262. this.y = y;
  6263. /**
  6264. * The z value of this vector.
  6265. *
  6266. * @type {number}
  6267. */
  6268. this.z = z;
  6269. /**
  6270. * The w value of this vector.
  6271. *
  6272. * @type {number}
  6273. */
  6274. this.w = w;
  6275. }
  6276. /**
  6277. * Alias for {@link Vector4#z}.
  6278. *
  6279. * @type {number}
  6280. */
  6281. get width() {
  6282. return this.z;
  6283. }
  6284. set width( value ) {
  6285. this.z = value;
  6286. }
  6287. /**
  6288. * Alias for {@link Vector4#w}.
  6289. *
  6290. * @type {number}
  6291. */
  6292. get height() {
  6293. return this.w;
  6294. }
  6295. set height( value ) {
  6296. this.w = value;
  6297. }
  6298. /**
  6299. * Sets the vector components.
  6300. *
  6301. * @param {number} x - The value of the x component.
  6302. * @param {number} y - The value of the y component.
  6303. * @param {number} z - The value of the z component.
  6304. * @param {number} w - The value of the w component.
  6305. * @return {Vector4} A reference to this vector.
  6306. */
  6307. set( x, y, z, w ) {
  6308. this.x = x;
  6309. this.y = y;
  6310. this.z = z;
  6311. this.w = w;
  6312. return this;
  6313. }
  6314. /**
  6315. * Sets the vector components to the same value.
  6316. *
  6317. * @param {number} scalar - The value to set for all vector components.
  6318. * @return {Vector4} A reference to this vector.
  6319. */
  6320. setScalar( scalar ) {
  6321. this.x = scalar;
  6322. this.y = scalar;
  6323. this.z = scalar;
  6324. this.w = scalar;
  6325. return this;
  6326. }
  6327. /**
  6328. * Sets the vector's x component to the given value
  6329. *
  6330. * @param {number} x - The value to set.
  6331. * @return {Vector4} A reference to this vector.
  6332. */
  6333. setX( x ) {
  6334. this.x = x;
  6335. return this;
  6336. }
  6337. /**
  6338. * Sets the vector's y component to the given value
  6339. *
  6340. * @param {number} y - The value to set.
  6341. * @return {Vector4} A reference to this vector.
  6342. */
  6343. setY( y ) {
  6344. this.y = y;
  6345. return this;
  6346. }
  6347. /**
  6348. * Sets the vector's z component to the given value
  6349. *
  6350. * @param {number} z - The value to set.
  6351. * @return {Vector4} A reference to this vector.
  6352. */
  6353. setZ( z ) {
  6354. this.z = z;
  6355. return this;
  6356. }
  6357. /**
  6358. * Sets the vector's w component to the given value
  6359. *
  6360. * @param {number} w - The value to set.
  6361. * @return {Vector4} A reference to this vector.
  6362. */
  6363. setW( w ) {
  6364. this.w = w;
  6365. return this;
  6366. }
  6367. /**
  6368. * Allows to set a vector component with an index.
  6369. *
  6370. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6371. * `2` equals to z, `3` equals to w.
  6372. * @param {number} value - The value to set.
  6373. * @return {Vector4} A reference to this vector.
  6374. */
  6375. setComponent( index, value ) {
  6376. switch ( index ) {
  6377. case 0: this.x = value; break;
  6378. case 1: this.y = value; break;
  6379. case 2: this.z = value; break;
  6380. case 3: this.w = value; break;
  6381. default: throw new Error( 'index is out of range: ' + index );
  6382. }
  6383. return this;
  6384. }
  6385. /**
  6386. * Returns the value of the vector component which matches the given index.
  6387. *
  6388. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6389. * `2` equals to z, `3` equals to w.
  6390. * @return {number} A vector component value.
  6391. */
  6392. getComponent( index ) {
  6393. switch ( index ) {
  6394. case 0: return this.x;
  6395. case 1: return this.y;
  6396. case 2: return this.z;
  6397. case 3: return this.w;
  6398. default: throw new Error( 'index is out of range: ' + index );
  6399. }
  6400. }
  6401. /**
  6402. * Returns a new vector with copied values from this instance.
  6403. *
  6404. * @return {Vector4} A clone of this instance.
  6405. */
  6406. clone() {
  6407. return new this.constructor( this.x, this.y, this.z, this.w );
  6408. }
  6409. /**
  6410. * Copies the values of the given vector to this instance.
  6411. *
  6412. * @param {Vector3|Vector4} v - The vector to copy.
  6413. * @return {Vector4} A reference to this vector.
  6414. */
  6415. copy( v ) {
  6416. this.x = v.x;
  6417. this.y = v.y;
  6418. this.z = v.z;
  6419. this.w = ( v.w !== undefined ) ? v.w : 1;
  6420. return this;
  6421. }
  6422. /**
  6423. * Adds the given vector to this instance.
  6424. *
  6425. * @param {Vector4} v - The vector to add.
  6426. * @return {Vector4} A reference to this vector.
  6427. */
  6428. add( v ) {
  6429. this.x += v.x;
  6430. this.y += v.y;
  6431. this.z += v.z;
  6432. this.w += v.w;
  6433. return this;
  6434. }
  6435. /**
  6436. * Adds the given scalar value to all components of this instance.
  6437. *
  6438. * @param {number} s - The scalar to add.
  6439. * @return {Vector4} A reference to this vector.
  6440. */
  6441. addScalar( s ) {
  6442. this.x += s;
  6443. this.y += s;
  6444. this.z += s;
  6445. this.w += s;
  6446. return this;
  6447. }
  6448. /**
  6449. * Adds the given vectors and stores the result in this instance.
  6450. *
  6451. * @param {Vector4} a - The first vector.
  6452. * @param {Vector4} b - The second vector.
  6453. * @return {Vector4} A reference to this vector.
  6454. */
  6455. addVectors( a, b ) {
  6456. this.x = a.x + b.x;
  6457. this.y = a.y + b.y;
  6458. this.z = a.z + b.z;
  6459. this.w = a.w + b.w;
  6460. return this;
  6461. }
  6462. /**
  6463. * Adds the given vector scaled by the given factor to this instance.
  6464. *
  6465. * @param {Vector4} v - The vector.
  6466. * @param {number} s - The factor that scales `v`.
  6467. * @return {Vector4} A reference to this vector.
  6468. */
  6469. addScaledVector( v, s ) {
  6470. this.x += v.x * s;
  6471. this.y += v.y * s;
  6472. this.z += v.z * s;
  6473. this.w += v.w * s;
  6474. return this;
  6475. }
  6476. /**
  6477. * Subtracts the given vector from this instance.
  6478. *
  6479. * @param {Vector4} v - The vector to subtract.
  6480. * @return {Vector4} A reference to this vector.
  6481. */
  6482. sub( v ) {
  6483. this.x -= v.x;
  6484. this.y -= v.y;
  6485. this.z -= v.z;
  6486. this.w -= v.w;
  6487. return this;
  6488. }
  6489. /**
  6490. * Subtracts the given scalar value from all components of this instance.
  6491. *
  6492. * @param {number} s - The scalar to subtract.
  6493. * @return {Vector4} A reference to this vector.
  6494. */
  6495. subScalar( s ) {
  6496. this.x -= s;
  6497. this.y -= s;
  6498. this.z -= s;
  6499. this.w -= s;
  6500. return this;
  6501. }
  6502. /**
  6503. * Subtracts the given vectors and stores the result in this instance.
  6504. *
  6505. * @param {Vector4} a - The first vector.
  6506. * @param {Vector4} b - The second vector.
  6507. * @return {Vector4} A reference to this vector.
  6508. */
  6509. subVectors( a, b ) {
  6510. this.x = a.x - b.x;
  6511. this.y = a.y - b.y;
  6512. this.z = a.z - b.z;
  6513. this.w = a.w - b.w;
  6514. return this;
  6515. }
  6516. /**
  6517. * Multiplies the given vector with this instance.
  6518. *
  6519. * @param {Vector4} v - The vector to multiply.
  6520. * @return {Vector4} A reference to this vector.
  6521. */
  6522. multiply( v ) {
  6523. this.x *= v.x;
  6524. this.y *= v.y;
  6525. this.z *= v.z;
  6526. this.w *= v.w;
  6527. return this;
  6528. }
  6529. /**
  6530. * Multiplies the given scalar value with all components of this instance.
  6531. *
  6532. * @param {number} scalar - The scalar to multiply.
  6533. * @return {Vector4} A reference to this vector.
  6534. */
  6535. multiplyScalar( scalar ) {
  6536. this.x *= scalar;
  6537. this.y *= scalar;
  6538. this.z *= scalar;
  6539. this.w *= scalar;
  6540. return this;
  6541. }
  6542. /**
  6543. * Multiplies this vector with the given 4x4 matrix.
  6544. *
  6545. * @param {Matrix4} m - The 4x4 matrix.
  6546. * @return {Vector4} A reference to this vector.
  6547. */
  6548. applyMatrix4( m ) {
  6549. const x = this.x, y = this.y, z = this.z, w = this.w;
  6550. const e = m.elements;
  6551. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6552. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6553. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6554. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6555. return this;
  6556. }
  6557. /**
  6558. * Divides this instance by the given vector.
  6559. *
  6560. * @param {Vector4} v - The vector to divide.
  6561. * @return {Vector4} A reference to this vector.
  6562. */
  6563. divide( v ) {
  6564. this.x /= v.x;
  6565. this.y /= v.y;
  6566. this.z /= v.z;
  6567. this.w /= v.w;
  6568. return this;
  6569. }
  6570. /**
  6571. * Divides this vector by the given scalar.
  6572. *
  6573. * @param {number} scalar - The scalar to divide.
  6574. * @return {Vector4} A reference to this vector.
  6575. */
  6576. divideScalar( scalar ) {
  6577. return this.multiplyScalar( 1 / scalar );
  6578. }
  6579. /**
  6580. * Sets the x, y and z components of this
  6581. * vector to the quaternion's axis and w to the angle.
  6582. *
  6583. * @param {Quaternion} q - The Quaternion to set.
  6584. * @return {Vector4} A reference to this vector.
  6585. */
  6586. setAxisAngleFromQuaternion( q ) {
  6587. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6588. // q is assumed to be normalized
  6589. this.w = 2 * Math.acos( q.w );
  6590. const s = Math.sqrt( 1 - q.w * q.w );
  6591. if ( s < 0.0001 ) {
  6592. this.x = 1;
  6593. this.y = 0;
  6594. this.z = 0;
  6595. } else {
  6596. this.x = q.x / s;
  6597. this.y = q.y / s;
  6598. this.z = q.z / s;
  6599. }
  6600. return this;
  6601. }
  6602. /**
  6603. * Sets the x, y and z components of this
  6604. * vector to the axis of rotation and w to the angle.
  6605. *
  6606. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6607. * @return {Vector4} A reference to this vector.
  6608. */
  6609. setAxisAngleFromRotationMatrix( m ) {
  6610. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6611. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6612. let angle, x, y, z; // variables for result
  6613. const epsilon = 0.01, // margin to allow for rounding errors
  6614. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6615. te = m.elements,
  6616. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6617. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6618. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6619. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6620. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6621. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6622. // singularity found
  6623. // first check for identity matrix which must have +1 for all terms
  6624. // in leading diagonal and zero in other terms
  6625. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6626. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6627. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6628. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6629. // this singularity is identity matrix so angle = 0
  6630. this.set( 1, 0, 0, 0 );
  6631. return this; // zero angle, arbitrary axis
  6632. }
  6633. // otherwise this singularity is angle = 180
  6634. angle = Math.PI;
  6635. const xx = ( m11 + 1 ) / 2;
  6636. const yy = ( m22 + 1 ) / 2;
  6637. const zz = ( m33 + 1 ) / 2;
  6638. const xy = ( m12 + m21 ) / 4;
  6639. const xz = ( m13 + m31 ) / 4;
  6640. const yz = ( m23 + m32 ) / 4;
  6641. if ( ( xx > yy ) && ( xx > zz ) ) {
  6642. // m11 is the largest diagonal term
  6643. if ( xx < epsilon ) {
  6644. x = 0;
  6645. y = 0.707106781;
  6646. z = 0.707106781;
  6647. } else {
  6648. x = Math.sqrt( xx );
  6649. y = xy / x;
  6650. z = xz / x;
  6651. }
  6652. } else if ( yy > zz ) {
  6653. // m22 is the largest diagonal term
  6654. if ( yy < epsilon ) {
  6655. x = 0.707106781;
  6656. y = 0;
  6657. z = 0.707106781;
  6658. } else {
  6659. y = Math.sqrt( yy );
  6660. x = xy / y;
  6661. z = yz / y;
  6662. }
  6663. } else {
  6664. // m33 is the largest diagonal term so base result on this
  6665. if ( zz < epsilon ) {
  6666. x = 0.707106781;
  6667. y = 0.707106781;
  6668. z = 0;
  6669. } else {
  6670. z = Math.sqrt( zz );
  6671. x = xz / z;
  6672. y = yz / z;
  6673. }
  6674. }
  6675. this.set( x, y, z, angle );
  6676. return this; // return 180 deg rotation
  6677. }
  6678. // as we have reached here there are no singularities so we can handle normally
  6679. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6680. ( m13 - m31 ) * ( m13 - m31 ) +
  6681. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6682. if ( Math.abs( s ) < 0.001 ) s = 1;
  6683. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6684. // caught by singularity test above, but I've left it in just in case
  6685. this.x = ( m32 - m23 ) / s;
  6686. this.y = ( m13 - m31 ) / s;
  6687. this.z = ( m21 - m12 ) / s;
  6688. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6689. return this;
  6690. }
  6691. /**
  6692. * Sets the vector components to the position elements of the
  6693. * given transformation matrix.
  6694. *
  6695. * @param {Matrix4} m - The 4x4 matrix.
  6696. * @return {Vector4} A reference to this vector.
  6697. */
  6698. setFromMatrixPosition( m ) {
  6699. const e = m.elements;
  6700. this.x = e[ 12 ];
  6701. this.y = e[ 13 ];
  6702. this.z = e[ 14 ];
  6703. this.w = e[ 15 ];
  6704. return this;
  6705. }
  6706. /**
  6707. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6708. * value, replace that value with the corresponding min value.
  6709. *
  6710. * @param {Vector4} v - The vector.
  6711. * @return {Vector4} A reference to this vector.
  6712. */
  6713. min( v ) {
  6714. this.x = Math.min( this.x, v.x );
  6715. this.y = Math.min( this.y, v.y );
  6716. this.z = Math.min( this.z, v.z );
  6717. this.w = Math.min( this.w, v.w );
  6718. return this;
  6719. }
  6720. /**
  6721. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6722. * value, replace that value with the corresponding max value.
  6723. *
  6724. * @param {Vector4} v - The vector.
  6725. * @return {Vector4} A reference to this vector.
  6726. */
  6727. max( v ) {
  6728. this.x = Math.max( this.x, v.x );
  6729. this.y = Math.max( this.y, v.y );
  6730. this.z = Math.max( this.z, v.z );
  6731. this.w = Math.max( this.w, v.w );
  6732. return this;
  6733. }
  6734. /**
  6735. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6736. * value, it is replaced by the corresponding value.
  6737. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6738. * it is replaced by the corresponding value.
  6739. *
  6740. * @param {Vector4} min - The minimum x, y and z values.
  6741. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6742. * @return {Vector4} A reference to this vector.
  6743. */
  6744. clamp( min, max ) {
  6745. // assumes min < max, componentwise
  6746. this.x = clamp( this.x, min.x, max.x );
  6747. this.y = clamp( this.y, min.y, max.y );
  6748. this.z = clamp( this.z, min.z, max.z );
  6749. this.w = clamp( this.w, min.w, max.w );
  6750. return this;
  6751. }
  6752. /**
  6753. * If this vector's x, y, z or w values are greater than the max value, they are
  6754. * replaced by the max value.
  6755. * If this vector's x, y, z or w values are less than the min value, they are
  6756. * replaced by the min value.
  6757. *
  6758. * @param {number} minVal - The minimum value the components will be clamped to.
  6759. * @param {number} maxVal - The maximum value the components will be clamped to.
  6760. * @return {Vector4} A reference to this vector.
  6761. */
  6762. clampScalar( minVal, maxVal ) {
  6763. this.x = clamp( this.x, minVal, maxVal );
  6764. this.y = clamp( this.y, minVal, maxVal );
  6765. this.z = clamp( this.z, minVal, maxVal );
  6766. this.w = clamp( this.w, minVal, maxVal );
  6767. return this;
  6768. }
  6769. /**
  6770. * If this vector's length is greater than the max value, it is replaced by
  6771. * the max value.
  6772. * If this vector's length is less than the min value, it is replaced by the
  6773. * min value.
  6774. *
  6775. * @param {number} min - The minimum value the vector length will be clamped to.
  6776. * @param {number} max - The maximum value the vector length will be clamped to.
  6777. * @return {Vector4} A reference to this vector.
  6778. */
  6779. clampLength( min, max ) {
  6780. const length = this.length();
  6781. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6782. }
  6783. /**
  6784. * The components of this vector are rounded down to the nearest integer value.
  6785. *
  6786. * @return {Vector4} A reference to this vector.
  6787. */
  6788. floor() {
  6789. this.x = Math.floor( this.x );
  6790. this.y = Math.floor( this.y );
  6791. this.z = Math.floor( this.z );
  6792. this.w = Math.floor( this.w );
  6793. return this;
  6794. }
  6795. /**
  6796. * The components of this vector are rounded up to the nearest integer value.
  6797. *
  6798. * @return {Vector4} A reference to this vector.
  6799. */
  6800. ceil() {
  6801. this.x = Math.ceil( this.x );
  6802. this.y = Math.ceil( this.y );
  6803. this.z = Math.ceil( this.z );
  6804. this.w = Math.ceil( this.w );
  6805. return this;
  6806. }
  6807. /**
  6808. * The components of this vector are rounded to the nearest integer value
  6809. *
  6810. * @return {Vector4} A reference to this vector.
  6811. */
  6812. round() {
  6813. this.x = Math.round( this.x );
  6814. this.y = Math.round( this.y );
  6815. this.z = Math.round( this.z );
  6816. this.w = Math.round( this.w );
  6817. return this;
  6818. }
  6819. /**
  6820. * The components of this vector are rounded towards zero (up if negative,
  6821. * down if positive) to an integer value.
  6822. *
  6823. * @return {Vector4} A reference to this vector.
  6824. */
  6825. roundToZero() {
  6826. this.x = Math.trunc( this.x );
  6827. this.y = Math.trunc( this.y );
  6828. this.z = Math.trunc( this.z );
  6829. this.w = Math.trunc( this.w );
  6830. return this;
  6831. }
  6832. /**
  6833. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6834. *
  6835. * @return {Vector4} A reference to this vector.
  6836. */
  6837. negate() {
  6838. this.x = - this.x;
  6839. this.y = - this.y;
  6840. this.z = - this.z;
  6841. this.w = - this.w;
  6842. return this;
  6843. }
  6844. /**
  6845. * Calculates the dot product of the given vector with this instance.
  6846. *
  6847. * @param {Vector4} v - The vector to compute the dot product with.
  6848. * @return {number} The result of the dot product.
  6849. */
  6850. dot( v ) {
  6851. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6852. }
  6853. /**
  6854. * Computes the square of the Euclidean length (straight-line length) from
  6855. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6856. * compare the length squared instead as it is slightly more efficient to calculate.
  6857. *
  6858. * @return {number} The square length of this vector.
  6859. */
  6860. lengthSq() {
  6861. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6862. }
  6863. /**
  6864. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6865. *
  6866. * @return {number} The length of this vector.
  6867. */
  6868. length() {
  6869. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6870. }
  6871. /**
  6872. * Computes the Manhattan length of this vector.
  6873. *
  6874. * @return {number} The length of this vector.
  6875. */
  6876. manhattanLength() {
  6877. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6878. }
  6879. /**
  6880. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6881. * with the same direction as this one, but with a vector length of `1`.
  6882. *
  6883. * @return {Vector4} A reference to this vector.
  6884. */
  6885. normalize() {
  6886. return this.divideScalar( this.length() || 1 );
  6887. }
  6888. /**
  6889. * Sets this vector to a vector with the same direction as this one, but
  6890. * with the specified length.
  6891. *
  6892. * @param {number} length - The new length of this vector.
  6893. * @return {Vector4} A reference to this vector.
  6894. */
  6895. setLength( length ) {
  6896. return this.normalize().multiplyScalar( length );
  6897. }
  6898. /**
  6899. * Linearly interpolates between the given vector and this instance, where
  6900. * alpha is the percent distance along the line - alpha = 0 will be this
  6901. * vector, and alpha = 1 will be the given one.
  6902. *
  6903. * @param {Vector4} v - The vector to interpolate towards.
  6904. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6905. * @return {Vector4} A reference to this vector.
  6906. */
  6907. lerp( v, alpha ) {
  6908. this.x += ( v.x - this.x ) * alpha;
  6909. this.y += ( v.y - this.y ) * alpha;
  6910. this.z += ( v.z - this.z ) * alpha;
  6911. this.w += ( v.w - this.w ) * alpha;
  6912. return this;
  6913. }
  6914. /**
  6915. * Linearly interpolates between the given vectors, where alpha is the percent
  6916. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6917. * be the second one. The result is stored in this instance.
  6918. *
  6919. * @param {Vector4} v1 - The first vector.
  6920. * @param {Vector4} v2 - The second vector.
  6921. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6922. * @return {Vector4} A reference to this vector.
  6923. */
  6924. lerpVectors( v1, v2, alpha ) {
  6925. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6926. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6927. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6928. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6929. return this;
  6930. }
  6931. /**
  6932. * Returns `true` if this vector is equal with the given one.
  6933. *
  6934. * @param {Vector4} v - The vector to test for equality.
  6935. * @return {boolean} Whether this vector is equal with the given one.
  6936. */
  6937. equals( v ) {
  6938. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6939. }
  6940. /**
  6941. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6942. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6943. *
  6944. * @param {Array<number>} array - An array holding the vector component values.
  6945. * @param {number} [offset=0] - The offset into the array.
  6946. * @return {Vector4} A reference to this vector.
  6947. */
  6948. fromArray( array, offset = 0 ) {
  6949. this.x = array[ offset ];
  6950. this.y = array[ offset + 1 ];
  6951. this.z = array[ offset + 2 ];
  6952. this.w = array[ offset + 3 ];
  6953. return this;
  6954. }
  6955. /**
  6956. * Writes the components of this vector to the given array. If no array is provided,
  6957. * the method returns a new instance.
  6958. *
  6959. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6960. * @param {number} [offset=0] - Index of the first element in the array.
  6961. * @return {Array<number>} The vector components.
  6962. */
  6963. toArray( array = [], offset = 0 ) {
  6964. array[ offset ] = this.x;
  6965. array[ offset + 1 ] = this.y;
  6966. array[ offset + 2 ] = this.z;
  6967. array[ offset + 3 ] = this.w;
  6968. return array;
  6969. }
  6970. /**
  6971. * Sets the components of this vector from the given buffer attribute.
  6972. *
  6973. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6974. * @param {number} index - The index into the attribute.
  6975. * @return {Vector4} A reference to this vector.
  6976. */
  6977. fromBufferAttribute( attribute, index ) {
  6978. this.x = attribute.getX( index );
  6979. this.y = attribute.getY( index );
  6980. this.z = attribute.getZ( index );
  6981. this.w = attribute.getW( index );
  6982. return this;
  6983. }
  6984. /**
  6985. * Sets each component of this vector to a pseudo-random value between `0` and
  6986. * `1`, excluding `1`.
  6987. *
  6988. * @return {Vector4} A reference to this vector.
  6989. */
  6990. random() {
  6991. this.x = Math.random();
  6992. this.y = Math.random();
  6993. this.z = Math.random();
  6994. this.w = Math.random();
  6995. return this;
  6996. }
  6997. *[ Symbol.iterator ]() {
  6998. yield this.x;
  6999. yield this.y;
  7000. yield this.z;
  7001. yield this.w;
  7002. }
  7003. }
  7004. /**
  7005. * A render target is a buffer where the video card draws pixels for a scene
  7006. * that is being rendered in the background. It is used in different effects,
  7007. * such as applying postprocessing to a rendered image before displaying it
  7008. * on the screen.
  7009. *
  7010. * @augments EventDispatcher
  7011. */
  7012. class RenderTarget extends EventDispatcher {
  7013. /**
  7014. * Render target options.
  7015. *
  7016. * @typedef {Object} RenderTarget~Options
  7017. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  7018. * @property {number} [magFilter=LinearFilter] - The mag filter.
  7019. * @property {number} [minFilter=LinearFilter] - The min filter.
  7020. * @property {number} [format=RGBAFormat] - The texture format.
  7021. * @property {number} [type=UnsignedByteType] - The texture type.
  7022. * @property {?string} [internalFormat=null] - The texture's internal format.
  7023. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  7024. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  7025. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  7026. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  7027. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  7028. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  7029. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  7030. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  7031. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  7032. * @property {number} [samples=0] - The MSAA samples count.
  7033. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  7034. * @property {number} [depth=1] - The texture depth.
  7035. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  7036. */
  7037. /**
  7038. * Constructs a new render target.
  7039. *
  7040. * @param {number} [width=1] - The width of the render target.
  7041. * @param {number} [height=1] - The height of the render target.
  7042. * @param {RenderTarget~Options} [options] - The configuration object.
  7043. */
  7044. constructor( width = 1, height = 1, options = {} ) {
  7045. super();
  7046. options = Object.assign( {
  7047. generateMipmaps: false,
  7048. internalFormat: null,
  7049. minFilter: LinearFilter,
  7050. depthBuffer: true,
  7051. stencilBuffer: false,
  7052. resolveDepthBuffer: true,
  7053. resolveStencilBuffer: true,
  7054. depthTexture: null,
  7055. samples: 0,
  7056. count: 1,
  7057. depth: 1,
  7058. multiview: false
  7059. }, options );
  7060. /**
  7061. * This flag can be used for type testing.
  7062. *
  7063. * @type {boolean}
  7064. * @readonly
  7065. * @default true
  7066. */
  7067. this.isRenderTarget = true;
  7068. /**
  7069. * The width of the render target.
  7070. *
  7071. * @type {number}
  7072. * @default 1
  7073. */
  7074. this.width = width;
  7075. /**
  7076. * The height of the render target.
  7077. *
  7078. * @type {number}
  7079. * @default 1
  7080. */
  7081. this.height = height;
  7082. /**
  7083. * The depth of the render target.
  7084. *
  7085. * @type {number}
  7086. * @default 1
  7087. */
  7088. this.depth = options.depth;
  7089. /**
  7090. * A rectangular area inside the render target's viewport. Fragments that are
  7091. * outside the area will be discarded.
  7092. *
  7093. * @type {Vector4}
  7094. * @default (0,0,width,height)
  7095. */
  7096. this.scissor = new Vector4( 0, 0, width, height );
  7097. /**
  7098. * Indicates whether the scissor test should be enabled when rendering into
  7099. * this render target or not.
  7100. *
  7101. * @type {boolean}
  7102. * @default false
  7103. */
  7104. this.scissorTest = false;
  7105. /**
  7106. * A rectangular area representing the render target's viewport.
  7107. *
  7108. * @type {Vector4}
  7109. * @default (0,0,width,height)
  7110. */
  7111. this.viewport = new Vector4( 0, 0, width, height );
  7112. /**
  7113. * An array of textures. Each color attachment is represented as a separate texture.
  7114. * Has at least a single entry for the default color attachment.
  7115. *
  7116. * @type {Array<Texture>}
  7117. */
  7118. this.textures = [];
  7119. const image = { width: width, height: height, depth: options.depth };
  7120. const texture = new Texture( image );
  7121. const count = options.count;
  7122. for ( let i = 0; i < count; i ++ ) {
  7123. this.textures[ i ] = texture.clone();
  7124. this.textures[ i ].isRenderTargetTexture = true;
  7125. this.textures[ i ].renderTarget = this;
  7126. }
  7127. this._setTextureOptions( options );
  7128. /**
  7129. * Whether to allocate a depth buffer or not.
  7130. *
  7131. * @type {boolean}
  7132. * @default true
  7133. */
  7134. this.depthBuffer = options.depthBuffer;
  7135. /**
  7136. * Whether to allocate a stencil buffer or not.
  7137. *
  7138. * @type {boolean}
  7139. * @default false
  7140. */
  7141. this.stencilBuffer = options.stencilBuffer;
  7142. /**
  7143. * Whether to resolve the depth buffer or not.
  7144. *
  7145. * @type {boolean}
  7146. * @default true
  7147. */
  7148. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7149. /**
  7150. * Whether to resolve the stencil buffer or not.
  7151. *
  7152. * @type {boolean}
  7153. * @default true
  7154. */
  7155. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7156. this._depthTexture = null;
  7157. this.depthTexture = options.depthTexture;
  7158. /**
  7159. * The number of MSAA samples.
  7160. *
  7161. * A value of `0` disables MSAA.
  7162. *
  7163. * @type {number}
  7164. * @default 0
  7165. */
  7166. this.samples = options.samples;
  7167. /**
  7168. * Whether to this target is used in multiview rendering.
  7169. *
  7170. * @type {boolean}
  7171. * @default false
  7172. */
  7173. this.multiview = options.multiview;
  7174. }
  7175. _setTextureOptions( options = {} ) {
  7176. const values = {
  7177. minFilter: LinearFilter,
  7178. generateMipmaps: false,
  7179. flipY: false,
  7180. internalFormat: null
  7181. };
  7182. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7183. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7184. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7185. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7186. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7187. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7188. if ( options.format !== undefined ) values.format = options.format;
  7189. if ( options.type !== undefined ) values.type = options.type;
  7190. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7191. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7192. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7193. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7194. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7195. for ( let i = 0; i < this.textures.length; i ++ ) {
  7196. const texture = this.textures[ i ];
  7197. texture.setValues( values );
  7198. }
  7199. }
  7200. /**
  7201. * The texture representing the default color attachment.
  7202. *
  7203. * @type {Texture}
  7204. */
  7205. get texture() {
  7206. return this.textures[ 0 ];
  7207. }
  7208. set texture( value ) {
  7209. this.textures[ 0 ] = value;
  7210. }
  7211. set depthTexture( current ) {
  7212. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7213. if ( current !== null ) current.renderTarget = this;
  7214. this._depthTexture = current;
  7215. }
  7216. /**
  7217. * Instead of saving the depth in a renderbuffer, a texture
  7218. * can be used instead which is useful for further processing
  7219. * e.g. in context of post-processing.
  7220. *
  7221. * @type {?DepthTexture}
  7222. * @default null
  7223. */
  7224. get depthTexture() {
  7225. return this._depthTexture;
  7226. }
  7227. /**
  7228. * Sets the size of this render target.
  7229. *
  7230. * @param {number} width - The width.
  7231. * @param {number} height - The height.
  7232. * @param {number} [depth=1] - The depth.
  7233. */
  7234. setSize( width, height, depth = 1 ) {
  7235. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7236. this.width = width;
  7237. this.height = height;
  7238. this.depth = depth;
  7239. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7240. this.textures[ i ].image.width = width;
  7241. this.textures[ i ].image.height = height;
  7242. this.textures[ i ].image.depth = depth;
  7243. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7244. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7245. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7246. // both are evaluated on each call?
  7247. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7248. }
  7249. }
  7250. this.dispose();
  7251. }
  7252. this.viewport.set( 0, 0, width, height );
  7253. this.scissor.set( 0, 0, width, height );
  7254. }
  7255. /**
  7256. * Returns a new render target with copied values from this instance.
  7257. *
  7258. * @return {RenderTarget} A clone of this instance.
  7259. */
  7260. clone() {
  7261. return new this.constructor().copy( this );
  7262. }
  7263. /**
  7264. * Copies the settings of the given render target. This is a structural copy so
  7265. * no resources are shared between render targets after the copy. That includes
  7266. * all MRT textures and the depth texture.
  7267. *
  7268. * @param {RenderTarget} source - The render target to copy.
  7269. * @return {RenderTarget} A reference to this instance.
  7270. */
  7271. copy( source ) {
  7272. this.width = source.width;
  7273. this.height = source.height;
  7274. this.depth = source.depth;
  7275. this.scissor.copy( source.scissor );
  7276. this.scissorTest = source.scissorTest;
  7277. this.viewport.copy( source.viewport );
  7278. this.textures.length = 0;
  7279. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7280. this.textures[ i ] = source.textures[ i ].clone();
  7281. this.textures[ i ].isRenderTargetTexture = true;
  7282. this.textures[ i ].renderTarget = this;
  7283. // ensure image object is not shared, see #20328
  7284. const image = Object.assign( {}, source.textures[ i ].image );
  7285. this.textures[ i ].source = new Source( image );
  7286. }
  7287. this.depthBuffer = source.depthBuffer;
  7288. this.stencilBuffer = source.stencilBuffer;
  7289. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7290. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7291. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7292. this.samples = source.samples;
  7293. this.multiview = source.multiview;
  7294. return this;
  7295. }
  7296. /**
  7297. * Frees the GPU-related resources allocated by this instance. Call this
  7298. * method whenever this instance is no longer used in your app.
  7299. *
  7300. * @fires RenderTarget#dispose
  7301. */
  7302. dispose() {
  7303. this.dispatchEvent( { type: 'dispose' } );
  7304. }
  7305. }
  7306. /**
  7307. * A render target used in context of {@link WebGLRenderer}.
  7308. *
  7309. * @augments RenderTarget
  7310. */
  7311. class WebGLRenderTarget extends RenderTarget {
  7312. /**
  7313. * Constructs a new 3D render target.
  7314. *
  7315. * @param {number} [width=1] - The width of the render target.
  7316. * @param {number} [height=1] - The height of the render target.
  7317. * @param {RenderTarget~Options} [options] - The configuration object.
  7318. */
  7319. constructor( width = 1, height = 1, options = {} ) {
  7320. super( width, height, options );
  7321. /**
  7322. * This flag can be used for type testing.
  7323. *
  7324. * @type {boolean}
  7325. * @readonly
  7326. * @default true
  7327. */
  7328. this.isWebGLRenderTarget = true;
  7329. }
  7330. }
  7331. /**
  7332. * Creates an array of textures directly from raw buffer data.
  7333. *
  7334. * @augments Texture
  7335. */
  7336. class DataArrayTexture extends Texture {
  7337. /**
  7338. * Constructs a new data array texture.
  7339. *
  7340. * @param {?TypedArray} [data=null] - The buffer data.
  7341. * @param {number} [width=1] - The width of the texture.
  7342. * @param {number} [height=1] - The height of the texture.
  7343. * @param {number} [depth=1] - The depth of the texture.
  7344. */
  7345. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7346. super( null );
  7347. /**
  7348. * This flag can be used for type testing.
  7349. *
  7350. * @type {boolean}
  7351. * @readonly
  7352. * @default true
  7353. */
  7354. this.isDataArrayTexture = true;
  7355. /**
  7356. * The image definition of a data texture.
  7357. *
  7358. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7359. */
  7360. this.image = { data, width, height, depth };
  7361. /**
  7362. * How the texture is sampled when a texel covers more than one pixel.
  7363. *
  7364. * Overwritten and set to `NearestFilter` by default.
  7365. *
  7366. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7367. * @default NearestFilter
  7368. */
  7369. this.magFilter = NearestFilter;
  7370. /**
  7371. * How the texture is sampled when a texel covers less than one pixel.
  7372. *
  7373. * Overwritten and set to `NearestFilter` by default.
  7374. *
  7375. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7376. * @default NearestFilter
  7377. */
  7378. this.minFilter = NearestFilter;
  7379. /**
  7380. * This defines how the texture is wrapped in the depth and corresponds to
  7381. * *W* in UVW mapping.
  7382. *
  7383. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7384. * @default ClampToEdgeWrapping
  7385. */
  7386. this.wrapR = ClampToEdgeWrapping;
  7387. /**
  7388. * Whether to generate mipmaps (if possible) for a texture.
  7389. *
  7390. * Overwritten and set to `false` by default.
  7391. *
  7392. * @type {boolean}
  7393. * @default false
  7394. */
  7395. this.generateMipmaps = false;
  7396. /**
  7397. * If set to `true`, the texture is flipped along the vertical axis when
  7398. * uploaded to the GPU.
  7399. *
  7400. * Overwritten and set to `false` by default.
  7401. *
  7402. * @type {boolean}
  7403. * @default false
  7404. */
  7405. this.flipY = false;
  7406. /**
  7407. * Specifies the alignment requirements for the start of each pixel row in memory.
  7408. *
  7409. * Overwritten and set to `1` by default.
  7410. *
  7411. * @type {boolean}
  7412. * @default 1
  7413. */
  7414. this.unpackAlignment = 1;
  7415. /**
  7416. * A set of all layers which need to be updated in the texture.
  7417. *
  7418. * @type {Set<number>}
  7419. */
  7420. this.layerUpdates = new Set();
  7421. }
  7422. /**
  7423. * Describes that a specific layer of the texture needs to be updated.
  7424. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7425. * entire data texture array is sent to the GPU. Marking specific
  7426. * layers will only transmit subsets of all mipmaps associated with a
  7427. * specific depth in the array which is often much more performant.
  7428. *
  7429. * @param {number} layerIndex - The layer index that should be updated.
  7430. */
  7431. addLayerUpdate( layerIndex ) {
  7432. this.layerUpdates.add( layerIndex );
  7433. }
  7434. /**
  7435. * Resets the layer updates registry.
  7436. */
  7437. clearLayerUpdates() {
  7438. this.layerUpdates.clear();
  7439. }
  7440. }
  7441. /**
  7442. * An array render target used in context of {@link WebGLRenderer}.
  7443. *
  7444. * @augments WebGLRenderTarget
  7445. */
  7446. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7447. /**
  7448. * Constructs a new array render target.
  7449. *
  7450. * @param {number} [width=1] - The width of the render target.
  7451. * @param {number} [height=1] - The height of the render target.
  7452. * @param {number} [depth=1] - The height of the render target.
  7453. * @param {RenderTarget~Options} [options] - The configuration object.
  7454. */
  7455. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7456. super( width, height, options );
  7457. /**
  7458. * This flag can be used for type testing.
  7459. *
  7460. * @type {boolean}
  7461. * @readonly
  7462. * @default true
  7463. */
  7464. this.isWebGLArrayRenderTarget = true;
  7465. this.depth = depth;
  7466. /**
  7467. * Overwritten with a different texture type.
  7468. *
  7469. * @type {DataArrayTexture}
  7470. */
  7471. this.texture = new DataArrayTexture( null, width, height, depth );
  7472. this._setTextureOptions( options );
  7473. this.texture.isRenderTargetTexture = true;
  7474. }
  7475. }
  7476. /**
  7477. * Creates a three-dimensional texture from raw data, with parameters to
  7478. * divide it into width, height, and depth.
  7479. *
  7480. * @augments Texture
  7481. */
  7482. class Data3DTexture extends Texture {
  7483. /**
  7484. * Constructs a new data array texture.
  7485. *
  7486. * @param {?TypedArray} [data=null] - The buffer data.
  7487. * @param {number} [width=1] - The width of the texture.
  7488. * @param {number} [height=1] - The height of the texture.
  7489. * @param {number} [depth=1] - The depth of the texture.
  7490. */
  7491. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7492. // We're going to add .setXXX() methods for setting properties later.
  7493. // Users can still set in Data3DTexture directly.
  7494. //
  7495. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7496. // texture.anisotropy = 16;
  7497. //
  7498. // See #14839
  7499. super( null );
  7500. /**
  7501. * This flag can be used for type testing.
  7502. *
  7503. * @type {boolean}
  7504. * @readonly
  7505. * @default true
  7506. */
  7507. this.isData3DTexture = true;
  7508. /**
  7509. * The image definition of a data texture.
  7510. *
  7511. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7512. */
  7513. this.image = { data, width, height, depth };
  7514. /**
  7515. * How the texture is sampled when a texel covers more than one pixel.
  7516. *
  7517. * Overwritten and set to `NearestFilter` by default.
  7518. *
  7519. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7520. * @default NearestFilter
  7521. */
  7522. this.magFilter = NearestFilter;
  7523. /**
  7524. * How the texture is sampled when a texel covers less than one pixel.
  7525. *
  7526. * Overwritten and set to `NearestFilter` by default.
  7527. *
  7528. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7529. * @default NearestFilter
  7530. */
  7531. this.minFilter = NearestFilter;
  7532. /**
  7533. * This defines how the texture is wrapped in the depth and corresponds to
  7534. * *W* in UVW mapping.
  7535. *
  7536. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7537. * @default ClampToEdgeWrapping
  7538. */
  7539. this.wrapR = ClampToEdgeWrapping;
  7540. /**
  7541. * Whether to generate mipmaps (if possible) for a texture.
  7542. *
  7543. * Overwritten and set to `false` by default.
  7544. *
  7545. * @type {boolean}
  7546. * @default false
  7547. */
  7548. this.generateMipmaps = false;
  7549. /**
  7550. * If set to `true`, the texture is flipped along the vertical axis when
  7551. * uploaded to the GPU.
  7552. *
  7553. * Overwritten and set to `false` by default.
  7554. *
  7555. * @type {boolean}
  7556. * @default false
  7557. */
  7558. this.flipY = false;
  7559. /**
  7560. * Specifies the alignment requirements for the start of each pixel row in memory.
  7561. *
  7562. * Overwritten and set to `1` by default.
  7563. *
  7564. * @type {boolean}
  7565. * @default 1
  7566. */
  7567. this.unpackAlignment = 1;
  7568. }
  7569. }
  7570. /**
  7571. * A 3D render target used in context of {@link WebGLRenderer}.
  7572. *
  7573. * @augments WebGLRenderTarget
  7574. */
  7575. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7576. /**
  7577. * Constructs a new 3D render target.
  7578. *
  7579. * @param {number} [width=1] - The width of the render target.
  7580. * @param {number} [height=1] - The height of the render target.
  7581. * @param {number} [depth=1] - The height of the render target.
  7582. * @param {RenderTarget~Options} [options] - The configuration object.
  7583. */
  7584. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7585. super( width, height, options );
  7586. /**
  7587. * This flag can be used for type testing.
  7588. *
  7589. * @type {boolean}
  7590. * @readonly
  7591. * @default true
  7592. */
  7593. this.isWebGL3DRenderTarget = true;
  7594. this.depth = depth;
  7595. /**
  7596. * Overwritten with a different texture type.
  7597. *
  7598. * @type {Data3DTexture}
  7599. */
  7600. this.texture = new Data3DTexture( null, width, height, depth );
  7601. this._setTextureOptions( options );
  7602. this.texture.isRenderTargetTexture = true;
  7603. }
  7604. }
  7605. /**
  7606. * Represents a 4x4 matrix.
  7607. *
  7608. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  7609. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  7610. *
  7611. * This allows a 3D vector representing a point in 3D space to undergo
  7612. * transformations such as translation, rotation, shear, scale, reflection,
  7613. * orthogonal or perspective projection and so on, by being multiplied by the
  7614. * matrix. This is known as `applying` the matrix to the vector.
  7615. *
  7616. * A Note on Row-Major and Column-Major Ordering:
  7617. *
  7618. * The constructor and {@link Matrix3#set} method take arguments in
  7619. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  7620. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  7621. * This means that calling:
  7622. * ```js
  7623. * const m = new THREE.Matrix4();
  7624. * m.set( 11, 12, 13, 14,
  7625. * 21, 22, 23, 24,
  7626. * 31, 32, 33, 34,
  7627. * 41, 42, 43, 44 );
  7628. * ```
  7629. * will result in the elements array containing:
  7630. * ```js
  7631. * m.elements = [ 11, 21, 31, 41,
  7632. * 12, 22, 32, 42,
  7633. * 13, 23, 33, 43,
  7634. * 14, 24, 34, 44 ];
  7635. * ```
  7636. * and internally all calculations are performed using column-major ordering.
  7637. * However, as the actual ordering makes no difference mathematically and
  7638. * most people are used to thinking about matrices in row-major order, the
  7639. * three.js documentation shows matrices in row-major order. Just bear in
  7640. * mind that if you are reading the source code, you'll have to take the
  7641. * transpose of any matrices outlined here to make sense of the calculations.
  7642. */
  7643. class Matrix4 {
  7644. static {
  7645. /**
  7646. * This flag can be used for type testing.
  7647. *
  7648. * @type {boolean}
  7649. * @readonly
  7650. * @default true
  7651. */
  7652. Matrix4.prototype.isMatrix4 = true;
  7653. }
  7654. /**
  7655. * Constructs a new 4x4 matrix. The arguments are supposed to be
  7656. * in row-major order. If no arguments are provided, the constructor
  7657. * initializes the matrix as an identity matrix.
  7658. *
  7659. * @param {number} [n11] - 1-1 matrix element.
  7660. * @param {number} [n12] - 1-2 matrix element.
  7661. * @param {number} [n13] - 1-3 matrix element.
  7662. * @param {number} [n14] - 1-4 matrix element.
  7663. * @param {number} [n21] - 2-1 matrix element.
  7664. * @param {number} [n22] - 2-2 matrix element.
  7665. * @param {number} [n23] - 2-3 matrix element.
  7666. * @param {number} [n24] - 2-4 matrix element.
  7667. * @param {number} [n31] - 3-1 matrix element.
  7668. * @param {number} [n32] - 3-2 matrix element.
  7669. * @param {number} [n33] - 3-3 matrix element.
  7670. * @param {number} [n34] - 3-4 matrix element.
  7671. * @param {number} [n41] - 4-1 matrix element.
  7672. * @param {number} [n42] - 4-2 matrix element.
  7673. * @param {number} [n43] - 4-3 matrix element.
  7674. * @param {number} [n44] - 4-4 matrix element.
  7675. */
  7676. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7677. /**
  7678. * A column-major list of matrix values.
  7679. *
  7680. * @type {Array<number>}
  7681. */
  7682. this.elements = [
  7683. 1, 0, 0, 0,
  7684. 0, 1, 0, 0,
  7685. 0, 0, 1, 0,
  7686. 0, 0, 0, 1
  7687. ];
  7688. if ( n11 !== undefined ) {
  7689. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  7690. }
  7691. }
  7692. /**
  7693. * Sets the elements of the matrix.The arguments are supposed to be
  7694. * in row-major order.
  7695. *
  7696. * @param {number} [n11] - 1-1 matrix element.
  7697. * @param {number} [n12] - 1-2 matrix element.
  7698. * @param {number} [n13] - 1-3 matrix element.
  7699. * @param {number} [n14] - 1-4 matrix element.
  7700. * @param {number} [n21] - 2-1 matrix element.
  7701. * @param {number} [n22] - 2-2 matrix element.
  7702. * @param {number} [n23] - 2-3 matrix element.
  7703. * @param {number} [n24] - 2-4 matrix element.
  7704. * @param {number} [n31] - 3-1 matrix element.
  7705. * @param {number} [n32] - 3-2 matrix element.
  7706. * @param {number} [n33] - 3-3 matrix element.
  7707. * @param {number} [n34] - 3-4 matrix element.
  7708. * @param {number} [n41] - 4-1 matrix element.
  7709. * @param {number} [n42] - 4-2 matrix element.
  7710. * @param {number} [n43] - 4-3 matrix element.
  7711. * @param {number} [n44] - 4-4 matrix element.
  7712. * @return {Matrix4} A reference to this matrix.
  7713. */
  7714. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7715. const te = this.elements;
  7716. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  7717. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  7718. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  7719. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  7720. return this;
  7721. }
  7722. /**
  7723. * Sets this matrix to the 4x4 identity matrix.
  7724. *
  7725. * @return {Matrix4} A reference to this matrix.
  7726. */
  7727. identity() {
  7728. this.set(
  7729. 1, 0, 0, 0,
  7730. 0, 1, 0, 0,
  7731. 0, 0, 1, 0,
  7732. 0, 0, 0, 1
  7733. );
  7734. return this;
  7735. }
  7736. /**
  7737. * Returns a matrix with copied values from this instance.
  7738. *
  7739. * @return {Matrix4} A clone of this instance.
  7740. */
  7741. clone() {
  7742. return new Matrix4().fromArray( this.elements );
  7743. }
  7744. /**
  7745. * Copies the values of the given matrix to this instance.
  7746. *
  7747. * @param {Matrix4} m - The matrix to copy.
  7748. * @return {Matrix4} A reference to this matrix.
  7749. */
  7750. copy( m ) {
  7751. const te = this.elements;
  7752. const me = m.elements;
  7753. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  7754. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  7755. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  7756. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  7757. return this;
  7758. }
  7759. /**
  7760. * Copies the translation component of the given matrix
  7761. * into this matrix's translation component.
  7762. *
  7763. * @param {Matrix4} m - The matrix to copy the translation component.
  7764. * @return {Matrix4} A reference to this matrix.
  7765. */
  7766. copyPosition( m ) {
  7767. const te = this.elements, me = m.elements;
  7768. te[ 12 ] = me[ 12 ];
  7769. te[ 13 ] = me[ 13 ];
  7770. te[ 14 ] = me[ 14 ];
  7771. return this;
  7772. }
  7773. /**
  7774. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  7775. *
  7776. * @param {Matrix3} m - The 3x3 matrix.
  7777. * @return {Matrix4} A reference to this matrix.
  7778. */
  7779. setFromMatrix3( m ) {
  7780. const me = m.elements;
  7781. this.set(
  7782. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  7783. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  7784. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  7785. 0, 0, 0, 1
  7786. );
  7787. return this;
  7788. }
  7789. /**
  7790. * Extracts the basis of this matrix into the three axis vectors provided.
  7791. *
  7792. * @param {Vector3} xAxis - The basis's x axis.
  7793. * @param {Vector3} yAxis - The basis's y axis.
  7794. * @param {Vector3} zAxis - The basis's z axis.
  7795. * @return {Matrix4} A reference to this matrix.
  7796. */
  7797. extractBasis( xAxis, yAxis, zAxis ) {
  7798. if ( this.determinant() === 0 ) {
  7799. xAxis.set( 1, 0, 0 );
  7800. yAxis.set( 0, 1, 0 );
  7801. zAxis.set( 0, 0, 1 );
  7802. return this;
  7803. }
  7804. xAxis.setFromMatrixColumn( this, 0 );
  7805. yAxis.setFromMatrixColumn( this, 1 );
  7806. zAxis.setFromMatrixColumn( this, 2 );
  7807. return this;
  7808. }
  7809. /**
  7810. * Sets the given basis vectors to this matrix.
  7811. *
  7812. * @param {Vector3} xAxis - The basis's x axis.
  7813. * @param {Vector3} yAxis - The basis's y axis.
  7814. * @param {Vector3} zAxis - The basis's z axis.
  7815. * @return {Matrix4} A reference to this matrix.
  7816. */
  7817. makeBasis( xAxis, yAxis, zAxis ) {
  7818. this.set(
  7819. xAxis.x, yAxis.x, zAxis.x, 0,
  7820. xAxis.y, yAxis.y, zAxis.y, 0,
  7821. xAxis.z, yAxis.z, zAxis.z, 0,
  7822. 0, 0, 0, 1
  7823. );
  7824. return this;
  7825. }
  7826. /**
  7827. * Extracts the rotation component of the given matrix
  7828. * into this matrix's rotation component.
  7829. *
  7830. * Note: This method does not support reflection matrices.
  7831. *
  7832. * @param {Matrix4} m - The matrix.
  7833. * @return {Matrix4} A reference to this matrix.
  7834. */
  7835. extractRotation( m ) {
  7836. if ( m.determinant() === 0 ) {
  7837. return this.identity();
  7838. }
  7839. const te = this.elements;
  7840. const me = m.elements;
  7841. const scaleX = 1 / _v1$7.setFromMatrixColumn( m, 0 ).length();
  7842. const scaleY = 1 / _v1$7.setFromMatrixColumn( m, 1 ).length();
  7843. const scaleZ = 1 / _v1$7.setFromMatrixColumn( m, 2 ).length();
  7844. te[ 0 ] = me[ 0 ] * scaleX;
  7845. te[ 1 ] = me[ 1 ] * scaleX;
  7846. te[ 2 ] = me[ 2 ] * scaleX;
  7847. te[ 3 ] = 0;
  7848. te[ 4 ] = me[ 4 ] * scaleY;
  7849. te[ 5 ] = me[ 5 ] * scaleY;
  7850. te[ 6 ] = me[ 6 ] * scaleY;
  7851. te[ 7 ] = 0;
  7852. te[ 8 ] = me[ 8 ] * scaleZ;
  7853. te[ 9 ] = me[ 9 ] * scaleZ;
  7854. te[ 10 ] = me[ 10 ] * scaleZ;
  7855. te[ 11 ] = 0;
  7856. te[ 12 ] = 0;
  7857. te[ 13 ] = 0;
  7858. te[ 14 ] = 0;
  7859. te[ 15 ] = 1;
  7860. return this;
  7861. }
  7862. /**
  7863. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  7864. * the rotation specified by the given Euler angles. The rest of
  7865. * the matrix is set to the identity. Depending on the {@link Euler#order},
  7866. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  7867. * for a complete list.
  7868. *
  7869. * @param {Euler} euler - The Euler angles.
  7870. * @return {Matrix4} A reference to this matrix.
  7871. */
  7872. makeRotationFromEuler( euler ) {
  7873. const te = this.elements;
  7874. const x = euler.x, y = euler.y, z = euler.z;
  7875. const a = Math.cos( x ), b = Math.sin( x );
  7876. const c = Math.cos( y ), d = Math.sin( y );
  7877. const e = Math.cos( z ), f = Math.sin( z );
  7878. if ( euler.order === 'XYZ' ) {
  7879. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7880. te[ 0 ] = c * e;
  7881. te[ 4 ] = - c * f;
  7882. te[ 8 ] = d;
  7883. te[ 1 ] = af + be * d;
  7884. te[ 5 ] = ae - bf * d;
  7885. te[ 9 ] = - b * c;
  7886. te[ 2 ] = bf - ae * d;
  7887. te[ 6 ] = be + af * d;
  7888. te[ 10 ] = a * c;
  7889. } else if ( euler.order === 'YXZ' ) {
  7890. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7891. te[ 0 ] = ce + df * b;
  7892. te[ 4 ] = de * b - cf;
  7893. te[ 8 ] = a * d;
  7894. te[ 1 ] = a * f;
  7895. te[ 5 ] = a * e;
  7896. te[ 9 ] = - b;
  7897. te[ 2 ] = cf * b - de;
  7898. te[ 6 ] = df + ce * b;
  7899. te[ 10 ] = a * c;
  7900. } else if ( euler.order === 'ZXY' ) {
  7901. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7902. te[ 0 ] = ce - df * b;
  7903. te[ 4 ] = - a * f;
  7904. te[ 8 ] = de + cf * b;
  7905. te[ 1 ] = cf + de * b;
  7906. te[ 5 ] = a * e;
  7907. te[ 9 ] = df - ce * b;
  7908. te[ 2 ] = - a * d;
  7909. te[ 6 ] = b;
  7910. te[ 10 ] = a * c;
  7911. } else if ( euler.order === 'ZYX' ) {
  7912. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7913. te[ 0 ] = c * e;
  7914. te[ 4 ] = be * d - af;
  7915. te[ 8 ] = ae * d + bf;
  7916. te[ 1 ] = c * f;
  7917. te[ 5 ] = bf * d + ae;
  7918. te[ 9 ] = af * d - be;
  7919. te[ 2 ] = - d;
  7920. te[ 6 ] = b * c;
  7921. te[ 10 ] = a * c;
  7922. } else if ( euler.order === 'YZX' ) {
  7923. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7924. te[ 0 ] = c * e;
  7925. te[ 4 ] = bd - ac * f;
  7926. te[ 8 ] = bc * f + ad;
  7927. te[ 1 ] = f;
  7928. te[ 5 ] = a * e;
  7929. te[ 9 ] = - b * e;
  7930. te[ 2 ] = - d * e;
  7931. te[ 6 ] = ad * f + bc;
  7932. te[ 10 ] = ac - bd * f;
  7933. } else if ( euler.order === 'XZY' ) {
  7934. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7935. te[ 0 ] = c * e;
  7936. te[ 4 ] = - f;
  7937. te[ 8 ] = d * e;
  7938. te[ 1 ] = ac * f + bd;
  7939. te[ 5 ] = a * e;
  7940. te[ 9 ] = ad * f - bc;
  7941. te[ 2 ] = bc * f - ad;
  7942. te[ 6 ] = b * e;
  7943. te[ 10 ] = bd * f + ac;
  7944. }
  7945. // bottom row
  7946. te[ 3 ] = 0;
  7947. te[ 7 ] = 0;
  7948. te[ 11 ] = 0;
  7949. // last column
  7950. te[ 12 ] = 0;
  7951. te[ 13 ] = 0;
  7952. te[ 14 ] = 0;
  7953. te[ 15 ] = 1;
  7954. return this;
  7955. }
  7956. /**
  7957. * Sets the rotation component of this matrix to the rotation specified by
  7958. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  7959. * The rest of the matrix is set to the identity.
  7960. *
  7961. * @param {Quaternion} q - The Quaternion.
  7962. * @return {Matrix4} A reference to this matrix.
  7963. */
  7964. makeRotationFromQuaternion( q ) {
  7965. return this.compose( _zero, q, _one );
  7966. }
  7967. /**
  7968. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  7969. * `target`, and oriented by the up-direction.
  7970. *
  7971. * @param {Vector3} eye - The eye vector.
  7972. * @param {Vector3} target - The target vector.
  7973. * @param {Vector3} up - The up vector.
  7974. * @return {Matrix4} A reference to this matrix.
  7975. */
  7976. lookAt( eye, target, up ) {
  7977. const te = this.elements;
  7978. _z.subVectors( eye, target );
  7979. if ( _z.lengthSq() === 0 ) {
  7980. // eye and target are in the same position
  7981. _z.z = 1;
  7982. }
  7983. _z.normalize();
  7984. _x.crossVectors( up, _z );
  7985. if ( _x.lengthSq() === 0 ) {
  7986. // up and z are parallel
  7987. if ( Math.abs( up.z ) === 1 ) {
  7988. _z.x += 0.0001;
  7989. } else {
  7990. _z.z += 0.0001;
  7991. }
  7992. _z.normalize();
  7993. _x.crossVectors( up, _z );
  7994. }
  7995. _x.normalize();
  7996. _y.crossVectors( _z, _x );
  7997. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  7998. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  7999. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8000. return this;
  8001. }
  8002. /**
  8003. * Post-multiplies this matrix by the given 4x4 matrix.
  8004. *
  8005. * @param {Matrix4} m - The matrix to multiply with.
  8006. * @return {Matrix4} A reference to this matrix.
  8007. */
  8008. multiply( m ) {
  8009. return this.multiplyMatrices( this, m );
  8010. }
  8011. /**
  8012. * Pre-multiplies this matrix by the given 4x4 matrix.
  8013. *
  8014. * @param {Matrix4} m - The matrix to multiply with.
  8015. * @return {Matrix4} A reference to this matrix.
  8016. */
  8017. premultiply( m ) {
  8018. return this.multiplyMatrices( m, this );
  8019. }
  8020. /**
  8021. * Multiples the given 4x4 matrices and stores the result
  8022. * in this matrix.
  8023. *
  8024. * @param {Matrix4} a - The first matrix.
  8025. * @param {Matrix4} b - The second matrix.
  8026. * @return {Matrix4} A reference to this matrix.
  8027. */
  8028. multiplyMatrices( a, b ) {
  8029. const ae = a.elements;
  8030. const be = b.elements;
  8031. const te = this.elements;
  8032. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8033. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8034. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8035. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8036. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8037. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8038. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8039. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8040. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8041. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8042. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8043. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8044. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8045. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8046. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8047. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8048. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8049. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8050. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8051. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8052. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8053. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8054. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8055. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8056. return this;
  8057. }
  8058. /**
  8059. * Multiplies every component of the matrix by the given scalar.
  8060. *
  8061. * @param {number} s - The scalar.
  8062. * @return {Matrix4} A reference to this matrix.
  8063. */
  8064. multiplyScalar( s ) {
  8065. const te = this.elements;
  8066. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8067. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8068. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8069. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8070. return this;
  8071. }
  8072. /**
  8073. * Computes and returns the determinant of this matrix.
  8074. *
  8075. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  8076. *
  8077. * @return {number} The determinant.
  8078. */
  8079. determinant() {
  8080. const te = this.elements;
  8081. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8082. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8083. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8084. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8085. const t11 = n23 * n34 - n24 * n33;
  8086. const t12 = n22 * n34 - n24 * n32;
  8087. const t13 = n22 * n33 - n23 * n32;
  8088. const t21 = n21 * n34 - n24 * n31;
  8089. const t22 = n21 * n33 - n23 * n31;
  8090. const t23 = n21 * n32 - n22 * n31;
  8091. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  8092. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  8093. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  8094. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  8095. }
  8096. /**
  8097. * Transposes this matrix in place.
  8098. *
  8099. * @return {Matrix4} A reference to this matrix.
  8100. */
  8101. transpose() {
  8102. const te = this.elements;
  8103. let tmp;
  8104. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8105. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8106. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8107. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8108. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8109. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8110. return this;
  8111. }
  8112. /**
  8113. * Sets the position component for this matrix from the given vector,
  8114. * without affecting the rest of the matrix.
  8115. *
  8116. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  8117. * @param {number} y - The y component of the vector.
  8118. * @param {number} z - The z component of the vector.
  8119. * @return {Matrix4} A reference to this matrix.
  8120. */
  8121. setPosition( x, y, z ) {
  8122. const te = this.elements;
  8123. if ( x.isVector3 ) {
  8124. te[ 12 ] = x.x;
  8125. te[ 13 ] = x.y;
  8126. te[ 14 ] = x.z;
  8127. } else {
  8128. te[ 12 ] = x;
  8129. te[ 13 ] = y;
  8130. te[ 14 ] = z;
  8131. }
  8132. return this;
  8133. }
  8134. /**
  8135. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  8136. * You can not invert with a determinant of zero. If you attempt this, the method produces
  8137. * a zero matrix instead.
  8138. *
  8139. * @return {Matrix4} A reference to this matrix.
  8140. */
  8141. invert() {
  8142. // based on https://github.com/toji/gl-matrix
  8143. const te = this.elements,
  8144. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  8145. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  8146. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  8147. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  8148. t1 = n11 * n22 - n21 * n12,
  8149. t2 = n11 * n32 - n31 * n12,
  8150. t3 = n11 * n42 - n41 * n12,
  8151. t4 = n21 * n32 - n31 * n22,
  8152. t5 = n21 * n42 - n41 * n22,
  8153. t6 = n31 * n42 - n41 * n32,
  8154. t7 = n13 * n24 - n23 * n14,
  8155. t8 = n13 * n34 - n33 * n14,
  8156. t9 = n13 * n44 - n43 * n14,
  8157. t10 = n23 * n34 - n33 * n24,
  8158. t11 = n23 * n44 - n43 * n24,
  8159. t12 = n33 * n44 - n43 * n34;
  8160. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  8161. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  8162. const detInv = 1 / det;
  8163. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  8164. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  8165. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  8166. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  8167. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  8168. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  8169. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  8170. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  8171. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  8172. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  8173. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  8174. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  8175. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  8176. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  8177. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  8178. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  8179. return this;
  8180. }
  8181. /**
  8182. * Multiplies the columns of this matrix by the given vector.
  8183. *
  8184. * @param {Vector3} v - The scale vector.
  8185. * @return {Matrix4} A reference to this matrix.
  8186. */
  8187. scale( v ) {
  8188. const te = this.elements;
  8189. const x = v.x, y = v.y, z = v.z;
  8190. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8191. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8192. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8193. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  8194. return this;
  8195. }
  8196. /**
  8197. * Gets the maximum scale value of the three axes.
  8198. *
  8199. * @return {number} The maximum scale.
  8200. */
  8201. getMaxScaleOnAxis() {
  8202. const te = this.elements;
  8203. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  8204. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  8205. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  8206. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  8207. }
  8208. /**
  8209. * Sets this matrix as a translation transform from the given vector.
  8210. *
  8211. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  8212. * @param {number} y - The amount to translate in the Y axis.
  8213. * @param {number} z - The amount to translate in the z axis.
  8214. * @return {Matrix4} A reference to this matrix.
  8215. */
  8216. makeTranslation( x, y, z ) {
  8217. if ( x.isVector3 ) {
  8218. this.set(
  8219. 1, 0, 0, x.x,
  8220. 0, 1, 0, x.y,
  8221. 0, 0, 1, x.z,
  8222. 0, 0, 0, 1
  8223. );
  8224. } else {
  8225. this.set(
  8226. 1, 0, 0, x,
  8227. 0, 1, 0, y,
  8228. 0, 0, 1, z,
  8229. 0, 0, 0, 1
  8230. );
  8231. }
  8232. return this;
  8233. }
  8234. /**
  8235. * Sets this matrix as a rotational transformation around the X axis by
  8236. * the given angle.
  8237. *
  8238. * @param {number} theta - The rotation in radians.
  8239. * @return {Matrix4} A reference to this matrix.
  8240. */
  8241. makeRotationX( theta ) {
  8242. const c = Math.cos( theta ), s = Math.sin( theta );
  8243. this.set(
  8244. 1, 0, 0, 0,
  8245. 0, c, - s, 0,
  8246. 0, s, c, 0,
  8247. 0, 0, 0, 1
  8248. );
  8249. return this;
  8250. }
  8251. /**
  8252. * Sets this matrix as a rotational transformation around the Y axis by
  8253. * the given angle.
  8254. *
  8255. * @param {number} theta - The rotation in radians.
  8256. * @return {Matrix4} A reference to this matrix.
  8257. */
  8258. makeRotationY( theta ) {
  8259. const c = Math.cos( theta ), s = Math.sin( theta );
  8260. this.set(
  8261. c, 0, s, 0,
  8262. 0, 1, 0, 0,
  8263. - s, 0, c, 0,
  8264. 0, 0, 0, 1
  8265. );
  8266. return this;
  8267. }
  8268. /**
  8269. * Sets this matrix as a rotational transformation around the Z axis by
  8270. * the given angle.
  8271. *
  8272. * @param {number} theta - The rotation in radians.
  8273. * @return {Matrix4} A reference to this matrix.
  8274. */
  8275. makeRotationZ( theta ) {
  8276. const c = Math.cos( theta ), s = Math.sin( theta );
  8277. this.set(
  8278. c, - s, 0, 0,
  8279. s, c, 0, 0,
  8280. 0, 0, 1, 0,
  8281. 0, 0, 0, 1
  8282. );
  8283. return this;
  8284. }
  8285. /**
  8286. * Sets this matrix as a rotational transformation around the given axis by
  8287. * the given angle.
  8288. *
  8289. * This is a somewhat controversial but mathematically sound alternative to
  8290. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  8291. *
  8292. * @param {Vector3} axis - The normalized rotation axis.
  8293. * @param {number} angle - The rotation in radians.
  8294. * @return {Matrix4} A reference to this matrix.
  8295. */
  8296. makeRotationAxis( axis, angle ) {
  8297. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  8298. const c = Math.cos( angle );
  8299. const s = Math.sin( angle );
  8300. const t = 1 - c;
  8301. const x = axis.x, y = axis.y, z = axis.z;
  8302. const tx = t * x, ty = t * y;
  8303. this.set(
  8304. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  8305. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  8306. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  8307. 0, 0, 0, 1
  8308. );
  8309. return this;
  8310. }
  8311. /**
  8312. * Sets this matrix as a scale transformation.
  8313. *
  8314. * @param {number} x - The amount to scale in the X axis.
  8315. * @param {number} y - The amount to scale in the Y axis.
  8316. * @param {number} z - The amount to scale in the Z axis.
  8317. * @return {Matrix4} A reference to this matrix.
  8318. */
  8319. makeScale( x, y, z ) {
  8320. this.set(
  8321. x, 0, 0, 0,
  8322. 0, y, 0, 0,
  8323. 0, 0, z, 0,
  8324. 0, 0, 0, 1
  8325. );
  8326. return this;
  8327. }
  8328. /**
  8329. * Sets this matrix as a shear transformation.
  8330. *
  8331. * @param {number} xy - The amount to shear X by Y.
  8332. * @param {number} xz - The amount to shear X by Z.
  8333. * @param {number} yx - The amount to shear Y by X.
  8334. * @param {number} yz - The amount to shear Y by Z.
  8335. * @param {number} zx - The amount to shear Z by X.
  8336. * @param {number} zy - The amount to shear Z by Y.
  8337. * @return {Matrix4} A reference to this matrix.
  8338. */
  8339. makeShear( xy, xz, yx, yz, zx, zy ) {
  8340. this.set(
  8341. 1, yx, zx, 0,
  8342. xy, 1, zy, 0,
  8343. xz, yz, 1, 0,
  8344. 0, 0, 0, 1
  8345. );
  8346. return this;
  8347. }
  8348. /**
  8349. * Sets this matrix to the transformation composed of the given position,
  8350. * rotation (Quaternion) and scale.
  8351. *
  8352. * @param {Vector3} position - The position vector.
  8353. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8354. * @param {Vector3} scale - The scale vector.
  8355. * @return {Matrix4} A reference to this matrix.
  8356. */
  8357. compose( position, quaternion, scale ) {
  8358. const te = this.elements;
  8359. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  8360. const x2 = x + x, y2 = y + y, z2 = z + z;
  8361. const xx = x * x2, xy = x * y2, xz = x * z2;
  8362. const yy = y * y2, yz = y * z2, zz = z * z2;
  8363. const wx = w * x2, wy = w * y2, wz = w * z2;
  8364. const sx = scale.x, sy = scale.y, sz = scale.z;
  8365. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  8366. te[ 1 ] = ( xy + wz ) * sx;
  8367. te[ 2 ] = ( xz - wy ) * sx;
  8368. te[ 3 ] = 0;
  8369. te[ 4 ] = ( xy - wz ) * sy;
  8370. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  8371. te[ 6 ] = ( yz + wx ) * sy;
  8372. te[ 7 ] = 0;
  8373. te[ 8 ] = ( xz + wy ) * sz;
  8374. te[ 9 ] = ( yz - wx ) * sz;
  8375. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  8376. te[ 11 ] = 0;
  8377. te[ 12 ] = position.x;
  8378. te[ 13 ] = position.y;
  8379. te[ 14 ] = position.z;
  8380. te[ 15 ] = 1;
  8381. return this;
  8382. }
  8383. /**
  8384. * Decomposes this matrix into its position, rotation and scale components
  8385. * and provides the result in the given objects.
  8386. *
  8387. * Note: Not all matrices are decomposable in this way. For example, if an
  8388. * object has a non-uniformly scaled parent, then the object's world matrix
  8389. * may not be decomposable, and this method may not be appropriate.
  8390. *
  8391. * @param {Vector3} position - The position vector.
  8392. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8393. * @param {Vector3} scale - The scale vector.
  8394. * @return {Matrix4} A reference to this matrix.
  8395. */
  8396. decompose( position, quaternion, scale ) {
  8397. const te = this.elements;
  8398. position.x = te[ 12 ];
  8399. position.y = te[ 13 ];
  8400. position.z = te[ 14 ];
  8401. const det = this.determinant();
  8402. if ( det === 0 ) {
  8403. scale.set( 1, 1, 1 );
  8404. quaternion.identity();
  8405. return this;
  8406. }
  8407. let sx = _v1$7.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  8408. const sy = _v1$7.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  8409. const sz = _v1$7.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  8410. // if determinant is negative, we need to invert one scale
  8411. if ( det < 0 ) sx = - sx;
  8412. // scale the rotation part
  8413. _m1$2.copy( this );
  8414. const invSX = 1 / sx;
  8415. const invSY = 1 / sy;
  8416. const invSZ = 1 / sz;
  8417. _m1$2.elements[ 0 ] *= invSX;
  8418. _m1$2.elements[ 1 ] *= invSX;
  8419. _m1$2.elements[ 2 ] *= invSX;
  8420. _m1$2.elements[ 4 ] *= invSY;
  8421. _m1$2.elements[ 5 ] *= invSY;
  8422. _m1$2.elements[ 6 ] *= invSY;
  8423. _m1$2.elements[ 8 ] *= invSZ;
  8424. _m1$2.elements[ 9 ] *= invSZ;
  8425. _m1$2.elements[ 10 ] *= invSZ;
  8426. quaternion.setFromRotationMatrix( _m1$2 );
  8427. scale.x = sx;
  8428. scale.y = sy;
  8429. scale.z = sz;
  8430. return this;
  8431. }
  8432. /**
  8433. * Creates a perspective projection matrix. This is used internally by
  8434. * {@link PerspectiveCamera#updateProjectionMatrix}.
  8435. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8436. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8437. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8438. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8439. * @param {number} near - The distance from the camera to the near plane.
  8440. * @param {number} far - The distance from the camera to the far plane.
  8441. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8442. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8443. * @return {Matrix4} A reference to this matrix.
  8444. */
  8445. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8446. const te = this.elements;
  8447. const x = 2 * near / ( right - left );
  8448. const y = 2 * near / ( top - bottom );
  8449. const a = ( right + left ) / ( right - left );
  8450. const b = ( top + bottom ) / ( top - bottom );
  8451. let c, d;
  8452. if ( reversedDepth ) {
  8453. c = near / ( far - near );
  8454. d = ( far * near ) / ( far - near );
  8455. } else {
  8456. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8457. c = - ( far + near ) / ( far - near );
  8458. d = ( -2 * far * near ) / ( far - near );
  8459. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8460. c = - far / ( far - near );
  8461. d = ( - far * near ) / ( far - near );
  8462. } else {
  8463. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  8464. }
  8465. }
  8466. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  8467. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  8468. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8469. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  8470. return this;
  8471. }
  8472. /**
  8473. * Creates a orthographic projection matrix. This is used internally by
  8474. * {@link OrthographicCamera#updateProjectionMatrix}.
  8475. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8476. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8477. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8478. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8479. * @param {number} near - The distance from the camera to the near plane.
  8480. * @param {number} far - The distance from the camera to the far plane.
  8481. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8482. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8483. * @return {Matrix4} A reference to this matrix.
  8484. */
  8485. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8486. const te = this.elements;
  8487. const x = 2 / ( right - left );
  8488. const y = 2 / ( top - bottom );
  8489. const a = - ( right + left ) / ( right - left );
  8490. const b = - ( top + bottom ) / ( top - bottom );
  8491. let c, d;
  8492. if ( reversedDepth ) {
  8493. c = 1 / ( far - near );
  8494. d = far / ( far - near );
  8495. } else {
  8496. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8497. c = -2 / ( far - near );
  8498. d = - ( far + near ) / ( far - near );
  8499. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8500. c = -1 / ( far - near );
  8501. d = - near / ( far - near );
  8502. } else {
  8503. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  8504. }
  8505. }
  8506. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  8507. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  8508. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8509. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  8510. return this;
  8511. }
  8512. /**
  8513. * Returns `true` if this matrix is equal with the given one.
  8514. *
  8515. * @param {Matrix4} matrix - The matrix to test for equality.
  8516. * @return {boolean} Whether this matrix is equal with the given one.
  8517. */
  8518. equals( matrix ) {
  8519. const te = this.elements;
  8520. const me = matrix.elements;
  8521. for ( let i = 0; i < 16; i ++ ) {
  8522. if ( te[ i ] !== me[ i ] ) return false;
  8523. }
  8524. return true;
  8525. }
  8526. /**
  8527. * Sets the elements of the matrix from the given array.
  8528. *
  8529. * @param {Array<number>} array - The matrix elements in column-major order.
  8530. * @param {number} [offset=0] - Index of the first element in the array.
  8531. * @return {Matrix4} A reference to this matrix.
  8532. */
  8533. fromArray( array, offset = 0 ) {
  8534. for ( let i = 0; i < 16; i ++ ) {
  8535. this.elements[ i ] = array[ i + offset ];
  8536. }
  8537. return this;
  8538. }
  8539. /**
  8540. * Writes the elements of this matrix to the given array. If no array is provided,
  8541. * the method returns a new instance.
  8542. *
  8543. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  8544. * @param {number} [offset=0] - Index of the first element in the array.
  8545. * @return {Array<number>} The matrix elements in column-major order.
  8546. */
  8547. toArray( array = [], offset = 0 ) {
  8548. const te = this.elements;
  8549. array[ offset ] = te[ 0 ];
  8550. array[ offset + 1 ] = te[ 1 ];
  8551. array[ offset + 2 ] = te[ 2 ];
  8552. array[ offset + 3 ] = te[ 3 ];
  8553. array[ offset + 4 ] = te[ 4 ];
  8554. array[ offset + 5 ] = te[ 5 ];
  8555. array[ offset + 6 ] = te[ 6 ];
  8556. array[ offset + 7 ] = te[ 7 ];
  8557. array[ offset + 8 ] = te[ 8 ];
  8558. array[ offset + 9 ] = te[ 9 ];
  8559. array[ offset + 10 ] = te[ 10 ];
  8560. array[ offset + 11 ] = te[ 11 ];
  8561. array[ offset + 12 ] = te[ 12 ];
  8562. array[ offset + 13 ] = te[ 13 ];
  8563. array[ offset + 14 ] = te[ 14 ];
  8564. array[ offset + 15 ] = te[ 15 ];
  8565. return array;
  8566. }
  8567. }
  8568. const _v1$7 = /*@__PURE__*/ new Vector3();
  8569. const _m1$2 = /*@__PURE__*/ new Matrix4();
  8570. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  8571. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  8572. const _x = /*@__PURE__*/ new Vector3();
  8573. const _y = /*@__PURE__*/ new Vector3();
  8574. const _z = /*@__PURE__*/ new Vector3();
  8575. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  8576. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  8577. /**
  8578. * A class representing Euler angles.
  8579. *
  8580. * Euler angles describe a rotational transformation by rotating an object on
  8581. * its various axes in specified amounts per axis, and a specified axis
  8582. * order.
  8583. *
  8584. * Iterating through an instance will yield its components (x, y, z,
  8585. * order) in the corresponding order.
  8586. *
  8587. * ```js
  8588. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  8589. * const b = new THREE.Vector3( 1, 0, 1 );
  8590. * b.applyEuler(a);
  8591. * ```
  8592. */
  8593. class Euler {
  8594. /**
  8595. * Constructs a new euler instance.
  8596. *
  8597. * @param {number} [x=0] - The angle of the x axis in radians.
  8598. * @param {number} [y=0] - The angle of the y axis in radians.
  8599. * @param {number} [z=0] - The angle of the z axis in radians.
  8600. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  8601. */
  8602. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  8603. /**
  8604. * This flag can be used for type testing.
  8605. *
  8606. * @type {boolean}
  8607. * @readonly
  8608. * @default true
  8609. */
  8610. this.isEuler = true;
  8611. this._x = x;
  8612. this._y = y;
  8613. this._z = z;
  8614. this._order = order;
  8615. }
  8616. /**
  8617. * The angle of the x axis in radians.
  8618. *
  8619. * @type {number}
  8620. * @default 0
  8621. */
  8622. get x() {
  8623. return this._x;
  8624. }
  8625. set x( value ) {
  8626. this._x = value;
  8627. this._onChangeCallback();
  8628. }
  8629. /**
  8630. * The angle of the y axis in radians.
  8631. *
  8632. * @type {number}
  8633. * @default 0
  8634. */
  8635. get y() {
  8636. return this._y;
  8637. }
  8638. set y( value ) {
  8639. this._y = value;
  8640. this._onChangeCallback();
  8641. }
  8642. /**
  8643. * The angle of the z axis in radians.
  8644. *
  8645. * @type {number}
  8646. * @default 0
  8647. */
  8648. get z() {
  8649. return this._z;
  8650. }
  8651. set z( value ) {
  8652. this._z = value;
  8653. this._onChangeCallback();
  8654. }
  8655. /**
  8656. * A string representing the order that the rotations are applied.
  8657. *
  8658. * @type {string}
  8659. * @default 'XYZ'
  8660. */
  8661. get order() {
  8662. return this._order;
  8663. }
  8664. set order( value ) {
  8665. this._order = value;
  8666. this._onChangeCallback();
  8667. }
  8668. /**
  8669. * Sets the Euler components.
  8670. *
  8671. * @param {number} x - The angle of the x axis in radians.
  8672. * @param {number} y - The angle of the y axis in radians.
  8673. * @param {number} z - The angle of the z axis in radians.
  8674. * @param {string} [order] - A string representing the order that the rotations are applied.
  8675. * @return {Euler} A reference to this Euler instance.
  8676. */
  8677. set( x, y, z, order = this._order ) {
  8678. this._x = x;
  8679. this._y = y;
  8680. this._z = z;
  8681. this._order = order;
  8682. this._onChangeCallback();
  8683. return this;
  8684. }
  8685. /**
  8686. * Returns a new Euler instance with copied values from this instance.
  8687. *
  8688. * @return {Euler} A clone of this instance.
  8689. */
  8690. clone() {
  8691. return new this.constructor( this._x, this._y, this._z, this._order );
  8692. }
  8693. /**
  8694. * Copies the values of the given Euler instance to this instance.
  8695. *
  8696. * @param {Euler} euler - The Euler instance to copy.
  8697. * @return {Euler} A reference to this Euler instance.
  8698. */
  8699. copy( euler ) {
  8700. this._x = euler._x;
  8701. this._y = euler._y;
  8702. this._z = euler._z;
  8703. this._order = euler._order;
  8704. this._onChangeCallback();
  8705. return this;
  8706. }
  8707. /**
  8708. * Sets the angles of this Euler instance from a pure rotation matrix.
  8709. *
  8710. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  8711. * @param {string} [order] - A string representing the order that the rotations are applied.
  8712. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8713. * @return {Euler} A reference to this Euler instance.
  8714. */
  8715. setFromRotationMatrix( m, order = this._order, update = true ) {
  8716. const te = m.elements;
  8717. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8718. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8719. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8720. switch ( order ) {
  8721. case 'XYZ':
  8722. this._y = Math.asin( clamp( m13, -1, 1 ) );
  8723. if ( Math.abs( m13 ) < 0.9999999 ) {
  8724. this._x = Math.atan2( - m23, m33 );
  8725. this._z = Math.atan2( - m12, m11 );
  8726. } else {
  8727. this._x = Math.atan2( m32, m22 );
  8728. this._z = 0;
  8729. }
  8730. break;
  8731. case 'YXZ':
  8732. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  8733. if ( Math.abs( m23 ) < 0.9999999 ) {
  8734. this._y = Math.atan2( m13, m33 );
  8735. this._z = Math.atan2( m21, m22 );
  8736. } else {
  8737. this._y = Math.atan2( - m31, m11 );
  8738. this._z = 0;
  8739. }
  8740. break;
  8741. case 'ZXY':
  8742. this._x = Math.asin( clamp( m32, -1, 1 ) );
  8743. if ( Math.abs( m32 ) < 0.9999999 ) {
  8744. this._y = Math.atan2( - m31, m33 );
  8745. this._z = Math.atan2( - m12, m22 );
  8746. } else {
  8747. this._y = 0;
  8748. this._z = Math.atan2( m21, m11 );
  8749. }
  8750. break;
  8751. case 'ZYX':
  8752. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  8753. if ( Math.abs( m31 ) < 0.9999999 ) {
  8754. this._x = Math.atan2( m32, m33 );
  8755. this._z = Math.atan2( m21, m11 );
  8756. } else {
  8757. this._x = 0;
  8758. this._z = Math.atan2( - m12, m22 );
  8759. }
  8760. break;
  8761. case 'YZX':
  8762. this._z = Math.asin( clamp( m21, -1, 1 ) );
  8763. if ( Math.abs( m21 ) < 0.9999999 ) {
  8764. this._x = Math.atan2( - m23, m22 );
  8765. this._y = Math.atan2( - m31, m11 );
  8766. } else {
  8767. this._x = 0;
  8768. this._y = Math.atan2( m13, m33 );
  8769. }
  8770. break;
  8771. case 'XZY':
  8772. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  8773. if ( Math.abs( m12 ) < 0.9999999 ) {
  8774. this._x = Math.atan2( m32, m22 );
  8775. this._y = Math.atan2( m13, m11 );
  8776. } else {
  8777. this._x = Math.atan2( - m23, m33 );
  8778. this._y = 0;
  8779. }
  8780. break;
  8781. default:
  8782. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  8783. }
  8784. this._order = order;
  8785. if ( update === true ) this._onChangeCallback();
  8786. return this;
  8787. }
  8788. /**
  8789. * Sets the angles of this Euler instance from a normalized quaternion.
  8790. *
  8791. * @param {Quaternion} q - A normalized Quaternion.
  8792. * @param {string} [order] - A string representing the order that the rotations are applied.
  8793. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8794. * @return {Euler} A reference to this Euler instance.
  8795. */
  8796. setFromQuaternion( q, order, update ) {
  8797. _matrix$2.makeRotationFromQuaternion( q );
  8798. return this.setFromRotationMatrix( _matrix$2, order, update );
  8799. }
  8800. /**
  8801. * Sets the angles of this Euler instance from the given vector.
  8802. *
  8803. * @param {Vector3} v - The vector.
  8804. * @param {string} [order] - A string representing the order that the rotations are applied.
  8805. * @return {Euler} A reference to this Euler instance.
  8806. */
  8807. setFromVector3( v, order = this._order ) {
  8808. return this.set( v.x, v.y, v.z, order );
  8809. }
  8810. /**
  8811. * Resets the euler angle with a new order by creating a quaternion from this
  8812. * euler angle and then setting this euler angle with the quaternion and the
  8813. * new order.
  8814. *
  8815. * Warning: This discards revolution information.
  8816. *
  8817. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  8818. * @return {Euler} A reference to this Euler instance.
  8819. */
  8820. reorder( newOrder ) {
  8821. _quaternion$4.setFromEuler( this );
  8822. return this.setFromQuaternion( _quaternion$4, newOrder );
  8823. }
  8824. /**
  8825. * Returns `true` if this Euler instance is equal with the given one.
  8826. *
  8827. * @param {Euler} euler - The Euler instance to test for equality.
  8828. * @return {boolean} Whether this Euler instance is equal with the given one.
  8829. */
  8830. equals( euler ) {
  8831. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8832. }
  8833. /**
  8834. * Sets this Euler instance's components to values from the given array. The first three
  8835. * entries of the array are assign to the x,y and z components. An optional fourth entry
  8836. * defines the Euler order.
  8837. *
  8838. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  8839. * @return {Euler} A reference to this Euler instance.
  8840. */
  8841. fromArray( array ) {
  8842. this._x = array[ 0 ];
  8843. this._y = array[ 1 ];
  8844. this._z = array[ 2 ];
  8845. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  8846. this._onChangeCallback();
  8847. return this;
  8848. }
  8849. /**
  8850. * Writes the components of this Euler instance to the given array. If no array is provided,
  8851. * the method returns a new instance.
  8852. *
  8853. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  8854. * @param {number} [offset=0] - Index of the first element in the array.
  8855. * @return {Array<number,number,number,string>} The Euler components.
  8856. */
  8857. toArray( array = [], offset = 0 ) {
  8858. array[ offset ] = this._x;
  8859. array[ offset + 1 ] = this._y;
  8860. array[ offset + 2 ] = this._z;
  8861. array[ offset + 3 ] = this._order;
  8862. return array;
  8863. }
  8864. _onChange( callback ) {
  8865. this._onChangeCallback = callback;
  8866. return this;
  8867. }
  8868. _onChangeCallback() {}
  8869. *[ Symbol.iterator ]() {
  8870. yield this._x;
  8871. yield this._y;
  8872. yield this._z;
  8873. yield this._order;
  8874. }
  8875. }
  8876. /**
  8877. * The default Euler angle order.
  8878. *
  8879. * @static
  8880. * @type {string}
  8881. * @default 'XYZ'
  8882. */
  8883. Euler.DEFAULT_ORDER = 'XYZ';
  8884. /**
  8885. * A layers object assigns an 3D object to 1 or more of 32
  8886. * layers numbered `0` to `31` - internally the layers are stored as a
  8887. * bit mask], and by default all 3D objects are a member of layer `0`.
  8888. *
  8889. * This can be used to control visibility - an object must share a layer with
  8890. * a camera to be visible when that camera's view is
  8891. * rendered.
  8892. *
  8893. * All classes that inherit from {@link Object3D} have an `layers` property which
  8894. * is an instance of this class.
  8895. */
  8896. class Layers {
  8897. /**
  8898. * Constructs a new layers instance, with membership
  8899. * initially set to layer `0`.
  8900. */
  8901. constructor() {
  8902. /**
  8903. * A bit mask storing which of the 32 layers this layers object is currently
  8904. * a member of.
  8905. *
  8906. * @type {number}
  8907. */
  8908. this.mask = 1 | 0;
  8909. }
  8910. /**
  8911. * Sets membership to the given layer, and remove membership all other layers.
  8912. *
  8913. * @param {number} layer - The layer to set.
  8914. */
  8915. set( layer ) {
  8916. this.mask = ( 1 << layer | 0 ) >>> 0;
  8917. }
  8918. /**
  8919. * Adds membership of the given layer.
  8920. *
  8921. * @param {number} layer - The layer to enable.
  8922. */
  8923. enable( layer ) {
  8924. this.mask |= 1 << layer | 0;
  8925. }
  8926. /**
  8927. * Adds membership to all layers.
  8928. */
  8929. enableAll() {
  8930. this.mask = 0xffffffff | 0;
  8931. }
  8932. /**
  8933. * Toggles the membership of the given layer.
  8934. *
  8935. * @param {number} layer - The layer to toggle.
  8936. */
  8937. toggle( layer ) {
  8938. this.mask ^= 1 << layer | 0;
  8939. }
  8940. /**
  8941. * Removes membership of the given layer.
  8942. *
  8943. * @param {number} layer - The layer to enable.
  8944. */
  8945. disable( layer ) {
  8946. this.mask &= ~ ( 1 << layer | 0 );
  8947. }
  8948. /**
  8949. * Removes the membership from all layers.
  8950. */
  8951. disableAll() {
  8952. this.mask = 0;
  8953. }
  8954. /**
  8955. * Returns `true` if this and the given layers object have at least one
  8956. * layer in common.
  8957. *
  8958. * @param {Layers} layers - The layers to test.
  8959. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  8960. */
  8961. test( layers ) {
  8962. return ( this.mask & layers.mask ) !== 0;
  8963. }
  8964. /**
  8965. * Returns `true` if the given layer is enabled.
  8966. *
  8967. * @param {number} layer - The layer to test.
  8968. * @return {boolean } Whether the given layer is enabled or not.
  8969. */
  8970. isEnabled( layer ) {
  8971. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  8972. }
  8973. }
  8974. let _object3DId = 0;
  8975. const _v1$6 = /*@__PURE__*/ new Vector3();
  8976. const _q1 = /*@__PURE__*/ new Quaternion();
  8977. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8978. const _target = /*@__PURE__*/ new Vector3();
  8979. const _position$4 = /*@__PURE__*/ new Vector3();
  8980. const _scale$3 = /*@__PURE__*/ new Vector3();
  8981. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  8982. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  8983. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  8984. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  8985. /**
  8986. * Fires when the object has been added to its parent object.
  8987. *
  8988. * @event Object3D#added
  8989. * @type {Object}
  8990. */
  8991. const _addedEvent = { type: 'added' };
  8992. /**
  8993. * Fires when the object has been removed from its parent object.
  8994. *
  8995. * @event Object3D#removed
  8996. * @type {Object}
  8997. */
  8998. const _removedEvent = { type: 'removed' };
  8999. /**
  9000. * Fires when a new child object has been added.
  9001. *
  9002. * @event Object3D#childadded
  9003. * @type {Object}
  9004. */
  9005. const _childaddedEvent = { type: 'childadded', child: null };
  9006. /**
  9007. * Fires when a child object has been removed.
  9008. *
  9009. * @event Object3D#childremoved
  9010. * @type {Object}
  9011. */
  9012. const _childremovedEvent = { type: 'childremoved', child: null };
  9013. /**
  9014. * This is the base class for most objects in three.js and provides a set of
  9015. * properties and methods for manipulating objects in 3D space.
  9016. *
  9017. * @augments EventDispatcher
  9018. */
  9019. class Object3D extends EventDispatcher {
  9020. /**
  9021. * Constructs a new 3D object.
  9022. */
  9023. constructor() {
  9024. super();
  9025. /**
  9026. * This flag can be used for type testing.
  9027. *
  9028. * @type {boolean}
  9029. * @readonly
  9030. * @default true
  9031. */
  9032. this.isObject3D = true;
  9033. /**
  9034. * The ID of the 3D object.
  9035. *
  9036. * @name Object3D#id
  9037. * @type {number}
  9038. * @readonly
  9039. */
  9040. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  9041. /**
  9042. * The UUID of the 3D object.
  9043. *
  9044. * @type {string}
  9045. * @readonly
  9046. */
  9047. this.uuid = generateUUID();
  9048. /**
  9049. * The name of the 3D object.
  9050. *
  9051. * @type {string}
  9052. */
  9053. this.name = '';
  9054. /**
  9055. * The type property is used for detecting the object type
  9056. * in context of serialization/deserialization.
  9057. *
  9058. * @type {string}
  9059. * @readonly
  9060. */
  9061. this.type = 'Object3D';
  9062. /**
  9063. * A reference to the parent object.
  9064. *
  9065. * @type {?Object3D}
  9066. * @default null
  9067. */
  9068. this.parent = null;
  9069. /**
  9070. * An array holding the child 3D objects of this instance.
  9071. *
  9072. * @type {Array<Object3D>}
  9073. */
  9074. this.children = [];
  9075. /**
  9076. * Defines the `up` direction of the 3D object which influences
  9077. * the orientation via methods like {@link Object3D#lookAt}.
  9078. *
  9079. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  9080. *
  9081. * @type {Vector3}
  9082. */
  9083. this.up = Object3D.DEFAULT_UP.clone();
  9084. const position = new Vector3();
  9085. const rotation = new Euler();
  9086. const quaternion = new Quaternion();
  9087. const scale = new Vector3( 1, 1, 1 );
  9088. function onRotationChange() {
  9089. quaternion.setFromEuler( rotation, false );
  9090. }
  9091. function onQuaternionChange() {
  9092. rotation.setFromQuaternion( quaternion, undefined, false );
  9093. }
  9094. rotation._onChange( onRotationChange );
  9095. quaternion._onChange( onQuaternionChange );
  9096. Object.defineProperties( this, {
  9097. /**
  9098. * Represents the object's local position.
  9099. *
  9100. * @name Object3D#position
  9101. * @type {Vector3}
  9102. * @default (0,0,0)
  9103. */
  9104. position: {
  9105. configurable: true,
  9106. enumerable: true,
  9107. value: position
  9108. },
  9109. /**
  9110. * Represents the object's local rotation as Euler angles, in radians.
  9111. *
  9112. * @name Object3D#rotation
  9113. * @type {Euler}
  9114. * @default (0,0,0)
  9115. */
  9116. rotation: {
  9117. configurable: true,
  9118. enumerable: true,
  9119. value: rotation
  9120. },
  9121. /**
  9122. * Represents the object's local rotation as Quaternions.
  9123. *
  9124. * @name Object3D#quaternion
  9125. * @type {Quaternion}
  9126. */
  9127. quaternion: {
  9128. configurable: true,
  9129. enumerable: true,
  9130. value: quaternion
  9131. },
  9132. /**
  9133. * Represents the object's local scale.
  9134. *
  9135. * @name Object3D#scale
  9136. * @type {Vector3}
  9137. * @default (1,1,1)
  9138. */
  9139. scale: {
  9140. configurable: true,
  9141. enumerable: true,
  9142. value: scale
  9143. },
  9144. /**
  9145. * Represents the object's model-view matrix.
  9146. *
  9147. * @name Object3D#modelViewMatrix
  9148. * @type {Matrix4}
  9149. */
  9150. modelViewMatrix: {
  9151. value: new Matrix4()
  9152. },
  9153. /**
  9154. * Represents the object's normal matrix.
  9155. *
  9156. * @name Object3D#normalMatrix
  9157. * @type {Matrix3}
  9158. */
  9159. normalMatrix: {
  9160. value: new Matrix3()
  9161. }
  9162. } );
  9163. /**
  9164. * Represents the object's transformation matrix in local space.
  9165. *
  9166. * @type {Matrix4}
  9167. */
  9168. this.matrix = new Matrix4();
  9169. /**
  9170. * Represents the object's transformation matrix in world space.
  9171. * If the 3D object has no parent, then it's identical to the local transformation matrix
  9172. *
  9173. * @type {Matrix4}
  9174. */
  9175. this.matrixWorld = new Matrix4();
  9176. /**
  9177. * When set to `true`, the engine automatically computes the local matrix from position,
  9178. * rotation and scale every frame. If set to `false`, the app is responsible for recomputing
  9179. * the local matrix by calling `updateMatrix()`.
  9180. *
  9181. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  9182. *
  9183. * @type {boolean}
  9184. * @default true
  9185. */
  9186. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  9187. /**
  9188. * When set to `true`, the engine automatically computes the world matrix from the current local
  9189. * matrix and the object's transformation hierarchy. If set to `false`, the app is responsible for
  9190. * recomputing the world matrix by directly updating the `matrixWorld` property.
  9191. *
  9192. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  9193. *
  9194. * @type {boolean}
  9195. * @default true
  9196. */
  9197. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  9198. /**
  9199. * When set to `true`, it calculates the world matrix in that frame and resets this property
  9200. * to `false`.
  9201. *
  9202. * @type {boolean}
  9203. * @default false
  9204. */
  9205. this.matrixWorldNeedsUpdate = false;
  9206. /**
  9207. * The layer membership of the 3D object. The 3D object is only visible if it has
  9208. * at least one layer in common with the camera in use. This property can also be
  9209. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  9210. *
  9211. * @type {Layers}
  9212. */
  9213. this.layers = new Layers();
  9214. /**
  9215. * When set to `true`, the 3D object gets rendered.
  9216. *
  9217. * @type {boolean}
  9218. * @default true
  9219. */
  9220. this.visible = true;
  9221. /**
  9222. * When set to `true`, the 3D object gets rendered into shadow maps.
  9223. *
  9224. * @type {boolean}
  9225. * @default false
  9226. */
  9227. this.castShadow = false;
  9228. /**
  9229. * When set to `true`, the 3D object is affected by shadows in the scene.
  9230. *
  9231. * @type {boolean}
  9232. * @default false
  9233. */
  9234. this.receiveShadow = false;
  9235. /**
  9236. * When set to `true`, the 3D object is honored by view frustum culling.
  9237. *
  9238. * @type {boolean}
  9239. * @default true
  9240. */
  9241. this.frustumCulled = true;
  9242. /**
  9243. * This value allows the default rendering order of scene graph objects to be
  9244. * overridden although opaque and transparent objects remain sorted independently.
  9245. * When this property is set for an instance of {@link Group},all descendants
  9246. * objects will be sorted and rendered together. Sorting is from lowest to highest
  9247. * render order.
  9248. *
  9249. * @type {number}
  9250. * @default 0
  9251. */
  9252. this.renderOrder = 0;
  9253. /**
  9254. * An array holding the animation clips of the 3D object.
  9255. *
  9256. * @type {Array<AnimationClip>}
  9257. */
  9258. this.animations = [];
  9259. /**
  9260. * Custom depth material to be used when rendering to the depth map. Can only be used
  9261. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  9262. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  9263. * material for proper shadows.
  9264. *
  9265. * Only relevant in context of {@link WebGLRenderer}.
  9266. *
  9267. * @type {(Material|undefined)}
  9268. * @default undefined
  9269. */
  9270. this.customDepthMaterial = undefined;
  9271. /**
  9272. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  9273. *
  9274. * Only relevant in context of {@link WebGLRenderer}.
  9275. *
  9276. * @type {(Material|undefined)}
  9277. * @default undefined
  9278. */
  9279. this.customDistanceMaterial = undefined;
  9280. /**
  9281. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  9282. * the 3D object is not going to be changed after the initial renderer. This includes
  9283. * geometry and material settings. A static 3D object can be processed by the renderer
  9284. * slightly faster since certain state checks can be bypassed.
  9285. *
  9286. * Only relevant in context of {@link WebGPURenderer}.
  9287. *
  9288. * @type {boolean}
  9289. * @default false
  9290. */
  9291. this.static = false;
  9292. /**
  9293. * An object that can be used to store custom data about the 3D object. It
  9294. * should not hold references to functions as these will not be cloned.
  9295. *
  9296. * @type {Object}
  9297. */
  9298. this.userData = {};
  9299. /**
  9300. * The pivot point for rotation and scale transformations.
  9301. * When set, rotation and scale are applied around this point
  9302. * instead of the object's origin.
  9303. *
  9304. * @type {?Vector3}
  9305. * @default null
  9306. */
  9307. this.pivot = null;
  9308. }
  9309. /**
  9310. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  9311. *
  9312. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9313. * @param {Object3D} object - The 3D object.
  9314. * @param {Camera} camera - The camera that is used to render the scene.
  9315. * @param {Camera} shadowCamera - The shadow camera.
  9316. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9317. * @param {Material} depthMaterial - The depth material.
  9318. * @param {Object} group - The geometry group data.
  9319. */
  9320. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9321. /**
  9322. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  9323. *
  9324. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9325. * @param {Object3D} object - The 3D object.
  9326. * @param {Camera} camera - The camera that is used to render the scene.
  9327. * @param {Camera} shadowCamera - The shadow camera.
  9328. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9329. * @param {Material} depthMaterial - The depth material.
  9330. * @param {Object} group - The geometry group data.
  9331. */
  9332. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9333. /**
  9334. * A callback that is executed immediately before a 3D object is rendered.
  9335. *
  9336. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9337. * @param {Object3D} object - The 3D object.
  9338. * @param {Camera} camera - The camera that is used to render the scene.
  9339. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9340. * @param {Material} material - The 3D object's material.
  9341. * @param {Object} group - The geometry group data.
  9342. */
  9343. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9344. /**
  9345. * A callback that is executed immediately after a 3D object is rendered.
  9346. *
  9347. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9348. * @param {Object3D} object - The 3D object.
  9349. * @param {Camera} camera - The camera that is used to render the scene.
  9350. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9351. * @param {Material} material - The 3D object's material.
  9352. * @param {Object} group - The geometry group data.
  9353. */
  9354. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9355. /**
  9356. * Applies the given transformation matrix to the object and updates the object's position,
  9357. * rotation and scale.
  9358. *
  9359. * @param {Matrix4} matrix - The transformation matrix.
  9360. */
  9361. applyMatrix4( matrix ) {
  9362. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9363. this.matrix.premultiply( matrix );
  9364. this.matrix.decompose( this.position, this.quaternion, this.scale );
  9365. }
  9366. /**
  9367. * Applies a rotation represented by given the quaternion to the 3D object.
  9368. *
  9369. * @param {Quaternion} q - The quaternion.
  9370. * @return {Object3D} A reference to this instance.
  9371. */
  9372. applyQuaternion( q ) {
  9373. this.quaternion.premultiply( q );
  9374. return this;
  9375. }
  9376. /**
  9377. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  9378. *
  9379. * @param {Vector3} axis - The (normalized) axis vector.
  9380. * @param {number} angle - The angle in radians.
  9381. */
  9382. setRotationFromAxisAngle( axis, angle ) {
  9383. // assumes axis is normalized
  9384. this.quaternion.setFromAxisAngle( axis, angle );
  9385. }
  9386. /**
  9387. * Sets the given rotation represented as Euler angles to the 3D object.
  9388. *
  9389. * @param {Euler} euler - The Euler angles.
  9390. */
  9391. setRotationFromEuler( euler ) {
  9392. this.quaternion.setFromEuler( euler, true );
  9393. }
  9394. /**
  9395. * Sets the given rotation represented as rotation matrix to the 3D object.
  9396. *
  9397. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  9398. * a pure rotation matrix (i.e, unscaled).
  9399. */
  9400. setRotationFromMatrix( m ) {
  9401. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9402. this.quaternion.setFromRotationMatrix( m );
  9403. }
  9404. /**
  9405. * Sets the given rotation represented as a Quaternion to the 3D object.
  9406. *
  9407. * @param {Quaternion} q - The Quaternion
  9408. */
  9409. setRotationFromQuaternion( q ) {
  9410. // assumes q is normalized
  9411. this.quaternion.copy( q );
  9412. }
  9413. /**
  9414. * Rotates the 3D object along an axis in local space.
  9415. *
  9416. * @param {Vector3} axis - The (normalized) axis vector.
  9417. * @param {number} angle - The angle in radians.
  9418. * @return {Object3D} A reference to this instance.
  9419. */
  9420. rotateOnAxis( axis, angle ) {
  9421. // rotate object on axis in object space
  9422. // axis is assumed to be normalized
  9423. _q1.setFromAxisAngle( axis, angle );
  9424. this.quaternion.multiply( _q1 );
  9425. return this;
  9426. }
  9427. /**
  9428. * Rotates the 3D object along an axis in world space.
  9429. *
  9430. * @param {Vector3} axis - The (normalized) axis vector.
  9431. * @param {number} angle - The angle in radians.
  9432. * @return {Object3D} A reference to this instance.
  9433. */
  9434. rotateOnWorldAxis( axis, angle ) {
  9435. // rotate object on axis in world space
  9436. // axis is assumed to be normalized
  9437. // method assumes no rotated parent
  9438. _q1.setFromAxisAngle( axis, angle );
  9439. this.quaternion.premultiply( _q1 );
  9440. return this;
  9441. }
  9442. /**
  9443. * Rotates the 3D object around its X axis in local space.
  9444. *
  9445. * @param {number} angle - The angle in radians.
  9446. * @return {Object3D} A reference to this instance.
  9447. */
  9448. rotateX( angle ) {
  9449. return this.rotateOnAxis( _xAxis, angle );
  9450. }
  9451. /**
  9452. * Rotates the 3D object around its Y axis in local space.
  9453. *
  9454. * @param {number} angle - The angle in radians.
  9455. * @return {Object3D} A reference to this instance.
  9456. */
  9457. rotateY( angle ) {
  9458. return this.rotateOnAxis( _yAxis, angle );
  9459. }
  9460. /**
  9461. * Rotates the 3D object around its Z axis in local space.
  9462. *
  9463. * @param {number} angle - The angle in radians.
  9464. * @return {Object3D} A reference to this instance.
  9465. */
  9466. rotateZ( angle ) {
  9467. return this.rotateOnAxis( _zAxis, angle );
  9468. }
  9469. /**
  9470. * Translate the 3D object by a distance along the given axis in local space.
  9471. *
  9472. * @param {Vector3} axis - The (normalized) axis vector.
  9473. * @param {number} distance - The distance in world units.
  9474. * @return {Object3D} A reference to this instance.
  9475. */
  9476. translateOnAxis( axis, distance ) {
  9477. // translate object by distance along axis in object space
  9478. // axis is assumed to be normalized
  9479. _v1$6.copy( axis ).applyQuaternion( this.quaternion );
  9480. this.position.add( _v1$6.multiplyScalar( distance ) );
  9481. return this;
  9482. }
  9483. /**
  9484. * Translate the 3D object by a distance along its X-axis in local space.
  9485. *
  9486. * @param {number} distance - The distance in world units.
  9487. * @return {Object3D} A reference to this instance.
  9488. */
  9489. translateX( distance ) {
  9490. return this.translateOnAxis( _xAxis, distance );
  9491. }
  9492. /**
  9493. * Translate the 3D object by a distance along its Y-axis in local space.
  9494. *
  9495. * @param {number} distance - The distance in world units.
  9496. * @return {Object3D} A reference to this instance.
  9497. */
  9498. translateY( distance ) {
  9499. return this.translateOnAxis( _yAxis, distance );
  9500. }
  9501. /**
  9502. * Translate the 3D object by a distance along its Z-axis in local space.
  9503. *
  9504. * @param {number} distance - The distance in world units.
  9505. * @return {Object3D} A reference to this instance.
  9506. */
  9507. translateZ( distance ) {
  9508. return this.translateOnAxis( _zAxis, distance );
  9509. }
  9510. /**
  9511. * Converts the given vector from this 3D object's local space to world space.
  9512. *
  9513. * @param {Vector3} vector - The vector to convert.
  9514. * @return {Vector3} The converted vector.
  9515. */
  9516. localToWorld( vector ) {
  9517. this.updateWorldMatrix( true, false );
  9518. return vector.applyMatrix4( this.matrixWorld );
  9519. }
  9520. /**
  9521. * Converts the given vector from this 3D object's world space to local space.
  9522. *
  9523. * @param {Vector3} vector - The vector to convert.
  9524. * @return {Vector3} The converted vector.
  9525. */
  9526. worldToLocal( vector ) {
  9527. this.updateWorldMatrix( true, false );
  9528. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  9529. }
  9530. /**
  9531. * Rotates the object to face a point in world space.
  9532. *
  9533. * This method does not support objects having non-uniformly-scaled parent(s).
  9534. *
  9535. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  9536. * @param {number} [y] - The y coordinate in world space.
  9537. * @param {number} [z] - The z coordinate in world space.
  9538. */
  9539. lookAt( x, y, z ) {
  9540. // This method does not support objects having non-uniformly-scaled parent(s)
  9541. if ( x.isVector3 ) {
  9542. _target.copy( x );
  9543. } else {
  9544. _target.set( x, y, z );
  9545. }
  9546. const parent = this.parent;
  9547. this.updateWorldMatrix( true, false );
  9548. _position$4.setFromMatrixPosition( this.matrixWorld );
  9549. if ( this.isCamera || this.isLight ) {
  9550. _m1$1.lookAt( _position$4, _target, this.up );
  9551. } else {
  9552. _m1$1.lookAt( _target, _position$4, this.up );
  9553. }
  9554. this.quaternion.setFromRotationMatrix( _m1$1 );
  9555. if ( parent ) {
  9556. _m1$1.extractRotation( parent.matrixWorld );
  9557. _q1.setFromRotationMatrix( _m1$1 );
  9558. this.quaternion.premultiply( _q1.invert() );
  9559. }
  9560. }
  9561. /**
  9562. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  9563. * objects may be added. Any current parent on an object passed in here will be
  9564. * removed, since an object can have at most one parent.
  9565. *
  9566. * @fires Object3D#added
  9567. * @fires Object3D#childadded
  9568. * @param {Object3D} object - The 3D object to add.
  9569. * @return {Object3D} A reference to this instance.
  9570. */
  9571. add( object ) {
  9572. if ( arguments.length > 1 ) {
  9573. for ( let i = 0; i < arguments.length; i ++ ) {
  9574. this.add( arguments[ i ] );
  9575. }
  9576. return this;
  9577. }
  9578. if ( object === this ) {
  9579. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  9580. return this;
  9581. }
  9582. if ( object && object.isObject3D ) {
  9583. object.removeFromParent();
  9584. object.parent = this;
  9585. this.children.push( object );
  9586. object.dispatchEvent( _addedEvent );
  9587. _childaddedEvent.child = object;
  9588. this.dispatchEvent( _childaddedEvent );
  9589. _childaddedEvent.child = null;
  9590. } else {
  9591. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  9592. }
  9593. return this;
  9594. }
  9595. /**
  9596. * Removes the given 3D object as child from this 3D object.
  9597. * An arbitrary number of objects may be removed.
  9598. *
  9599. * @fires Object3D#removed
  9600. * @fires Object3D#childremoved
  9601. * @param {Object3D} object - The 3D object to remove.
  9602. * @return {Object3D} A reference to this instance.
  9603. */
  9604. remove( object ) {
  9605. if ( arguments.length > 1 ) {
  9606. for ( let i = 0; i < arguments.length; i ++ ) {
  9607. this.remove( arguments[ i ] );
  9608. }
  9609. return this;
  9610. }
  9611. const index = this.children.indexOf( object );
  9612. if ( index !== -1 ) {
  9613. object.parent = null;
  9614. this.children.splice( index, 1 );
  9615. object.dispatchEvent( _removedEvent );
  9616. _childremovedEvent.child = object;
  9617. this.dispatchEvent( _childremovedEvent );
  9618. _childremovedEvent.child = null;
  9619. }
  9620. return this;
  9621. }
  9622. /**
  9623. * Removes this 3D object from its current parent.
  9624. *
  9625. * @fires Object3D#removed
  9626. * @fires Object3D#childremoved
  9627. * @return {Object3D} A reference to this instance.
  9628. */
  9629. removeFromParent() {
  9630. const parent = this.parent;
  9631. if ( parent !== null ) {
  9632. parent.remove( this );
  9633. }
  9634. return this;
  9635. }
  9636. /**
  9637. * Removes all child objects.
  9638. *
  9639. * @fires Object3D#removed
  9640. * @fires Object3D#childremoved
  9641. * @return {Object3D} A reference to this instance.
  9642. */
  9643. clear() {
  9644. return this.remove( ... this.children );
  9645. }
  9646. /**
  9647. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  9648. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  9649. *
  9650. * @fires Object3D#added
  9651. * @fires Object3D#childadded
  9652. * @param {Object3D} object - The 3D object to attach.
  9653. * @return {Object3D} A reference to this instance.
  9654. */
  9655. attach( object ) {
  9656. // adds object as a child of this, while maintaining the object's world transform
  9657. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  9658. this.updateWorldMatrix( true, false );
  9659. _m1$1.copy( this.matrixWorld ).invert();
  9660. if ( object.parent !== null ) {
  9661. object.parent.updateWorldMatrix( true, false );
  9662. _m1$1.multiply( object.parent.matrixWorld );
  9663. }
  9664. object.applyMatrix4( _m1$1 );
  9665. object.removeFromParent();
  9666. object.parent = this;
  9667. this.children.push( object );
  9668. object.updateWorldMatrix( false, true );
  9669. object.dispatchEvent( _addedEvent );
  9670. _childaddedEvent.child = object;
  9671. this.dispatchEvent( _childaddedEvent );
  9672. _childaddedEvent.child = null;
  9673. return this;
  9674. }
  9675. /**
  9676. * Searches through the 3D object and its children, starting with the 3D object
  9677. * itself, and returns the first with a matching ID.
  9678. *
  9679. * @param {number} id - The id.
  9680. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9681. */
  9682. getObjectById( id ) {
  9683. return this.getObjectByProperty( 'id', id );
  9684. }
  9685. /**
  9686. * Searches through the 3D object and its children, starting with the 3D object
  9687. * itself, and returns the first with a matching name.
  9688. *
  9689. * @param {string} name - The name.
  9690. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9691. */
  9692. getObjectByName( name ) {
  9693. return this.getObjectByProperty( 'name', name );
  9694. }
  9695. /**
  9696. * Searches through the 3D object and its children, starting with the 3D object
  9697. * itself, and returns the first with a matching property value.
  9698. *
  9699. * @param {string} name - The name of the property.
  9700. * @param {any} value - The value.
  9701. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9702. */
  9703. getObjectByProperty( name, value ) {
  9704. if ( this[ name ] === value ) return this;
  9705. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  9706. const child = this.children[ i ];
  9707. const object = child.getObjectByProperty( name, value );
  9708. if ( object !== undefined ) {
  9709. return object;
  9710. }
  9711. }
  9712. return undefined;
  9713. }
  9714. /**
  9715. * Searches through the 3D object and its children, starting with the 3D object
  9716. * itself, and returns all 3D objects with a matching property value.
  9717. *
  9718. * @param {string} name - The name of the property.
  9719. * @param {any} value - The value.
  9720. * @param {Array<Object3D>} result - The method stores the result in this array.
  9721. * @return {Array<Object3D>} The found 3D objects.
  9722. */
  9723. getObjectsByProperty( name, value, result = [] ) {
  9724. if ( this[ name ] === value ) result.push( this );
  9725. const children = this.children;
  9726. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9727. children[ i ].getObjectsByProperty( name, value, result );
  9728. }
  9729. return result;
  9730. }
  9731. /**
  9732. * Returns a vector representing the position of the 3D object in world space.
  9733. *
  9734. * @param {Vector3} target - The target vector the result is stored to.
  9735. * @return {Vector3} The 3D object's position in world space.
  9736. */
  9737. getWorldPosition( target ) {
  9738. this.updateWorldMatrix( true, false );
  9739. return target.setFromMatrixPosition( this.matrixWorld );
  9740. }
  9741. /**
  9742. * Returns a Quaternion representing the position of the 3D object in world space.
  9743. *
  9744. * @param {Quaternion} target - The target Quaternion the result is stored to.
  9745. * @return {Quaternion} The 3D object's rotation in world space.
  9746. */
  9747. getWorldQuaternion( target ) {
  9748. this.updateWorldMatrix( true, false );
  9749. this.matrixWorld.decompose( _position$4, target, _scale$3 );
  9750. return target;
  9751. }
  9752. /**
  9753. * Returns a vector representing the scale of the 3D object in world space.
  9754. *
  9755. * @param {Vector3} target - The target vector the result is stored to.
  9756. * @return {Vector3} The 3D object's scale in world space.
  9757. */
  9758. getWorldScale( target ) {
  9759. this.updateWorldMatrix( true, false );
  9760. this.matrixWorld.decompose( _position$4, _quaternion$3, target );
  9761. return target;
  9762. }
  9763. /**
  9764. * Returns a vector representing the ("look") direction of the 3D object in world space.
  9765. *
  9766. * @param {Vector3} target - The target vector the result is stored to.
  9767. * @return {Vector3} The 3D object's direction in world space.
  9768. */
  9769. getWorldDirection( target ) {
  9770. this.updateWorldMatrix( true, false );
  9771. const e = this.matrixWorld.elements;
  9772. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9773. }
  9774. /**
  9775. * Abstract method to get intersections between a casted ray and this
  9776. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  9777. * implement this method in order to use raycasting.
  9778. *
  9779. * @abstract
  9780. * @param {Raycaster} raycaster - The raycaster.
  9781. * @param {Array<Object>} intersects - An array holding the result of the method.
  9782. */
  9783. raycast( /* raycaster, intersects */ ) {}
  9784. /**
  9785. * Executes the callback on this 3D object and all descendants.
  9786. *
  9787. * Note: Modifying the scene graph inside the callback is discouraged.
  9788. *
  9789. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9790. */
  9791. traverse( callback ) {
  9792. callback( this );
  9793. const children = this.children;
  9794. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9795. children[ i ].traverse( callback );
  9796. }
  9797. }
  9798. /**
  9799. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  9800. * Descendants of invisible 3D objects are not traversed.
  9801. *
  9802. * Note: Modifying the scene graph inside the callback is discouraged.
  9803. *
  9804. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9805. */
  9806. traverseVisible( callback ) {
  9807. if ( this.visible === false ) return;
  9808. callback( this );
  9809. const children = this.children;
  9810. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9811. children[ i ].traverseVisible( callback );
  9812. }
  9813. }
  9814. /**
  9815. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  9816. *
  9817. * Note: Modifying the scene graph inside the callback is discouraged.
  9818. *
  9819. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9820. */
  9821. traverseAncestors( callback ) {
  9822. const parent = this.parent;
  9823. if ( parent !== null ) {
  9824. callback( parent );
  9825. parent.traverseAncestors( callback );
  9826. }
  9827. }
  9828. /**
  9829. * Updates the transformation matrix in local space by computing it from the current
  9830. * position, rotation and scale values.
  9831. */
  9832. updateMatrix() {
  9833. this.matrix.compose( this.position, this.quaternion, this.scale );
  9834. const pivot = this.pivot;
  9835. if ( pivot !== null ) {
  9836. const px = pivot.x, py = pivot.y, pz = pivot.z;
  9837. const te = this.matrix.elements;
  9838. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  9839. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  9840. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  9841. }
  9842. this.matrixWorldNeedsUpdate = true;
  9843. }
  9844. /**
  9845. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  9846. *
  9847. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  9848. * local space. The computation of the local and world matrix can be controlled with the
  9849. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  9850. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  9851. *
  9852. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  9853. * when {@link Object3D#matrixWorldNeedsUpdate} is `false`.
  9854. */
  9855. updateMatrixWorld( force ) {
  9856. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9857. if ( this.matrixWorldNeedsUpdate || force ) {
  9858. if ( this.matrixWorldAutoUpdate === true ) {
  9859. if ( this.parent === null ) {
  9860. this.matrixWorld.copy( this.matrix );
  9861. } else {
  9862. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9863. }
  9864. }
  9865. this.matrixWorldNeedsUpdate = false;
  9866. force = true;
  9867. }
  9868. // make sure descendants are updated if required
  9869. const children = this.children;
  9870. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9871. const child = children[ i ];
  9872. child.updateMatrixWorld( force );
  9873. }
  9874. }
  9875. /**
  9876. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  9877. * update of ancestor and descendant nodes.
  9878. *
  9879. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  9880. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  9881. */
  9882. updateWorldMatrix( updateParents, updateChildren ) {
  9883. const parent = this.parent;
  9884. if ( updateParents === true && parent !== null ) {
  9885. parent.updateWorldMatrix( true, false );
  9886. }
  9887. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9888. if ( this.matrixWorldAutoUpdate === true ) {
  9889. if ( this.parent === null ) {
  9890. this.matrixWorld.copy( this.matrix );
  9891. } else {
  9892. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9893. }
  9894. }
  9895. // make sure descendants are updated
  9896. if ( updateChildren === true ) {
  9897. const children = this.children;
  9898. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9899. const child = children[ i ];
  9900. child.updateWorldMatrix( false, true );
  9901. }
  9902. }
  9903. }
  9904. /**
  9905. * Serializes the 3D object into JSON.
  9906. *
  9907. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  9908. * @return {Object} A JSON object representing the serialized 3D object.
  9909. * @see {@link ObjectLoader#parse}
  9910. */
  9911. toJSON( meta ) {
  9912. // meta is a string when called from JSON.stringify
  9913. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  9914. const output = {};
  9915. // meta is a hash used to collect geometries, materials.
  9916. // not providing it implies that this is the root object
  9917. // being serialized.
  9918. if ( isRootObject ) {
  9919. // initialize meta obj
  9920. meta = {
  9921. geometries: {},
  9922. materials: {},
  9923. textures: {},
  9924. images: {},
  9925. shapes: {},
  9926. skeletons: {},
  9927. animations: {},
  9928. nodes: {}
  9929. };
  9930. output.metadata = {
  9931. version: 4.7,
  9932. type: 'Object',
  9933. generator: 'Object3D.toJSON'
  9934. };
  9935. }
  9936. // standard Object3D serialization
  9937. const object = {};
  9938. object.uuid = this.uuid;
  9939. object.type = this.type;
  9940. if ( this.name !== '' ) object.name = this.name;
  9941. if ( this.castShadow === true ) object.castShadow = true;
  9942. if ( this.receiveShadow === true ) object.receiveShadow = true;
  9943. if ( this.visible === false ) object.visible = false;
  9944. if ( this.frustumCulled === false ) object.frustumCulled = false;
  9945. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  9946. if ( this.static !== false ) object.static = this.static;
  9947. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  9948. object.layers = this.layers.mask;
  9949. object.matrix = this.matrix.toArray();
  9950. object.up = this.up.toArray();
  9951. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  9952. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  9953. if ( this.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, this.morphTargetDictionary );
  9954. if ( this.morphTargetInfluences !== undefined ) object.morphTargetInfluences = this.morphTargetInfluences.slice();
  9955. // object specific properties
  9956. if ( this.isInstancedMesh ) {
  9957. object.type = 'InstancedMesh';
  9958. object.count = this.count;
  9959. object.instanceMatrix = this.instanceMatrix.toJSON();
  9960. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  9961. }
  9962. if ( this.isBatchedMesh ) {
  9963. object.type = 'BatchedMesh';
  9964. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  9965. object.sortObjects = this.sortObjects;
  9966. object.drawRanges = this._drawRanges;
  9967. object.reservedRanges = this._reservedRanges;
  9968. object.geometryInfo = this._geometryInfo.map( info => ( {
  9969. ...info,
  9970. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  9971. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  9972. } ) );
  9973. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  9974. object.availableInstanceIds = this._availableInstanceIds.slice();
  9975. object.availableGeometryIds = this._availableGeometryIds.slice();
  9976. object.nextIndexStart = this._nextIndexStart;
  9977. object.nextVertexStart = this._nextVertexStart;
  9978. object.geometryCount = this._geometryCount;
  9979. object.maxInstanceCount = this._maxInstanceCount;
  9980. object.maxVertexCount = this._maxVertexCount;
  9981. object.maxIndexCount = this._maxIndexCount;
  9982. object.geometryInitialized = this._geometryInitialized;
  9983. object.matricesTexture = this._matricesTexture.toJSON( meta );
  9984. object.indirectTexture = this._indirectTexture.toJSON( meta );
  9985. if ( this._colorsTexture !== null ) {
  9986. object.colorsTexture = this._colorsTexture.toJSON( meta );
  9987. }
  9988. if ( this.boundingSphere !== null ) {
  9989. object.boundingSphere = this.boundingSphere.toJSON();
  9990. }
  9991. if ( this.boundingBox !== null ) {
  9992. object.boundingBox = this.boundingBox.toJSON();
  9993. }
  9994. }
  9995. //
  9996. function serialize( library, element ) {
  9997. if ( library[ element.uuid ] === undefined ) {
  9998. library[ element.uuid ] = element.toJSON( meta );
  9999. }
  10000. return element.uuid;
  10001. }
  10002. if ( this.isScene ) {
  10003. if ( this.background ) {
  10004. if ( this.background.isColor ) {
  10005. object.background = this.background.toJSON();
  10006. } else if ( this.background.isTexture ) {
  10007. object.background = this.background.toJSON( meta ).uuid;
  10008. }
  10009. }
  10010. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10011. object.environment = this.environment.toJSON( meta ).uuid;
  10012. }
  10013. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10014. object.geometry = serialize( meta.geometries, this.geometry );
  10015. const parameters = this.geometry.parameters;
  10016. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10017. const shapes = parameters.shapes;
  10018. if ( Array.isArray( shapes ) ) {
  10019. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10020. const shape = shapes[ i ];
  10021. serialize( meta.shapes, shape );
  10022. }
  10023. } else {
  10024. serialize( meta.shapes, shapes );
  10025. }
  10026. }
  10027. }
  10028. if ( this.isSkinnedMesh ) {
  10029. object.bindMode = this.bindMode;
  10030. object.bindMatrix = this.bindMatrix.toArray();
  10031. if ( this.skeleton !== undefined ) {
  10032. serialize( meta.skeletons, this.skeleton );
  10033. object.skeleton = this.skeleton.uuid;
  10034. }
  10035. }
  10036. if ( this.material !== undefined ) {
  10037. if ( Array.isArray( this.material ) ) {
  10038. const uuids = [];
  10039. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  10040. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10041. }
  10042. object.material = uuids;
  10043. } else {
  10044. object.material = serialize( meta.materials, this.material );
  10045. }
  10046. }
  10047. //
  10048. if ( this.children.length > 0 ) {
  10049. object.children = [];
  10050. for ( let i = 0; i < this.children.length; i ++ ) {
  10051. object.children.push( this.children[ i ].toJSON( meta ).object );
  10052. }
  10053. }
  10054. //
  10055. if ( this.animations.length > 0 ) {
  10056. object.animations = [];
  10057. for ( let i = 0; i < this.animations.length; i ++ ) {
  10058. const animation = this.animations[ i ];
  10059. object.animations.push( serialize( meta.animations, animation ) );
  10060. }
  10061. }
  10062. if ( isRootObject ) {
  10063. const geometries = extractFromCache( meta.geometries );
  10064. const materials = extractFromCache( meta.materials );
  10065. const textures = extractFromCache( meta.textures );
  10066. const images = extractFromCache( meta.images );
  10067. const shapes = extractFromCache( meta.shapes );
  10068. const skeletons = extractFromCache( meta.skeletons );
  10069. const animations = extractFromCache( meta.animations );
  10070. const nodes = extractFromCache( meta.nodes );
  10071. if ( geometries.length > 0 ) output.geometries = geometries;
  10072. if ( materials.length > 0 ) output.materials = materials;
  10073. if ( textures.length > 0 ) output.textures = textures;
  10074. if ( images.length > 0 ) output.images = images;
  10075. if ( shapes.length > 0 ) output.shapes = shapes;
  10076. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  10077. if ( animations.length > 0 ) output.animations = animations;
  10078. if ( nodes.length > 0 ) output.nodes = nodes;
  10079. }
  10080. output.object = object;
  10081. return output;
  10082. // extract data from the cache hash
  10083. // remove metadata on each item
  10084. // and return as array
  10085. function extractFromCache( cache ) {
  10086. const values = [];
  10087. for ( const key in cache ) {
  10088. const data = cache[ key ];
  10089. delete data.metadata;
  10090. values.push( data );
  10091. }
  10092. return values;
  10093. }
  10094. }
  10095. /**
  10096. * Returns a new 3D object with copied values from this instance.
  10097. *
  10098. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  10099. * @return {Object3D} A clone of this instance.
  10100. */
  10101. clone( recursive ) {
  10102. return new this.constructor().copy( this, recursive );
  10103. }
  10104. /**
  10105. * Copies the values of the given 3D object to this instance.
  10106. *
  10107. * @param {Object3D} source - The 3D object to copy.
  10108. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  10109. * @return {Object3D} A reference to this instance.
  10110. */
  10111. copy( source, recursive = true ) {
  10112. this.name = source.name;
  10113. this.up.copy( source.up );
  10114. this.position.copy( source.position );
  10115. this.rotation.order = source.rotation.order;
  10116. this.quaternion.copy( source.quaternion );
  10117. this.scale.copy( source.scale );
  10118. this.pivot = ( source.pivot !== null ) ? source.pivot.clone() : null;
  10119. this.matrix.copy( source.matrix );
  10120. this.matrixWorld.copy( source.matrixWorld );
  10121. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10122. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  10123. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10124. this.layers.mask = source.layers.mask;
  10125. this.visible = source.visible;
  10126. this.castShadow = source.castShadow;
  10127. this.receiveShadow = source.receiveShadow;
  10128. this.frustumCulled = source.frustumCulled;
  10129. this.renderOrder = source.renderOrder;
  10130. this.static = source.static;
  10131. this.animations = source.animations.slice();
  10132. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10133. if ( recursive === true ) {
  10134. for ( let i = 0; i < source.children.length; i ++ ) {
  10135. const child = source.children[ i ];
  10136. this.add( child.clone() );
  10137. }
  10138. }
  10139. return this;
  10140. }
  10141. }
  10142. /**
  10143. * The default up direction for objects, also used as the default
  10144. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  10145. *
  10146. * @static
  10147. * @type {Vector3}
  10148. * @default (0,1,0)
  10149. */
  10150. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10151. /**
  10152. * The default setting for {@link Object3D#matrixAutoUpdate} for
  10153. * newly created 3D objects.
  10154. *
  10155. * @static
  10156. * @type {boolean}
  10157. * @default true
  10158. */
  10159. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  10160. /**
  10161. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  10162. * newly created 3D objects.
  10163. *
  10164. * @static
  10165. * @type {boolean}
  10166. * @default true
  10167. */
  10168. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  10169. /**
  10170. * This is almost identical to an {@link Object3D}. Its purpose is to
  10171. * make working with groups of objects syntactically clearer.
  10172. *
  10173. * ```js
  10174. * // Create a group and add the two cubes.
  10175. * // These cubes can now be rotated / scaled etc as a group.
  10176. * const group = new THREE.Group();
  10177. *
  10178. * group.add( meshA );
  10179. * group.add( meshB );
  10180. *
  10181. * scene.add( group );
  10182. * ```
  10183. *
  10184. * @augments Object3D
  10185. */
  10186. class Group extends Object3D {
  10187. constructor() {
  10188. super();
  10189. /**
  10190. * This flag can be used for type testing.
  10191. *
  10192. * @type {boolean}
  10193. * @readonly
  10194. * @default true
  10195. */
  10196. this.isGroup = true;
  10197. this.type = 'Group';
  10198. }
  10199. }
  10200. const _moveEvent = { type: 'move' };
  10201. /**
  10202. * Class for representing a XR controller with its
  10203. * different coordinate systems.
  10204. *
  10205. * @private
  10206. */
  10207. class WebXRController {
  10208. /**
  10209. * Constructs a new XR controller.
  10210. */
  10211. constructor() {
  10212. /**
  10213. * A group representing the target ray space
  10214. * of the XR controller.
  10215. *
  10216. * @private
  10217. * @type {?Group}
  10218. * @default null
  10219. */
  10220. this._targetRay = null;
  10221. /**
  10222. * A group representing the grip space
  10223. * of the XR controller.
  10224. *
  10225. * @private
  10226. * @type {?Group}
  10227. * @default null
  10228. */
  10229. this._grip = null;
  10230. /**
  10231. * A group representing the hand space
  10232. * of the XR controller.
  10233. *
  10234. * @private
  10235. * @type {?Group}
  10236. * @default null
  10237. */
  10238. this._hand = null;
  10239. }
  10240. /**
  10241. * Returns a group representing the hand space of the XR controller.
  10242. *
  10243. * @return {Group} A group representing the hand space of the XR controller.
  10244. */
  10245. getHandSpace() {
  10246. if ( this._hand === null ) {
  10247. this._hand = new Group();
  10248. this._hand.matrixAutoUpdate = false;
  10249. this._hand.visible = false;
  10250. this._hand.joints = {};
  10251. this._hand.inputState = { pinching: false };
  10252. }
  10253. return this._hand;
  10254. }
  10255. /**
  10256. * Returns a group representing the target ray space of the XR controller.
  10257. *
  10258. * @return {Group} A group representing the target ray space of the XR controller.
  10259. */
  10260. getTargetRaySpace() {
  10261. if ( this._targetRay === null ) {
  10262. this._targetRay = new Group();
  10263. this._targetRay.matrixAutoUpdate = false;
  10264. this._targetRay.visible = false;
  10265. this._targetRay.hasLinearVelocity = false;
  10266. this._targetRay.linearVelocity = new Vector3();
  10267. this._targetRay.hasAngularVelocity = false;
  10268. this._targetRay.angularVelocity = new Vector3();
  10269. }
  10270. return this._targetRay;
  10271. }
  10272. /**
  10273. * Returns a group representing the grip space of the XR controller.
  10274. *
  10275. * @return {Group} A group representing the grip space of the XR controller.
  10276. */
  10277. getGripSpace() {
  10278. if ( this._grip === null ) {
  10279. this._grip = new Group();
  10280. this._grip.matrixAutoUpdate = false;
  10281. this._grip.visible = false;
  10282. this._grip.hasLinearVelocity = false;
  10283. this._grip.linearVelocity = new Vector3();
  10284. this._grip.hasAngularVelocity = false;
  10285. this._grip.angularVelocity = new Vector3();
  10286. this._grip.eventsEnabled = false;
  10287. }
  10288. return this._grip;
  10289. }
  10290. /**
  10291. * Dispatches the given event to the groups representing
  10292. * the different coordinate spaces of the XR controller.
  10293. *
  10294. * @param {Object} event - The event to dispatch.
  10295. * @return {WebXRController} A reference to this instance.
  10296. */
  10297. dispatchEvent( event ) {
  10298. if ( this._targetRay !== null ) {
  10299. this._targetRay.dispatchEvent( event );
  10300. }
  10301. if ( this._grip !== null ) {
  10302. this._grip.dispatchEvent( event );
  10303. }
  10304. if ( this._hand !== null ) {
  10305. this._hand.dispatchEvent( event );
  10306. }
  10307. return this;
  10308. }
  10309. /**
  10310. * Connects the controller with the given XR input source.
  10311. *
  10312. * @param {XRInputSource} inputSource - The input source.
  10313. * @return {WebXRController} A reference to this instance.
  10314. */
  10315. connect( inputSource ) {
  10316. if ( inputSource && inputSource.hand ) {
  10317. const hand = this._hand;
  10318. if ( hand ) {
  10319. for ( const inputjoint of inputSource.hand.values() ) {
  10320. // Initialize hand with joints when connected
  10321. this._getHandJoint( hand, inputjoint );
  10322. }
  10323. }
  10324. }
  10325. this.dispatchEvent( { type: 'connected', data: inputSource } );
  10326. return this;
  10327. }
  10328. /**
  10329. * Disconnects the controller from the given XR input source.
  10330. *
  10331. * @param {XRInputSource} inputSource - The input source.
  10332. * @return {WebXRController} A reference to this instance.
  10333. */
  10334. disconnect( inputSource ) {
  10335. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  10336. if ( this._targetRay !== null ) {
  10337. this._targetRay.visible = false;
  10338. }
  10339. if ( this._grip !== null ) {
  10340. this._grip.visible = false;
  10341. }
  10342. if ( this._hand !== null ) {
  10343. this._hand.visible = false;
  10344. }
  10345. return this;
  10346. }
  10347. /**
  10348. * Updates the controller with the given input source, XR frame and reference space.
  10349. * This updates the transformations of the groups that represent the different
  10350. * coordinate systems of the controller.
  10351. *
  10352. * @param {XRInputSource} inputSource - The input source.
  10353. * @param {XRFrame} frame - The XR frame.
  10354. * @param {XRReferenceSpace} referenceSpace - The reference space.
  10355. * @return {WebXRController} A reference to this instance.
  10356. */
  10357. update( inputSource, frame, referenceSpace ) {
  10358. let inputPose = null;
  10359. let gripPose = null;
  10360. let handPose = null;
  10361. const targetRay = this._targetRay;
  10362. const grip = this._grip;
  10363. const hand = this._hand;
  10364. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  10365. if ( hand && inputSource.hand ) {
  10366. handPose = true;
  10367. for ( const inputjoint of inputSource.hand.values() ) {
  10368. // Update the joints groups with the XRJoint poses
  10369. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  10370. // The transform of this joint will be updated with the joint pose on each frame
  10371. const joint = this._getHandJoint( hand, inputjoint );
  10372. if ( jointPose !== null ) {
  10373. joint.matrix.fromArray( jointPose.transform.matrix );
  10374. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  10375. joint.matrixWorldNeedsUpdate = true;
  10376. joint.jointRadius = jointPose.radius;
  10377. }
  10378. joint.visible = jointPose !== null;
  10379. }
  10380. // Custom events
  10381. // Check pinchz
  10382. const indexTip = hand.joints[ 'index-finger-tip' ];
  10383. const thumbTip = hand.joints[ 'thumb-tip' ];
  10384. const distance = indexTip.position.distanceTo( thumbTip.position );
  10385. const distanceToPinch = 0.02;
  10386. const threshold = 0.005;
  10387. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  10388. hand.inputState.pinching = false;
  10389. this.dispatchEvent( {
  10390. type: 'pinchend',
  10391. handedness: inputSource.handedness,
  10392. target: this
  10393. } );
  10394. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  10395. hand.inputState.pinching = true;
  10396. this.dispatchEvent( {
  10397. type: 'pinchstart',
  10398. handedness: inputSource.handedness,
  10399. target: this
  10400. } );
  10401. }
  10402. } else {
  10403. if ( grip !== null && inputSource.gripSpace ) {
  10404. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  10405. if ( gripPose !== null ) {
  10406. grip.matrix.fromArray( gripPose.transform.matrix );
  10407. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  10408. grip.matrixWorldNeedsUpdate = true;
  10409. if ( gripPose.linearVelocity ) {
  10410. grip.hasLinearVelocity = true;
  10411. grip.linearVelocity.copy( gripPose.linearVelocity );
  10412. } else {
  10413. grip.hasLinearVelocity = false;
  10414. }
  10415. if ( gripPose.angularVelocity ) {
  10416. grip.hasAngularVelocity = true;
  10417. grip.angularVelocity.copy( gripPose.angularVelocity );
  10418. } else {
  10419. grip.hasAngularVelocity = false;
  10420. }
  10421. // grip update event if enabled
  10422. if ( grip.eventsEnabled ) {
  10423. grip.dispatchEvent( {
  10424. type: 'gripUpdated',
  10425. data: inputSource,
  10426. target: this
  10427. } );
  10428. }
  10429. }
  10430. }
  10431. }
  10432. if ( targetRay !== null ) {
  10433. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  10434. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  10435. if ( inputPose === null && gripPose !== null ) {
  10436. inputPose = gripPose;
  10437. }
  10438. if ( inputPose !== null ) {
  10439. targetRay.matrix.fromArray( inputPose.transform.matrix );
  10440. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  10441. targetRay.matrixWorldNeedsUpdate = true;
  10442. if ( inputPose.linearVelocity ) {
  10443. targetRay.hasLinearVelocity = true;
  10444. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  10445. } else {
  10446. targetRay.hasLinearVelocity = false;
  10447. }
  10448. if ( inputPose.angularVelocity ) {
  10449. targetRay.hasAngularVelocity = true;
  10450. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  10451. } else {
  10452. targetRay.hasAngularVelocity = false;
  10453. }
  10454. this.dispatchEvent( _moveEvent );
  10455. }
  10456. }
  10457. }
  10458. if ( targetRay !== null ) {
  10459. targetRay.visible = ( inputPose !== null );
  10460. }
  10461. if ( grip !== null ) {
  10462. grip.visible = ( gripPose !== null );
  10463. }
  10464. if ( hand !== null ) {
  10465. hand.visible = ( handPose !== null );
  10466. }
  10467. return this;
  10468. }
  10469. /**
  10470. * Returns a group representing the hand joint for the given input joint.
  10471. *
  10472. * @private
  10473. * @param {Group} hand - The group representing the hand space.
  10474. * @param {XRJointSpace} inputjoint - The hand joint data.
  10475. * @return {Group} A group representing the hand joint for the given input joint.
  10476. */
  10477. _getHandJoint( hand, inputjoint ) {
  10478. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  10479. const joint = new Group();
  10480. joint.matrixAutoUpdate = false;
  10481. joint.visible = false;
  10482. hand.joints[ inputjoint.jointName ] = joint;
  10483. hand.add( joint );
  10484. }
  10485. return hand.joints[ inputjoint.jointName ];
  10486. }
  10487. }
  10488. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  10489. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  10490. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  10491. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  10492. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  10493. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  10494. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  10495. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  10496. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  10497. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  10498. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  10499. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  10500. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  10501. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  10502. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  10503. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  10504. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  10505. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  10506. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  10507. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  10508. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  10509. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  10510. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  10511. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  10512. const _hslA = { h: 0, s: 0, l: 0 };
  10513. const _hslB = { h: 0, s: 0, l: 0 };
  10514. function hue2rgb( p, q, t ) {
  10515. if ( t < 0 ) t += 1;
  10516. if ( t > 1 ) t -= 1;
  10517. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  10518. if ( t < 1 / 2 ) return q;
  10519. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  10520. return p;
  10521. }
  10522. /**
  10523. * A Color instance is represented by RGB components in the linear <i>working
  10524. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  10525. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  10526. * strings) are converted to the working color space automatically.
  10527. *
  10528. * ```js
  10529. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  10530. * const color = new THREE.Color().setHex( 0x112233 );
  10531. * ```
  10532. * Source color spaces may be specified explicitly, to ensure correct conversions.
  10533. * ```js
  10534. * // assumed already LinearSRGBColorSpace; no conversion
  10535. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  10536. *
  10537. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  10538. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  10539. * ```
  10540. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  10541. * see <i>Color management</i>. Iterating through a Color instance will yield
  10542. * its components (r, g, b) in the corresponding order. A Color can be initialised
  10543. * in any of the following ways:
  10544. * ```js
  10545. * //empty constructor - will default white
  10546. * const color1 = new THREE.Color();
  10547. *
  10548. * //Hexadecimal color (recommended)
  10549. * const color2 = new THREE.Color( 0xff0000 );
  10550. *
  10551. * //RGB string
  10552. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  10553. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  10554. *
  10555. * //X11 color name - all 140 color names are supported.
  10556. * //Note the lack of CamelCase in the name
  10557. * const color5 = new THREE.Color( 'skyblue' );
  10558. * //HSL string
  10559. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  10560. *
  10561. * //Separate RGB values between 0 and 1
  10562. * const color7 = new THREE.Color( 1, 0, 0 );
  10563. * ```
  10564. */
  10565. class Color {
  10566. /**
  10567. * Constructs a new color.
  10568. *
  10569. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  10570. * and that method is used throughout the rest of the documentation.
  10571. *
  10572. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10573. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10574. * @param {number} [g] - The green component.
  10575. * @param {number} [b] - The blue component.
  10576. */
  10577. constructor( r, g, b ) {
  10578. /**
  10579. * This flag can be used for type testing.
  10580. *
  10581. * @type {boolean}
  10582. * @readonly
  10583. * @default true
  10584. */
  10585. this.isColor = true;
  10586. /**
  10587. * The red component.
  10588. *
  10589. * @type {number}
  10590. * @default 1
  10591. */
  10592. this.r = 1;
  10593. /**
  10594. * The green component.
  10595. *
  10596. * @type {number}
  10597. * @default 1
  10598. */
  10599. this.g = 1;
  10600. /**
  10601. * The blue component.
  10602. *
  10603. * @type {number}
  10604. * @default 1
  10605. */
  10606. this.b = 1;
  10607. return this.set( r, g, b );
  10608. }
  10609. /**
  10610. * Sets the colors's components from the given values.
  10611. *
  10612. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10613. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10614. * @param {number} [g] - The green component.
  10615. * @param {number} [b] - The blue component.
  10616. * @return {Color} A reference to this color.
  10617. */
  10618. set( r, g, b ) {
  10619. if ( g === undefined && b === undefined ) {
  10620. // r is THREE.Color, hex or string
  10621. const value = r;
  10622. if ( value && value.isColor ) {
  10623. this.copy( value );
  10624. } else if ( typeof value === 'number' ) {
  10625. this.setHex( value );
  10626. } else if ( typeof value === 'string' ) {
  10627. this.setStyle( value );
  10628. }
  10629. } else {
  10630. this.setRGB( r, g, b );
  10631. }
  10632. return this;
  10633. }
  10634. /**
  10635. * Sets the colors's components to the given scalar value.
  10636. *
  10637. * @param {number} scalar - The scalar value.
  10638. * @return {Color} A reference to this color.
  10639. */
  10640. setScalar( scalar ) {
  10641. this.r = scalar;
  10642. this.g = scalar;
  10643. this.b = scalar;
  10644. return this;
  10645. }
  10646. /**
  10647. * Sets this color from a hexadecimal value.
  10648. *
  10649. * @param {number} hex - The hexadecimal value.
  10650. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10651. * @return {Color} A reference to this color.
  10652. */
  10653. setHex( hex, colorSpace = SRGBColorSpace ) {
  10654. hex = Math.floor( hex );
  10655. this.r = ( hex >> 16 & 255 ) / 255;
  10656. this.g = ( hex >> 8 & 255 ) / 255;
  10657. this.b = ( hex & 255 ) / 255;
  10658. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10659. return this;
  10660. }
  10661. /**
  10662. * Sets this color from RGB values.
  10663. *
  10664. * @param {number} r - Red channel value between `0.0` and `1.0`.
  10665. * @param {number} g - Green channel value between `0.0` and `1.0`.
  10666. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  10667. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10668. * @return {Color} A reference to this color.
  10669. */
  10670. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  10671. this.r = r;
  10672. this.g = g;
  10673. this.b = b;
  10674. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10675. return this;
  10676. }
  10677. /**
  10678. * Sets this color from RGB values.
  10679. *
  10680. * @param {number} h - Hue value between `0.0` and `1.0`.
  10681. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10682. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10683. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10684. * @return {Color} A reference to this color.
  10685. */
  10686. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  10687. // h,s,l ranges are in 0.0 - 1.0
  10688. h = euclideanModulo( h, 1 );
  10689. s = clamp( s, 0, 1 );
  10690. l = clamp( l, 0, 1 );
  10691. if ( s === 0 ) {
  10692. this.r = this.g = this.b = l;
  10693. } else {
  10694. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  10695. const q = ( 2 * l ) - p;
  10696. this.r = hue2rgb( q, p, h + 1 / 3 );
  10697. this.g = hue2rgb( q, p, h );
  10698. this.b = hue2rgb( q, p, h - 1 / 3 );
  10699. }
  10700. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10701. return this;
  10702. }
  10703. /**
  10704. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  10705. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  10706. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  10707. * all 140 color names are supported).
  10708. *
  10709. * @param {string} style - Color as a CSS-style string.
  10710. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10711. * @return {Color} A reference to this color.
  10712. */
  10713. setStyle( style, colorSpace = SRGBColorSpace ) {
  10714. function handleAlpha( string ) {
  10715. if ( string === undefined ) return;
  10716. if ( parseFloat( string ) < 1 ) {
  10717. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  10718. }
  10719. }
  10720. let m;
  10721. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  10722. // rgb / hsl
  10723. let color;
  10724. const name = m[ 1 ];
  10725. const components = m[ 2 ];
  10726. switch ( name ) {
  10727. case 'rgb':
  10728. case 'rgba':
  10729. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10730. // rgb(255,0,0) rgba(255,0,0,0.5)
  10731. handleAlpha( color[ 4 ] );
  10732. return this.setRGB(
  10733. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  10734. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  10735. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  10736. colorSpace
  10737. );
  10738. }
  10739. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10740. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10741. handleAlpha( color[ 4 ] );
  10742. return this.setRGB(
  10743. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  10744. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  10745. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  10746. colorSpace
  10747. );
  10748. }
  10749. break;
  10750. case 'hsl':
  10751. case 'hsla':
  10752. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10753. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10754. handleAlpha( color[ 4 ] );
  10755. return this.setHSL(
  10756. parseFloat( color[ 1 ] ) / 360,
  10757. parseFloat( color[ 2 ] ) / 100,
  10758. parseFloat( color[ 3 ] ) / 100,
  10759. colorSpace
  10760. );
  10761. }
  10762. break;
  10763. default:
  10764. warn( 'Color: Unknown color model ' + style );
  10765. }
  10766. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  10767. // hex color
  10768. const hex = m[ 1 ];
  10769. const size = hex.length;
  10770. if ( size === 3 ) {
  10771. // #ff0
  10772. return this.setRGB(
  10773. parseInt( hex.charAt( 0 ), 16 ) / 15,
  10774. parseInt( hex.charAt( 1 ), 16 ) / 15,
  10775. parseInt( hex.charAt( 2 ), 16 ) / 15,
  10776. colorSpace
  10777. );
  10778. } else if ( size === 6 ) {
  10779. // #ff0000
  10780. return this.setHex( parseInt( hex, 16 ), colorSpace );
  10781. } else {
  10782. warn( 'Color: Invalid hex color ' + style );
  10783. }
  10784. } else if ( style && style.length > 0 ) {
  10785. return this.setColorName( style, colorSpace );
  10786. }
  10787. return this;
  10788. }
  10789. /**
  10790. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  10791. * you don't need the other CSS-style formats.
  10792. *
  10793. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  10794. * ```js
  10795. * Color.NAMES.aliceblue // returns 0xF0F8FF
  10796. * ```
  10797. *
  10798. * @param {string} style - The color name.
  10799. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10800. * @return {Color} A reference to this color.
  10801. */
  10802. setColorName( style, colorSpace = SRGBColorSpace ) {
  10803. // color keywords
  10804. const hex = _colorKeywords[ style.toLowerCase() ];
  10805. if ( hex !== undefined ) {
  10806. // red
  10807. this.setHex( hex, colorSpace );
  10808. } else {
  10809. // unknown color
  10810. warn( 'Color: Unknown color ' + style );
  10811. }
  10812. return this;
  10813. }
  10814. /**
  10815. * Returns a new color with copied values from this instance.
  10816. *
  10817. * @return {Color} A clone of this instance.
  10818. */
  10819. clone() {
  10820. return new this.constructor( this.r, this.g, this.b );
  10821. }
  10822. /**
  10823. * Copies the values of the given color to this instance.
  10824. *
  10825. * @param {Color} color - The color to copy.
  10826. * @return {Color} A reference to this color.
  10827. */
  10828. copy( color ) {
  10829. this.r = color.r;
  10830. this.g = color.g;
  10831. this.b = color.b;
  10832. return this;
  10833. }
  10834. /**
  10835. * Copies the given color into this color, and then converts this color from
  10836. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10837. *
  10838. * @param {Color} color - The color to copy/convert.
  10839. * @return {Color} A reference to this color.
  10840. */
  10841. copySRGBToLinear( color ) {
  10842. this.r = SRGBToLinear( color.r );
  10843. this.g = SRGBToLinear( color.g );
  10844. this.b = SRGBToLinear( color.b );
  10845. return this;
  10846. }
  10847. /**
  10848. * Copies the given color into this color, and then converts this color from
  10849. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10850. *
  10851. * @param {Color} color - The color to copy/convert.
  10852. * @return {Color} A reference to this color.
  10853. */
  10854. copyLinearToSRGB( color ) {
  10855. this.r = LinearToSRGB( color.r );
  10856. this.g = LinearToSRGB( color.g );
  10857. this.b = LinearToSRGB( color.b );
  10858. return this;
  10859. }
  10860. /**
  10861. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10862. *
  10863. * @return {Color} A reference to this color.
  10864. */
  10865. convertSRGBToLinear() {
  10866. this.copySRGBToLinear( this );
  10867. return this;
  10868. }
  10869. /**
  10870. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10871. *
  10872. * @return {Color} A reference to this color.
  10873. */
  10874. convertLinearToSRGB() {
  10875. this.copyLinearToSRGB( this );
  10876. return this;
  10877. }
  10878. /**
  10879. * Returns the hexadecimal value of this color.
  10880. *
  10881. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10882. * @return {number} The hexadecimal value.
  10883. */
  10884. getHex( colorSpace = SRGBColorSpace ) {
  10885. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10886. 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 ) );
  10887. }
  10888. /**
  10889. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  10890. *
  10891. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10892. * @return {string} The hexadecimal value as a string.
  10893. */
  10894. getHexString( colorSpace = SRGBColorSpace ) {
  10895. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  10896. }
  10897. /**
  10898. * Converts the colors RGB values into the HSL format and stores them into the
  10899. * given target object.
  10900. *
  10901. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  10902. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10903. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  10904. */
  10905. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  10906. // h,s,l ranges are in 0.0 - 1.0
  10907. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10908. const r = _color.r, g = _color.g, b = _color.b;
  10909. const max = Math.max( r, g, b );
  10910. const min = Math.min( r, g, b );
  10911. let hue, saturation;
  10912. const lightness = ( min + max ) / 2.0;
  10913. if ( min === max ) {
  10914. hue = 0;
  10915. saturation = 0;
  10916. } else {
  10917. const delta = max - min;
  10918. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  10919. switch ( max ) {
  10920. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  10921. case g: hue = ( b - r ) / delta + 2; break;
  10922. case b: hue = ( r - g ) / delta + 4; break;
  10923. }
  10924. hue /= 6;
  10925. }
  10926. target.h = hue;
  10927. target.s = saturation;
  10928. target.l = lightness;
  10929. return target;
  10930. }
  10931. /**
  10932. * Returns the RGB values of this color and stores them into the given target object.
  10933. *
  10934. * @param {Color} target - The target color that is used to store the method's result.
  10935. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10936. * @return {Color} The RGB representation of this color.
  10937. */
  10938. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  10939. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10940. target.r = _color.r;
  10941. target.g = _color.g;
  10942. target.b = _color.b;
  10943. return target;
  10944. }
  10945. /**
  10946. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  10947. *
  10948. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10949. * @return {string} The CSS representation of this color.
  10950. */
  10951. getStyle( colorSpace = SRGBColorSpace ) {
  10952. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10953. const r = _color.r, g = _color.g, b = _color.b;
  10954. if ( colorSpace !== SRGBColorSpace ) {
  10955. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  10956. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  10957. }
  10958. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  10959. }
  10960. /**
  10961. * Adds the given HSL values to this color's values.
  10962. * Internally, this converts the color's RGB values to HSL, adds HSL
  10963. * and then converts the color back to RGB.
  10964. *
  10965. * @param {number} h - Hue value between `0.0` and `1.0`.
  10966. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10967. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10968. * @return {Color} A reference to this color.
  10969. */
  10970. offsetHSL( h, s, l ) {
  10971. this.getHSL( _hslA );
  10972. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  10973. }
  10974. /**
  10975. * Adds the RGB values of the given color to the RGB values of this color.
  10976. *
  10977. * @param {Color} color - The color to add.
  10978. * @return {Color} A reference to this color.
  10979. */
  10980. add( color ) {
  10981. this.r += color.r;
  10982. this.g += color.g;
  10983. this.b += color.b;
  10984. return this;
  10985. }
  10986. /**
  10987. * Adds the RGB values of the given colors and stores the result in this instance.
  10988. *
  10989. * @param {Color} color1 - The first color.
  10990. * @param {Color} color2 - The second color.
  10991. * @return {Color} A reference to this color.
  10992. */
  10993. addColors( color1, color2 ) {
  10994. this.r = color1.r + color2.r;
  10995. this.g = color1.g + color2.g;
  10996. this.b = color1.b + color2.b;
  10997. return this;
  10998. }
  10999. /**
  11000. * Adds the given scalar value to the RGB values of this color.
  11001. *
  11002. * @param {number} s - The scalar to add.
  11003. * @return {Color} A reference to this color.
  11004. */
  11005. addScalar( s ) {
  11006. this.r += s;
  11007. this.g += s;
  11008. this.b += s;
  11009. return this;
  11010. }
  11011. /**
  11012. * Subtracts the RGB values of the given color from the RGB values of this color.
  11013. *
  11014. * @param {Color} color - The color to subtract.
  11015. * @return {Color} A reference to this color.
  11016. */
  11017. sub( color ) {
  11018. this.r = Math.max( 0, this.r - color.r );
  11019. this.g = Math.max( 0, this.g - color.g );
  11020. this.b = Math.max( 0, this.b - color.b );
  11021. return this;
  11022. }
  11023. /**
  11024. * Multiplies the RGB values of the given color with the RGB values of this color.
  11025. *
  11026. * @param {Color} color - The color to multiply.
  11027. * @return {Color} A reference to this color.
  11028. */
  11029. multiply( color ) {
  11030. this.r *= color.r;
  11031. this.g *= color.g;
  11032. this.b *= color.b;
  11033. return this;
  11034. }
  11035. /**
  11036. * Multiplies the given scalar value with the RGB values of this color.
  11037. *
  11038. * @param {number} s - The scalar to multiply.
  11039. * @return {Color} A reference to this color.
  11040. */
  11041. multiplyScalar( s ) {
  11042. this.r *= s;
  11043. this.g *= s;
  11044. this.b *= s;
  11045. return this;
  11046. }
  11047. /**
  11048. * Linearly interpolates this color's RGB values toward the RGB values of the
  11049. * given color. The alpha argument can be thought of as the ratio between
  11050. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  11051. *
  11052. * @param {Color} color - The color to converge on.
  11053. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11054. * @return {Color} A reference to this color.
  11055. */
  11056. lerp( color, alpha ) {
  11057. this.r += ( color.r - this.r ) * alpha;
  11058. this.g += ( color.g - this.g ) * alpha;
  11059. this.b += ( color.b - this.b ) * alpha;
  11060. return this;
  11061. }
  11062. /**
  11063. * Linearly interpolates between the given colors and stores the result in this instance.
  11064. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  11065. * is the first and `1.0` is the second color.
  11066. *
  11067. * @param {Color} color1 - The first color.
  11068. * @param {Color} color2 - The second color.
  11069. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11070. * @return {Color} A reference to this color.
  11071. */
  11072. lerpColors( color1, color2, alpha ) {
  11073. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  11074. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  11075. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  11076. return this;
  11077. }
  11078. /**
  11079. * Linearly interpolates this color's HSL values toward the HSL values of the
  11080. * given color. It differs from {@link Color#lerp} by not interpolating straight
  11081. * from one color to the other, but instead going through all the hues in between
  11082. * those two colors. The alpha argument can be thought of as the ratio between
  11083. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  11084. *
  11085. * @param {Color} color - The color to converge on.
  11086. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11087. * @return {Color} A reference to this color.
  11088. */
  11089. lerpHSL( color, alpha ) {
  11090. this.getHSL( _hslA );
  11091. color.getHSL( _hslB );
  11092. const h = lerp( _hslA.h, _hslB.h, alpha );
  11093. const s = lerp( _hslA.s, _hslB.s, alpha );
  11094. const l = lerp( _hslA.l, _hslB.l, alpha );
  11095. this.setHSL( h, s, l );
  11096. return this;
  11097. }
  11098. /**
  11099. * Sets the color's RGB components from the given 3D vector.
  11100. *
  11101. * @param {Vector3} v - The vector to set.
  11102. * @return {Color} A reference to this color.
  11103. */
  11104. setFromVector3( v ) {
  11105. this.r = v.x;
  11106. this.g = v.y;
  11107. this.b = v.z;
  11108. return this;
  11109. }
  11110. /**
  11111. * Transforms this color with the given 3x3 matrix.
  11112. *
  11113. * @param {Matrix3} m - The matrix.
  11114. * @return {Color} A reference to this color.
  11115. */
  11116. applyMatrix3( m ) {
  11117. const r = this.r, g = this.g, b = this.b;
  11118. const e = m.elements;
  11119. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  11120. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  11121. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  11122. return this;
  11123. }
  11124. /**
  11125. * Returns `true` if this color is equal with the given one.
  11126. *
  11127. * @param {Color} c - The color to test for equality.
  11128. * @return {boolean} Whether this bounding color is equal with the given one.
  11129. */
  11130. equals( c ) {
  11131. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  11132. }
  11133. /**
  11134. * Sets this color's RGB components from the given array.
  11135. *
  11136. * @param {Array<number>} array - An array holding the RGB values.
  11137. * @param {number} [offset=0] - The offset into the array.
  11138. * @return {Color} A reference to this color.
  11139. */
  11140. fromArray( array, offset = 0 ) {
  11141. this.r = array[ offset ];
  11142. this.g = array[ offset + 1 ];
  11143. this.b = array[ offset + 2 ];
  11144. return this;
  11145. }
  11146. /**
  11147. * Writes the RGB components of this color to the given array. If no array is provided,
  11148. * the method returns a new instance.
  11149. *
  11150. * @param {Array<number>} [array=[]] - The target array holding the color components.
  11151. * @param {number} [offset=0] - Index of the first element in the array.
  11152. * @return {Array<number>} The color components.
  11153. */
  11154. toArray( array = [], offset = 0 ) {
  11155. array[ offset ] = this.r;
  11156. array[ offset + 1 ] = this.g;
  11157. array[ offset + 2 ] = this.b;
  11158. return array;
  11159. }
  11160. /**
  11161. * Sets the components of this color from the given buffer attribute.
  11162. *
  11163. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  11164. * @param {number} index - The index into the attribute.
  11165. * @return {Color} A reference to this color.
  11166. */
  11167. fromBufferAttribute( attribute, index ) {
  11168. this.r = attribute.getX( index );
  11169. this.g = attribute.getY( index );
  11170. this.b = attribute.getZ( index );
  11171. return this;
  11172. }
  11173. /**
  11174. * This methods defines the serialization result of this class. Returns the color
  11175. * as a hexadecimal value.
  11176. *
  11177. * @return {number} The hexadecimal value.
  11178. */
  11179. toJSON() {
  11180. return this.getHex();
  11181. }
  11182. *[ Symbol.iterator ]() {
  11183. yield this.r;
  11184. yield this.g;
  11185. yield this.b;
  11186. }
  11187. }
  11188. const _color = /*@__PURE__*/ new Color();
  11189. /**
  11190. * A dictionary with X11 color names.
  11191. *
  11192. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  11193. *
  11194. * @static
  11195. * @type {Object}
  11196. */
  11197. Color.NAMES = _colorKeywords;
  11198. /**
  11199. * This class can be used to define an exponential squared fog,
  11200. * which gives a clear view near the camera and a faster than exponentially
  11201. * densening fog farther from the camera.
  11202. *
  11203. * ```js
  11204. * const scene = new THREE.Scene();
  11205. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  11206. * ```
  11207. */
  11208. class FogExp2 {
  11209. /**
  11210. * Constructs a new fog.
  11211. *
  11212. * @param {number|Color} color - The fog's color.
  11213. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  11214. */
  11215. constructor( color, density = 0.00025 ) {
  11216. /**
  11217. * This flag can be used for type testing.
  11218. *
  11219. * @type {boolean}
  11220. * @readonly
  11221. * @default true
  11222. */
  11223. this.isFogExp2 = true;
  11224. /**
  11225. * The name of the fog.
  11226. *
  11227. * @type {string}
  11228. */
  11229. this.name = '';
  11230. /**
  11231. * The fog's color.
  11232. *
  11233. * @type {Color}
  11234. */
  11235. this.color = new Color( color );
  11236. /**
  11237. * Defines how fast the fog will grow dense.
  11238. *
  11239. * @type {number}
  11240. * @default 0.00025
  11241. */
  11242. this.density = density;
  11243. }
  11244. /**
  11245. * Returns a new fog with copied values from this instance.
  11246. *
  11247. * @return {FogExp2} A clone of this instance.
  11248. */
  11249. clone() {
  11250. return new FogExp2( this.color, this.density );
  11251. }
  11252. /**
  11253. * Serializes the fog into JSON.
  11254. *
  11255. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11256. * @return {Object} A JSON object representing the serialized fog
  11257. */
  11258. toJSON( /* meta */ ) {
  11259. return {
  11260. type: 'FogExp2',
  11261. name: this.name,
  11262. color: this.color.getHex(),
  11263. density: this.density
  11264. };
  11265. }
  11266. }
  11267. /**
  11268. * This class can be used to define a linear fog that grows linearly denser
  11269. * with the distance.
  11270. *
  11271. * ```js
  11272. * const scene = new THREE.Scene();
  11273. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  11274. * ```
  11275. */
  11276. class Fog {
  11277. /**
  11278. * Constructs a new fog.
  11279. *
  11280. * @param {number|Color} color - The fog's color.
  11281. * @param {number} [near=1] - The minimum distance to start applying fog.
  11282. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  11283. */
  11284. constructor( color, near = 1, far = 1000 ) {
  11285. /**
  11286. * This flag can be used for type testing.
  11287. *
  11288. * @type {boolean}
  11289. * @readonly
  11290. * @default true
  11291. */
  11292. this.isFog = true;
  11293. /**
  11294. * The name of the fog.
  11295. *
  11296. * @type {string}
  11297. */
  11298. this.name = '';
  11299. /**
  11300. * The fog's color.
  11301. *
  11302. * @type {Color}
  11303. */
  11304. this.color = new Color( color );
  11305. /**
  11306. * The minimum distance to start applying fog. Objects that are less than
  11307. * `near` units from the active camera won't be affected by fog.
  11308. *
  11309. * @type {number}
  11310. * @default 1
  11311. */
  11312. this.near = near;
  11313. /**
  11314. * The maximum distance at which fog stops being calculated and applied.
  11315. * Objects that are more than `far` units away from the active camera won't
  11316. * be affected by fog.
  11317. *
  11318. * @type {number}
  11319. * @default 1000
  11320. */
  11321. this.far = far;
  11322. }
  11323. /**
  11324. * Returns a new fog with copied values from this instance.
  11325. *
  11326. * @return {Fog} A clone of this instance.
  11327. */
  11328. clone() {
  11329. return new Fog( this.color, this.near, this.far );
  11330. }
  11331. /**
  11332. * Serializes the fog into JSON.
  11333. *
  11334. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11335. * @return {Object} A JSON object representing the serialized fog
  11336. */
  11337. toJSON( /* meta */ ) {
  11338. return {
  11339. type: 'Fog',
  11340. name: this.name,
  11341. color: this.color.getHex(),
  11342. near: this.near,
  11343. far: this.far
  11344. };
  11345. }
  11346. }
  11347. /**
  11348. * Scenes allow you to set up what is to be rendered and where by three.js.
  11349. * This is where you place 3D objects like meshes, lines or lights.
  11350. *
  11351. * @augments Object3D
  11352. */
  11353. class Scene extends Object3D {
  11354. /**
  11355. * Constructs a new scene.
  11356. */
  11357. constructor() {
  11358. super();
  11359. /**
  11360. * This flag can be used for type testing.
  11361. *
  11362. * @type {boolean}
  11363. * @readonly
  11364. * @default true
  11365. */
  11366. this.isScene = true;
  11367. this.type = 'Scene';
  11368. /**
  11369. * Defines the background of the scene. Valid inputs are:
  11370. *
  11371. * - A color for defining a uniform colored background.
  11372. * - A texture for defining a (flat) textured background.
  11373. * - Cube textures or equirectangular textures for defining a skybox.
  11374. *
  11375. * @type {?(Color|Texture)}
  11376. * @default null
  11377. */
  11378. this.background = null;
  11379. /**
  11380. * Sets the environment map for all physical materials in the scene. However,
  11381. * it's not possible to overwrite an existing texture assigned to the `envMap`
  11382. * material property.
  11383. *
  11384. * @type {?Texture}
  11385. * @default null
  11386. */
  11387. this.environment = null;
  11388. /**
  11389. * A fog instance defining the type of fog that affects everything
  11390. * rendered in the scene.
  11391. *
  11392. * @type {?(Fog|FogExp2)}
  11393. * @default null
  11394. */
  11395. this.fog = null;
  11396. /**
  11397. * Sets the blurriness of the background. Only influences environment maps
  11398. * assigned to {@link Scene#background}. Valid input is a float between `0`
  11399. * and `1`.
  11400. *
  11401. * @type {number}
  11402. * @default 0
  11403. */
  11404. this.backgroundBlurriness = 0;
  11405. /**
  11406. * Attenuates the color of the background. Only applies to background textures.
  11407. *
  11408. * @type {number}
  11409. * @default 1
  11410. */
  11411. this.backgroundIntensity = 1;
  11412. /**
  11413. * The rotation of the background in radians. Only influences environment maps
  11414. * assigned to {@link Scene#background}.
  11415. *
  11416. * @type {Euler}
  11417. * @default (0,0,0)
  11418. */
  11419. this.backgroundRotation = new Euler();
  11420. /**
  11421. * Attenuates the color of the environment. Only influences environment maps
  11422. * assigned to {@link Scene#environment}.
  11423. *
  11424. * @type {number}
  11425. * @default 1
  11426. */
  11427. this.environmentIntensity = 1;
  11428. /**
  11429. * The rotation of the environment map in radians. Only influences physical materials
  11430. * in the scene when {@link Scene#environment} is used.
  11431. *
  11432. * @type {Euler}
  11433. * @default (0,0,0)
  11434. */
  11435. this.environmentRotation = new Euler();
  11436. /**
  11437. * Forces everything in the scene to be rendered with the defined material. It is possible
  11438. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  11439. *
  11440. * @type {?Material}
  11441. * @default null
  11442. */
  11443. this.overrideMaterial = null;
  11444. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  11445. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  11446. }
  11447. }
  11448. copy( source, recursive ) {
  11449. super.copy( source, recursive );
  11450. if ( source.background !== null ) this.background = source.background.clone();
  11451. if ( source.environment !== null ) this.environment = source.environment.clone();
  11452. if ( source.fog !== null ) this.fog = source.fog.clone();
  11453. this.backgroundBlurriness = source.backgroundBlurriness;
  11454. this.backgroundIntensity = source.backgroundIntensity;
  11455. this.backgroundRotation.copy( source.backgroundRotation );
  11456. this.environmentIntensity = source.environmentIntensity;
  11457. this.environmentRotation.copy( source.environmentRotation );
  11458. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  11459. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11460. return this;
  11461. }
  11462. toJSON( meta ) {
  11463. const data = super.toJSON( meta );
  11464. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  11465. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  11466. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  11467. data.object.backgroundRotation = this.backgroundRotation.toArray();
  11468. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  11469. data.object.environmentRotation = this.environmentRotation.toArray();
  11470. return data;
  11471. }
  11472. }
  11473. const _v0$2 = /*@__PURE__*/ new Vector3();
  11474. const _v1$5 = /*@__PURE__*/ new Vector3();
  11475. const _v2$4 = /*@__PURE__*/ new Vector3();
  11476. const _v3$2 = /*@__PURE__*/ new Vector3();
  11477. const _vab = /*@__PURE__*/ new Vector3();
  11478. const _vac = /*@__PURE__*/ new Vector3();
  11479. const _vbc = /*@__PURE__*/ new Vector3();
  11480. const _vap = /*@__PURE__*/ new Vector3();
  11481. const _vbp = /*@__PURE__*/ new Vector3();
  11482. const _vcp = /*@__PURE__*/ new Vector3();
  11483. const _v40 = /*@__PURE__*/ new Vector4();
  11484. const _v41 = /*@__PURE__*/ new Vector4();
  11485. const _v42 = /*@__PURE__*/ new Vector4();
  11486. /**
  11487. * A geometric triangle as defined by three vectors representing its three corners.
  11488. */
  11489. class Triangle {
  11490. /**
  11491. * Constructs a new triangle.
  11492. *
  11493. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11494. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11495. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11496. */
  11497. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11498. /**
  11499. * The first corner of the triangle.
  11500. *
  11501. * @type {Vector3}
  11502. */
  11503. this.a = a;
  11504. /**
  11505. * The second corner of the triangle.
  11506. *
  11507. * @type {Vector3}
  11508. */
  11509. this.b = b;
  11510. /**
  11511. * The third corner of the triangle.
  11512. *
  11513. * @type {Vector3}
  11514. */
  11515. this.c = c;
  11516. }
  11517. /**
  11518. * Computes the normal vector of a triangle.
  11519. *
  11520. * @param {Vector3} a - The first corner of the triangle.
  11521. * @param {Vector3} b - The second corner of the triangle.
  11522. * @param {Vector3} c - The third corner of the triangle.
  11523. * @param {Vector3} target - The target vector that is used to store the method's result.
  11524. * @return {Vector3} The triangle's normal.
  11525. */
  11526. static getNormal( a, b, c, target ) {
  11527. target.subVectors( c, b );
  11528. _v0$2.subVectors( a, b );
  11529. target.cross( _v0$2 );
  11530. const targetLengthSq = target.lengthSq();
  11531. if ( targetLengthSq > 0 ) {
  11532. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11533. }
  11534. return target.set( 0, 0, 0 );
  11535. }
  11536. /**
  11537. * Computes a barycentric coordinates from the given vector.
  11538. * Returns `null` if the triangle is degenerate.
  11539. *
  11540. * @param {Vector3} point - A point in 3D space.
  11541. * @param {Vector3} a - The first corner of the triangle.
  11542. * @param {Vector3} b - The second corner of the triangle.
  11543. * @param {Vector3} c - The third corner of the triangle.
  11544. * @param {Vector3} target - The target vector that is used to store the method's result.
  11545. * @return {?Vector3} The barycentric coordinates for the given point
  11546. */
  11547. static getBarycoord( point, a, b, c, target ) {
  11548. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11549. _v0$2.subVectors( c, a );
  11550. _v1$5.subVectors( b, a );
  11551. _v2$4.subVectors( point, a );
  11552. const dot00 = _v0$2.dot( _v0$2 );
  11553. const dot01 = _v0$2.dot( _v1$5 );
  11554. const dot02 = _v0$2.dot( _v2$4 );
  11555. const dot11 = _v1$5.dot( _v1$5 );
  11556. const dot12 = _v1$5.dot( _v2$4 );
  11557. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11558. // collinear or singular triangle
  11559. if ( denom === 0 ) {
  11560. target.set( 0, 0, 0 );
  11561. return null;
  11562. }
  11563. const invDenom = 1 / denom;
  11564. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11565. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11566. // barycentric coordinates must always sum to 1
  11567. return target.set( 1 - u - v, v, u );
  11568. }
  11569. /**
  11570. * Returns `true` if the given point, when projected onto the plane of the
  11571. * triangle, lies within the triangle.
  11572. *
  11573. * @param {Vector3} point - The point in 3D space to test.
  11574. * @param {Vector3} a - The first corner of the triangle.
  11575. * @param {Vector3} b - The second corner of the triangle.
  11576. * @param {Vector3} c - The third corner of the triangle.
  11577. * @return {boolean} Whether the given point, when projected onto the plane of the
  11578. * triangle, lies within the triangle or not.
  11579. */
  11580. static containsPoint( point, a, b, c ) {
  11581. // if the triangle is degenerate then we can't contain a point
  11582. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11583. return false;
  11584. }
  11585. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11586. }
  11587. /**
  11588. * Computes the value barycentrically interpolated for the given point on the
  11589. * triangle. Returns `null` if the triangle is degenerate.
  11590. *
  11591. * @param {Vector3} point - Position of interpolated point.
  11592. * @param {Vector3} p1 - The first corner of the triangle.
  11593. * @param {Vector3} p2 - The second corner of the triangle.
  11594. * @param {Vector3} p3 - The third corner of the triangle.
  11595. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11596. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11597. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11598. * @param {Vector3} target - The target vector that is used to store the method's result.
  11599. * @return {?Vector3} The interpolated value.
  11600. */
  11601. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11602. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11603. target.x = 0;
  11604. target.y = 0;
  11605. if ( 'z' in target ) target.z = 0;
  11606. if ( 'w' in target ) target.w = 0;
  11607. return null;
  11608. }
  11609. target.setScalar( 0 );
  11610. target.addScaledVector( v1, _v3$2.x );
  11611. target.addScaledVector( v2, _v3$2.y );
  11612. target.addScaledVector( v3, _v3$2.z );
  11613. return target;
  11614. }
  11615. /**
  11616. * Computes the value barycentrically interpolated for the given attribute and indices.
  11617. *
  11618. * @param {BufferAttribute} attr - The attribute to interpolate.
  11619. * @param {number} i1 - Index of first vertex.
  11620. * @param {number} i2 - Index of second vertex.
  11621. * @param {number} i3 - Index of third vertex.
  11622. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11623. * @param {Vector3} target - The target vector that is used to store the method's result.
  11624. * @return {Vector3} The interpolated attribute value.
  11625. */
  11626. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11627. _v40.setScalar( 0 );
  11628. _v41.setScalar( 0 );
  11629. _v42.setScalar( 0 );
  11630. _v40.fromBufferAttribute( attr, i1 );
  11631. _v41.fromBufferAttribute( attr, i2 );
  11632. _v42.fromBufferAttribute( attr, i3 );
  11633. target.setScalar( 0 );
  11634. target.addScaledVector( _v40, barycoord.x );
  11635. target.addScaledVector( _v41, barycoord.y );
  11636. target.addScaledVector( _v42, barycoord.z );
  11637. return target;
  11638. }
  11639. /**
  11640. * Returns `true` if the triangle is oriented towards the given direction.
  11641. *
  11642. * @param {Vector3} a - The first corner of the triangle.
  11643. * @param {Vector3} b - The second corner of the triangle.
  11644. * @param {Vector3} c - The third corner of the triangle.
  11645. * @param {Vector3} direction - The (normalized) direction vector.
  11646. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11647. */
  11648. static isFrontFacing( a, b, c, direction ) {
  11649. _v0$2.subVectors( c, b );
  11650. _v1$5.subVectors( a, b );
  11651. // strictly front facing
  11652. return _v0$2.cross( _v1$5 ).dot( direction ) < 0;
  11653. }
  11654. /**
  11655. * Sets the triangle's vertices by copying the given values.
  11656. *
  11657. * @param {Vector3} a - The first corner of the triangle.
  11658. * @param {Vector3} b - The second corner of the triangle.
  11659. * @param {Vector3} c - The third corner of the triangle.
  11660. * @return {Triangle} A reference to this triangle.
  11661. */
  11662. set( a, b, c ) {
  11663. this.a.copy( a );
  11664. this.b.copy( b );
  11665. this.c.copy( c );
  11666. return this;
  11667. }
  11668. /**
  11669. * Sets the triangle's vertices by copying the given array values.
  11670. *
  11671. * @param {Array<Vector3>} points - An array with 3D points.
  11672. * @param {number} i0 - The array index representing the first corner of the triangle.
  11673. * @param {number} i1 - The array index representing the second corner of the triangle.
  11674. * @param {number} i2 - The array index representing the third corner of the triangle.
  11675. * @return {Triangle} A reference to this triangle.
  11676. */
  11677. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11678. this.a.copy( points[ i0 ] );
  11679. this.b.copy( points[ i1 ] );
  11680. this.c.copy( points[ i2 ] );
  11681. return this;
  11682. }
  11683. /**
  11684. * Sets the triangle's vertices by copying the given attribute values.
  11685. *
  11686. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11687. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11688. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11689. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11690. * @return {Triangle} A reference to this triangle.
  11691. */
  11692. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11693. this.a.fromBufferAttribute( attribute, i0 );
  11694. this.b.fromBufferAttribute( attribute, i1 );
  11695. this.c.fromBufferAttribute( attribute, i2 );
  11696. return this;
  11697. }
  11698. /**
  11699. * Returns a new triangle with copied values from this instance.
  11700. *
  11701. * @return {Triangle} A clone of this instance.
  11702. */
  11703. clone() {
  11704. return new this.constructor().copy( this );
  11705. }
  11706. /**
  11707. * Copies the values of the given triangle to this instance.
  11708. *
  11709. * @param {Triangle} triangle - The triangle to copy.
  11710. * @return {Triangle} A reference to this triangle.
  11711. */
  11712. copy( triangle ) {
  11713. this.a.copy( triangle.a );
  11714. this.b.copy( triangle.b );
  11715. this.c.copy( triangle.c );
  11716. return this;
  11717. }
  11718. /**
  11719. * Computes the area of the triangle.
  11720. *
  11721. * @return {number} The triangle's area.
  11722. */
  11723. getArea() {
  11724. _v0$2.subVectors( this.c, this.b );
  11725. _v1$5.subVectors( this.a, this.b );
  11726. return _v0$2.cross( _v1$5 ).length() * 0.5;
  11727. }
  11728. /**
  11729. * Computes the midpoint of the triangle.
  11730. *
  11731. * @param {Vector3} target - The target vector that is used to store the method's result.
  11732. * @return {Vector3} The triangle's midpoint.
  11733. */
  11734. getMidpoint( target ) {
  11735. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11736. }
  11737. /**
  11738. * Computes the normal of the triangle.
  11739. *
  11740. * @param {Vector3} target - The target vector that is used to store the method's result.
  11741. * @return {Vector3} The triangle's normal.
  11742. */
  11743. getNormal( target ) {
  11744. return Triangle.getNormal( this.a, this.b, this.c, target );
  11745. }
  11746. /**
  11747. * Computes a plane the triangle lies within.
  11748. *
  11749. * @param {Plane} target - The target vector that is used to store the method's result.
  11750. * @return {Plane} The plane the triangle lies within.
  11751. */
  11752. getPlane( target ) {
  11753. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11754. }
  11755. /**
  11756. * Computes a barycentric coordinates from the given vector.
  11757. * Returns `null` if the triangle is degenerate.
  11758. *
  11759. * @param {Vector3} point - A point in 3D space.
  11760. * @param {Vector3} target - The target vector that is used to store the method's result.
  11761. * @return {?Vector3} The barycentric coordinates for the given point
  11762. */
  11763. getBarycoord( point, target ) {
  11764. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11765. }
  11766. /**
  11767. * Computes the value barycentrically interpolated for the given point on the
  11768. * triangle. Returns `null` if the triangle is degenerate.
  11769. *
  11770. * @param {Vector3} point - Position of interpolated point.
  11771. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11772. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11773. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11774. * @param {Vector3} target - The target vector that is used to store the method's result.
  11775. * @return {?Vector3} The interpolated value.
  11776. */
  11777. getInterpolation( point, v1, v2, v3, target ) {
  11778. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11779. }
  11780. /**
  11781. * Returns `true` if the given point, when projected onto the plane of the
  11782. * triangle, lies within the triangle.
  11783. *
  11784. * @param {Vector3} point - The point in 3D space to test.
  11785. * @return {boolean} Whether the given point, when projected onto the plane of the
  11786. * triangle, lies within the triangle or not.
  11787. */
  11788. containsPoint( point ) {
  11789. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11790. }
  11791. /**
  11792. * Returns `true` if the triangle is oriented towards the given direction.
  11793. *
  11794. * @param {Vector3} direction - The (normalized) direction vector.
  11795. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11796. */
  11797. isFrontFacing( direction ) {
  11798. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11799. }
  11800. /**
  11801. * Returns `true` if this triangle intersects with the given box.
  11802. *
  11803. * @param {Box3} box - The box to intersect.
  11804. * @return {boolean} Whether this triangle intersects with the given box or not.
  11805. */
  11806. intersectsBox( box ) {
  11807. return box.intersectsTriangle( this );
  11808. }
  11809. /**
  11810. * Returns the closest point on the triangle to the given point.
  11811. *
  11812. * @param {Vector3} p - The point to compute the closest point for.
  11813. * @param {Vector3} target - The target vector that is used to store the method's result.
  11814. * @return {Vector3} The closest point on the triangle.
  11815. */
  11816. closestPointToPoint( p, target ) {
  11817. const a = this.a, b = this.b, c = this.c;
  11818. let v, w;
  11819. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11820. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11821. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11822. // basically, we're distinguishing which of the voronoi regions of the triangle
  11823. // the point lies in with the minimum amount of redundant computation.
  11824. _vab.subVectors( b, a );
  11825. _vac.subVectors( c, a );
  11826. _vap.subVectors( p, a );
  11827. const d1 = _vab.dot( _vap );
  11828. const d2 = _vac.dot( _vap );
  11829. if ( d1 <= 0 && d2 <= 0 ) {
  11830. // vertex region of A; barycentric coords (1, 0, 0)
  11831. return target.copy( a );
  11832. }
  11833. _vbp.subVectors( p, b );
  11834. const d3 = _vab.dot( _vbp );
  11835. const d4 = _vac.dot( _vbp );
  11836. if ( d3 >= 0 && d4 <= d3 ) {
  11837. // vertex region of B; barycentric coords (0, 1, 0)
  11838. return target.copy( b );
  11839. }
  11840. const vc = d1 * d4 - d3 * d2;
  11841. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11842. v = d1 / ( d1 - d3 );
  11843. // edge region of AB; barycentric coords (1-v, v, 0)
  11844. return target.copy( a ).addScaledVector( _vab, v );
  11845. }
  11846. _vcp.subVectors( p, c );
  11847. const d5 = _vab.dot( _vcp );
  11848. const d6 = _vac.dot( _vcp );
  11849. if ( d6 >= 0 && d5 <= d6 ) {
  11850. // vertex region of C; barycentric coords (0, 0, 1)
  11851. return target.copy( c );
  11852. }
  11853. const vb = d5 * d2 - d1 * d6;
  11854. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11855. w = d2 / ( d2 - d6 );
  11856. // edge region of AC; barycentric coords (1-w, 0, w)
  11857. return target.copy( a ).addScaledVector( _vac, w );
  11858. }
  11859. const va = d3 * d6 - d5 * d4;
  11860. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11861. _vbc.subVectors( c, b );
  11862. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11863. // edge region of BC; barycentric coords (0, 1-w, w)
  11864. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11865. }
  11866. // face region
  11867. const denom = 1 / ( va + vb + vc );
  11868. // u = va * denom
  11869. v = vb * denom;
  11870. w = vc * denom;
  11871. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11872. }
  11873. /**
  11874. * Returns `true` if this triangle is equal with the given one.
  11875. *
  11876. * @param {Triangle} triangle - The triangle to test for equality.
  11877. * @return {boolean} Whether this triangle is equal with the given one.
  11878. */
  11879. equals( triangle ) {
  11880. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11881. }
  11882. }
  11883. /**
  11884. * Represents an axis-aligned bounding box (AABB) in 3D space.
  11885. */
  11886. class Box3 {
  11887. /**
  11888. * Constructs a new bounding box.
  11889. *
  11890. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  11891. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  11892. */
  11893. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  11894. /**
  11895. * This flag can be used for type testing.
  11896. *
  11897. * @type {boolean}
  11898. * @readonly
  11899. * @default true
  11900. */
  11901. this.isBox3 = true;
  11902. /**
  11903. * The lower boundary of the box.
  11904. *
  11905. * @type {Vector3}
  11906. */
  11907. this.min = min;
  11908. /**
  11909. * The upper boundary of the box.
  11910. *
  11911. * @type {Vector3}
  11912. */
  11913. this.max = max;
  11914. }
  11915. /**
  11916. * Sets the lower and upper boundaries of this box.
  11917. * Please note that this method only copies the values from the given objects.
  11918. *
  11919. * @param {Vector3} min - The lower boundary of the box.
  11920. * @param {Vector3} max - The upper boundary of the box.
  11921. * @return {Box3} A reference to this bounding box.
  11922. */
  11923. set( min, max ) {
  11924. this.min.copy( min );
  11925. this.max.copy( max );
  11926. return this;
  11927. }
  11928. /**
  11929. * Sets the upper and lower bounds of this box so it encloses the position data
  11930. * in the given array.
  11931. *
  11932. * @param {Array<number>} array - An array holding 3D position data.
  11933. * @return {Box3} A reference to this bounding box.
  11934. */
  11935. setFromArray( array ) {
  11936. this.makeEmpty();
  11937. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  11938. this.expandByPoint( _vector$b.fromArray( array, i ) );
  11939. }
  11940. return this;
  11941. }
  11942. /**
  11943. * Sets the upper and lower bounds of this box so it encloses the position data
  11944. * in the given buffer attribute.
  11945. *
  11946. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  11947. * @return {Box3} A reference to this bounding box.
  11948. */
  11949. setFromBufferAttribute( attribute ) {
  11950. this.makeEmpty();
  11951. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  11952. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  11953. }
  11954. return this;
  11955. }
  11956. /**
  11957. * Sets the upper and lower bounds of this box so it encloses the position data
  11958. * in the given array.
  11959. *
  11960. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  11961. * @return {Box3} A reference to this bounding box.
  11962. */
  11963. setFromPoints( points ) {
  11964. this.makeEmpty();
  11965. for ( let i = 0, il = points.length; i < il; i ++ ) {
  11966. this.expandByPoint( points[ i ] );
  11967. }
  11968. return this;
  11969. }
  11970. /**
  11971. * Centers this box on the given center vector and sets this box's width, height and
  11972. * depth to the given size values.
  11973. *
  11974. * @param {Vector3} center - The center of the box.
  11975. * @param {Vector3} size - The x, y and z dimensions of the box.
  11976. * @return {Box3} A reference to this bounding box.
  11977. */
  11978. setFromCenterAndSize( center, size ) {
  11979. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  11980. this.min.copy( center ).sub( halfSize );
  11981. this.max.copy( center ).add( halfSize );
  11982. return this;
  11983. }
  11984. /**
  11985. * Computes the world-axis-aligned bounding box for the given 3D object
  11986. * (including its children), accounting for the object's, and children's,
  11987. * world transforms. The function may result in a larger box than strictly necessary.
  11988. *
  11989. * @param {Object3D} object - The 3D object to compute the bounding box for.
  11990. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  11991. * world-axis-aligned bounding box at the expense of more computation.
  11992. * @return {Box3} A reference to this bounding box.
  11993. */
  11994. setFromObject( object, precise = false ) {
  11995. this.makeEmpty();
  11996. return this.expandByObject( object, precise );
  11997. }
  11998. /**
  11999. * Returns a new box with copied values from this instance.
  12000. *
  12001. * @return {Box3} A clone of this instance.
  12002. */
  12003. clone() {
  12004. return new this.constructor().copy( this );
  12005. }
  12006. /**
  12007. * Copies the values of the given box to this instance.
  12008. *
  12009. * @param {Box3} box - The box to copy.
  12010. * @return {Box3} A reference to this bounding box.
  12011. */
  12012. copy( box ) {
  12013. this.min.copy( box.min );
  12014. this.max.copy( box.max );
  12015. return this;
  12016. }
  12017. /**
  12018. * Makes this box empty which means in encloses a zero space in 3D.
  12019. *
  12020. * @return {Box3} A reference to this bounding box.
  12021. */
  12022. makeEmpty() {
  12023. this.min.x = this.min.y = this.min.z = + Infinity;
  12024. this.max.x = this.max.y = this.max.z = - Infinity;
  12025. return this;
  12026. }
  12027. /**
  12028. * Returns true if this box includes zero points within its bounds.
  12029. * Note that a box with equal lower and upper bounds still includes one
  12030. * point, the one both bounds share.
  12031. *
  12032. * @return {boolean} Whether this box is empty or not.
  12033. */
  12034. isEmpty() {
  12035. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  12036. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  12037. }
  12038. /**
  12039. * Returns the center point of this box.
  12040. *
  12041. * @param {Vector3} target - The target vector that is used to store the method's result.
  12042. * @return {Vector3} The center point.
  12043. */
  12044. getCenter( target ) {
  12045. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  12046. }
  12047. /**
  12048. * Returns the dimensions of this box.
  12049. *
  12050. * @param {Vector3} target - The target vector that is used to store the method's result.
  12051. * @return {Vector3} The size.
  12052. */
  12053. getSize( target ) {
  12054. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  12055. }
  12056. /**
  12057. * Expands the boundaries of this box to include the given point.
  12058. *
  12059. * @param {Vector3} point - The point that should be included by the bounding box.
  12060. * @return {Box3} A reference to this bounding box.
  12061. */
  12062. expandByPoint( point ) {
  12063. this.min.min( point );
  12064. this.max.max( point );
  12065. return this;
  12066. }
  12067. /**
  12068. * Expands this box equilaterally by the given vector. The width of this
  12069. * box will be expanded by the x component of the vector in both
  12070. * directions. The height of this box will be expanded by the y component of
  12071. * the vector in both directions. The depth of this box will be
  12072. * expanded by the z component of the vector in both directions.
  12073. *
  12074. * @param {Vector3} vector - The vector that should expand the bounding box.
  12075. * @return {Box3} A reference to this bounding box.
  12076. */
  12077. expandByVector( vector ) {
  12078. this.min.sub( vector );
  12079. this.max.add( vector );
  12080. return this;
  12081. }
  12082. /**
  12083. * Expands each dimension of the box by the given scalar. If negative, the
  12084. * dimensions of the box will be contracted.
  12085. *
  12086. * @param {number} scalar - The scalar value that should expand the bounding box.
  12087. * @return {Box3} A reference to this bounding box.
  12088. */
  12089. expandByScalar( scalar ) {
  12090. this.min.addScalar( - scalar );
  12091. this.max.addScalar( scalar );
  12092. return this;
  12093. }
  12094. /**
  12095. * Expands the boundaries of this box to include the given 3D object and
  12096. * its children, accounting for the object's, and children's, world
  12097. * transforms. The function may result in a larger box than strictly
  12098. * necessary (unless the precise parameter is set to true).
  12099. *
  12100. * @param {Object3D} object - The 3D object that should expand the bounding box.
  12101. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  12102. * as little as necessary at the expense of more computation.
  12103. * @return {Box3} A reference to this bounding box.
  12104. */
  12105. expandByObject( object, precise = false ) {
  12106. // Computes the world-axis-aligned bounding box of an object (including its children),
  12107. // accounting for both the object's, and children's, world transforms
  12108. object.updateWorldMatrix( false, false );
  12109. const geometry = object.geometry;
  12110. if ( geometry !== undefined ) {
  12111. const positionAttribute = geometry.getAttribute( 'position' );
  12112. // precise AABB computation based on vertex data requires at least a position attribute.
  12113. // instancing isn't supported so far and uses the normal (conservative) code path.
  12114. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  12115. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  12116. if ( object.isMesh === true ) {
  12117. object.getVertexPosition( i, _vector$b );
  12118. } else {
  12119. _vector$b.fromBufferAttribute( positionAttribute, i );
  12120. }
  12121. _vector$b.applyMatrix4( object.matrixWorld );
  12122. this.expandByPoint( _vector$b );
  12123. }
  12124. } else {
  12125. if ( object.boundingBox !== undefined ) {
  12126. // object-level bounding box
  12127. if ( object.boundingBox === null ) {
  12128. object.computeBoundingBox();
  12129. }
  12130. _box$4.copy( object.boundingBox );
  12131. } else {
  12132. // geometry-level bounding box
  12133. if ( geometry.boundingBox === null ) {
  12134. geometry.computeBoundingBox();
  12135. }
  12136. _box$4.copy( geometry.boundingBox );
  12137. }
  12138. _box$4.applyMatrix4( object.matrixWorld );
  12139. this.union( _box$4 );
  12140. }
  12141. }
  12142. const children = object.children;
  12143. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12144. this.expandByObject( children[ i ], precise );
  12145. }
  12146. return this;
  12147. }
  12148. /**
  12149. * Returns `true` if the given point lies within or on the boundaries of this box.
  12150. *
  12151. * @param {Vector3} point - The point to test.
  12152. * @return {boolean} Whether the bounding box contains the given point or not.
  12153. */
  12154. containsPoint( point ) {
  12155. return point.x >= this.min.x && point.x <= this.max.x &&
  12156. point.y >= this.min.y && point.y <= this.max.y &&
  12157. point.z >= this.min.z && point.z <= this.max.z;
  12158. }
  12159. /**
  12160. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  12161. * If this box and the given one are identical, this function also returns `true`.
  12162. *
  12163. * @param {Box3} box - The bounding box to test.
  12164. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  12165. */
  12166. containsBox( box ) {
  12167. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  12168. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  12169. this.min.z <= box.min.z && box.max.z <= this.max.z;
  12170. }
  12171. /**
  12172. * Returns a point as a proportion of this box's width, height and depth.
  12173. *
  12174. * @param {Vector3} point - A point in 3D space.
  12175. * @param {Vector3} target - The target vector that is used to store the method's result.
  12176. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  12177. */
  12178. getParameter( point, target ) {
  12179. // This can potentially have a divide by zero if the box
  12180. // has a size dimension of 0.
  12181. return target.set(
  12182. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  12183. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  12184. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  12185. );
  12186. }
  12187. /**
  12188. * Returns `true` if the given bounding box intersects with this bounding box.
  12189. *
  12190. * @param {Box3} box - The bounding box to test.
  12191. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  12192. */
  12193. intersectsBox( box ) {
  12194. // using 6 splitting planes to rule out intersections.
  12195. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  12196. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  12197. box.max.z >= this.min.z && box.min.z <= this.max.z;
  12198. }
  12199. /**
  12200. * Returns `true` if the given bounding sphere intersects with this bounding box.
  12201. *
  12202. * @param {Sphere} sphere - The bounding sphere to test.
  12203. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  12204. */
  12205. intersectsSphere( sphere ) {
  12206. // Find the point on the AABB closest to the sphere center.
  12207. this.clampPoint( sphere.center, _vector$b );
  12208. // If that point is inside the sphere, the AABB and sphere intersect.
  12209. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  12210. }
  12211. /**
  12212. * Returns `true` if the given plane intersects with this bounding box.
  12213. *
  12214. * @param {Plane} plane - The plane to test.
  12215. * @return {boolean} Whether the given plane intersects with this bounding box.
  12216. */
  12217. intersectsPlane( plane ) {
  12218. // We compute the minimum and maximum dot product values. If those values
  12219. // are on the same side (back or front) of the plane, then there is no intersection.
  12220. let min, max;
  12221. if ( plane.normal.x > 0 ) {
  12222. min = plane.normal.x * this.min.x;
  12223. max = plane.normal.x * this.max.x;
  12224. } else {
  12225. min = plane.normal.x * this.max.x;
  12226. max = plane.normal.x * this.min.x;
  12227. }
  12228. if ( plane.normal.y > 0 ) {
  12229. min += plane.normal.y * this.min.y;
  12230. max += plane.normal.y * this.max.y;
  12231. } else {
  12232. min += plane.normal.y * this.max.y;
  12233. max += plane.normal.y * this.min.y;
  12234. }
  12235. if ( plane.normal.z > 0 ) {
  12236. min += plane.normal.z * this.min.z;
  12237. max += plane.normal.z * this.max.z;
  12238. } else {
  12239. min += plane.normal.z * this.max.z;
  12240. max += plane.normal.z * this.min.z;
  12241. }
  12242. return ( min <= - plane.constant && max >= - plane.constant );
  12243. }
  12244. /**
  12245. * Returns `true` if the given triangle intersects with this bounding box.
  12246. *
  12247. * @param {Triangle} triangle - The triangle to test.
  12248. * @return {boolean} Whether the given triangle intersects with this bounding box.
  12249. */
  12250. intersectsTriangle( triangle ) {
  12251. if ( this.isEmpty() ) {
  12252. return false;
  12253. }
  12254. // compute box center and extents
  12255. this.getCenter( _center );
  12256. _extents.subVectors( this.max, _center );
  12257. // translate triangle to aabb origin
  12258. _v0$1.subVectors( triangle.a, _center );
  12259. _v1$4.subVectors( triangle.b, _center );
  12260. _v2$3.subVectors( triangle.c, _center );
  12261. // compute edge vectors for triangle
  12262. _f0.subVectors( _v1$4, _v0$1 );
  12263. _f1.subVectors( _v2$3, _v1$4 );
  12264. _f2.subVectors( _v0$1, _v2$3 );
  12265. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  12266. // 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
  12267. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  12268. let axes = [
  12269. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  12270. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  12271. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  12272. ];
  12273. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12274. return false;
  12275. }
  12276. // test 3 face normals from the aabb
  12277. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  12278. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12279. return false;
  12280. }
  12281. // finally testing the face normal of the triangle
  12282. // use already existing triangle edge vectors here
  12283. _triangleNormal.crossVectors( _f0, _f1 );
  12284. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  12285. return satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents );
  12286. }
  12287. /**
  12288. * Clamps the given point within the bounds of this box.
  12289. *
  12290. * @param {Vector3} point - The point to clamp.
  12291. * @param {Vector3} target - The target vector that is used to store the method's result.
  12292. * @return {Vector3} The clamped point.
  12293. */
  12294. clampPoint( point, target ) {
  12295. return target.copy( point ).clamp( this.min, this.max );
  12296. }
  12297. /**
  12298. * Returns the euclidean distance from any edge of this box to the specified point. If
  12299. * the given point lies inside of this box, the distance will be `0`.
  12300. *
  12301. * @param {Vector3} point - The point to compute the distance to.
  12302. * @return {number} The euclidean distance.
  12303. */
  12304. distanceToPoint( point ) {
  12305. return this.clampPoint( point, _vector$b ).distanceTo( point );
  12306. }
  12307. /**
  12308. * Returns a bounding sphere that encloses this bounding box.
  12309. *
  12310. * @param {Sphere} target - The target sphere that is used to store the method's result.
  12311. * @return {Sphere} The bounding sphere that encloses this bounding box.
  12312. */
  12313. getBoundingSphere( target ) {
  12314. if ( this.isEmpty() ) {
  12315. target.makeEmpty();
  12316. } else {
  12317. this.getCenter( target.center );
  12318. target.radius = this.getSize( _vector$b ).length() * 0.5;
  12319. }
  12320. return target;
  12321. }
  12322. /**
  12323. * Computes the intersection of this bounding box and the given one, setting the upper
  12324. * bound of this box to the lesser of the two boxes' upper bounds and the
  12325. * lower bound of this box to the greater of the two boxes' lower bounds. If
  12326. * there's no overlap, makes this box empty.
  12327. *
  12328. * @param {Box3} box - The bounding box to intersect with.
  12329. * @return {Box3} A reference to this bounding box.
  12330. */
  12331. intersect( box ) {
  12332. this.min.max( box.min );
  12333. this.max.min( box.max );
  12334. // 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.
  12335. if ( this.isEmpty() ) this.makeEmpty();
  12336. return this;
  12337. }
  12338. /**
  12339. * Computes the union of this box and another and the given one, setting the upper
  12340. * bound of this box to the greater of the two boxes' upper bounds and the
  12341. * lower bound of this box to the lesser of the two boxes' lower bounds.
  12342. *
  12343. * @param {Box3} box - The bounding box that will be unioned with this instance.
  12344. * @return {Box3} A reference to this bounding box.
  12345. */
  12346. union( box ) {
  12347. this.min.min( box.min );
  12348. this.max.max( box.max );
  12349. return this;
  12350. }
  12351. /**
  12352. * Transforms this bounding box by the given 4x4 transformation matrix.
  12353. *
  12354. * @param {Matrix4} matrix - The transformation matrix.
  12355. * @return {Box3} A reference to this bounding box.
  12356. */
  12357. applyMatrix4( matrix ) {
  12358. // transform of empty box is an empty box.
  12359. if ( this.isEmpty() ) return this;
  12360. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  12361. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  12362. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  12363. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  12364. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  12365. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  12366. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  12367. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  12368. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  12369. this.setFromPoints( _points );
  12370. return this;
  12371. }
  12372. /**
  12373. * Adds the given offset to both the upper and lower bounds of this bounding box,
  12374. * effectively moving it in 3D space.
  12375. *
  12376. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  12377. * @return {Box3} A reference to this bounding box.
  12378. */
  12379. translate( offset ) {
  12380. this.min.add( offset );
  12381. this.max.add( offset );
  12382. return this;
  12383. }
  12384. /**
  12385. * Returns `true` if this bounding box is equal with the given one.
  12386. *
  12387. * @param {Box3} box - The box to test for equality.
  12388. * @return {boolean} Whether this bounding box is equal with the given one.
  12389. */
  12390. equals( box ) {
  12391. return box.min.equals( this.min ) && box.max.equals( this.max );
  12392. }
  12393. /**
  12394. * Returns a serialized structure of the bounding box.
  12395. *
  12396. * @return {Object} Serialized structure with fields representing the object state.
  12397. */
  12398. toJSON() {
  12399. return {
  12400. min: this.min.toArray(),
  12401. max: this.max.toArray()
  12402. };
  12403. }
  12404. /**
  12405. * Returns a serialized structure of the bounding box.
  12406. *
  12407. * @param {Object} json - The serialized json to set the box from.
  12408. * @return {Box3} A reference to this bounding box.
  12409. */
  12410. fromJSON( json ) {
  12411. this.min.fromArray( json.min );
  12412. this.max.fromArray( json.max );
  12413. return this;
  12414. }
  12415. }
  12416. const _points = [
  12417. /*@__PURE__*/ new Vector3(),
  12418. /*@__PURE__*/ new Vector3(),
  12419. /*@__PURE__*/ new Vector3(),
  12420. /*@__PURE__*/ new Vector3(),
  12421. /*@__PURE__*/ new Vector3(),
  12422. /*@__PURE__*/ new Vector3(),
  12423. /*@__PURE__*/ new Vector3(),
  12424. /*@__PURE__*/ new Vector3()
  12425. ];
  12426. const _vector$b = /*@__PURE__*/ new Vector3();
  12427. const _box$4 = /*@__PURE__*/ new Box3();
  12428. // triangle centered vertices
  12429. const _v0$1 = /*@__PURE__*/ new Vector3();
  12430. const _v1$4 = /*@__PURE__*/ new Vector3();
  12431. const _v2$3 = /*@__PURE__*/ new Vector3();
  12432. // triangle edge vectors
  12433. const _f0 = /*@__PURE__*/ new Vector3();
  12434. const _f1 = /*@__PURE__*/ new Vector3();
  12435. const _f2 = /*@__PURE__*/ new Vector3();
  12436. const _center = /*@__PURE__*/ new Vector3();
  12437. const _extents = /*@__PURE__*/ new Vector3();
  12438. const _triangleNormal = /*@__PURE__*/ new Vector3();
  12439. const _testAxis = /*@__PURE__*/ new Vector3();
  12440. function satForAxes( axes, v0, v1, v2, extents ) {
  12441. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  12442. _testAxis.fromArray( axes, i );
  12443. // project the aabb onto the separating axis
  12444. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  12445. // project all 3 vertices of the triangle onto the separating axis
  12446. const p0 = v0.dot( _testAxis );
  12447. const p1 = v1.dot( _testAxis );
  12448. const p2 = v2.dot( _testAxis );
  12449. // actual test, basically see if either of the most extreme of the triangle points intersects r
  12450. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  12451. // points of the projected triangle are outside the projected half-length of the aabb
  12452. // the axis is separating and we can exit
  12453. return false;
  12454. }
  12455. }
  12456. return true;
  12457. }
  12458. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  12459. const _tables = /*@__PURE__*/ _generateTables();
  12460. function _generateTables() {
  12461. // float32 to float16 helpers
  12462. const buffer = new ArrayBuffer( 4 );
  12463. const floatView = new Float32Array( buffer );
  12464. const uint32View = new Uint32Array( buffer );
  12465. const baseTable = new Uint32Array( 512 );
  12466. const shiftTable = new Uint32Array( 512 );
  12467. for ( let i = 0; i < 256; ++ i ) {
  12468. const e = i - 127;
  12469. // very small number (0, -0)
  12470. if ( e < -27 ) {
  12471. baseTable[ i ] = 0x0000;
  12472. baseTable[ i | 0x100 ] = 0x8000;
  12473. shiftTable[ i ] = 24;
  12474. shiftTable[ i | 0x100 ] = 24;
  12475. // small number (denorm)
  12476. } else if ( e < -14 ) {
  12477. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  12478. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  12479. shiftTable[ i ] = - e - 1;
  12480. shiftTable[ i | 0x100 ] = - e - 1;
  12481. // normal number
  12482. } else if ( e <= 15 ) {
  12483. baseTable[ i ] = ( e + 15 ) << 10;
  12484. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  12485. shiftTable[ i ] = 13;
  12486. shiftTable[ i | 0x100 ] = 13;
  12487. // large number (Infinity, -Infinity)
  12488. } else if ( e < 128 ) {
  12489. baseTable[ i ] = 0x7c00;
  12490. baseTable[ i | 0x100 ] = 0xfc00;
  12491. shiftTable[ i ] = 24;
  12492. shiftTable[ i | 0x100 ] = 24;
  12493. // stay (NaN, Infinity, -Infinity)
  12494. } else {
  12495. baseTable[ i ] = 0x7c00;
  12496. baseTable[ i | 0x100 ] = 0xfc00;
  12497. shiftTable[ i ] = 13;
  12498. shiftTable[ i | 0x100 ] = 13;
  12499. }
  12500. }
  12501. // float16 to float32 helpers
  12502. const mantissaTable = new Uint32Array( 2048 );
  12503. const exponentTable = new Uint32Array( 64 );
  12504. const offsetTable = new Uint32Array( 64 );
  12505. for ( let i = 1; i < 1024; ++ i ) {
  12506. let m = i << 13; // zero pad mantissa bits
  12507. let e = 0; // zero exponent
  12508. // normalized
  12509. while ( ( m & 0x00800000 ) === 0 ) {
  12510. m <<= 1;
  12511. e -= 0x00800000; // decrement exponent
  12512. }
  12513. m &= -8388609; // clear leading 1 bit
  12514. e += 0x38800000; // adjust bias
  12515. mantissaTable[ i ] = m | e;
  12516. }
  12517. for ( let i = 1024; i < 2048; ++ i ) {
  12518. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  12519. }
  12520. for ( let i = 1; i < 31; ++ i ) {
  12521. exponentTable[ i ] = i << 23;
  12522. }
  12523. exponentTable[ 31 ] = 0x47800000;
  12524. exponentTable[ 32 ] = 0x80000000;
  12525. for ( let i = 33; i < 63; ++ i ) {
  12526. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  12527. }
  12528. exponentTable[ 63 ] = 0xc7800000;
  12529. for ( let i = 1; i < 64; ++ i ) {
  12530. if ( i !== 32 ) {
  12531. offsetTable[ i ] = 1024;
  12532. }
  12533. }
  12534. return {
  12535. floatView: floatView,
  12536. uint32View: uint32View,
  12537. baseTable: baseTable,
  12538. shiftTable: shiftTable,
  12539. mantissaTable: mantissaTable,
  12540. exponentTable: exponentTable,
  12541. offsetTable: offsetTable
  12542. };
  12543. }
  12544. /**
  12545. * Returns a half precision floating point value (FP16) from the given single
  12546. * precision floating point value (FP32).
  12547. *
  12548. * @param {number} val - A single precision floating point value.
  12549. * @return {number} The FP16 value.
  12550. */
  12551. function toHalfFloat( val ) {
  12552. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  12553. val = clamp( val, -65504, 65504 );
  12554. _tables.floatView[ 0 ] = val;
  12555. const f = _tables.uint32View[ 0 ];
  12556. const e = ( f >> 23 ) & 0x1ff;
  12557. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  12558. }
  12559. /**
  12560. * Returns a single precision floating point value (FP32) from the given half
  12561. * precision floating point value (FP16).
  12562. *
  12563. * @param {number} val - A half precision floating point value.
  12564. * @return {number} The FP32 value.
  12565. */
  12566. function fromHalfFloat( val ) {
  12567. const m = val >> 10;
  12568. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  12569. return _tables.floatView[ 0 ];
  12570. }
  12571. /**
  12572. * A class containing utility functions for data.
  12573. *
  12574. * @hideconstructor
  12575. */
  12576. class DataUtils {
  12577. /**
  12578. * Returns a half precision floating point value (FP16) from the given single
  12579. * precision floating point value (FP32).
  12580. *
  12581. * @param {number} val - A single precision floating point value.
  12582. * @return {number} The FP16 value.
  12583. */
  12584. static toHalfFloat( val ) {
  12585. return toHalfFloat( val );
  12586. }
  12587. /**
  12588. * Returns a single precision floating point value (FP32) from the given half
  12589. * precision floating point value (FP16).
  12590. *
  12591. * @param {number} val - A half precision floating point value.
  12592. * @return {number} The FP32 value.
  12593. */
  12594. static fromHalfFloat( val ) {
  12595. return fromHalfFloat( val );
  12596. }
  12597. }
  12598. const _vector$a = /*@__PURE__*/ new Vector3();
  12599. const _vector2$1 = /*@__PURE__*/ new Vector2();
  12600. let _id$2 = 0;
  12601. /**
  12602. * This class stores data for an attribute (such as vertex positions, face
  12603. * indices, normals, colors, UVs, and any custom attributes ) associated with
  12604. * a geometry, which allows for more efficient passing of data to the GPU.
  12605. *
  12606. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  12607. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  12608. */
  12609. class BufferAttribute extends EventDispatcher {
  12610. /**
  12611. * Constructs a new buffer attribute.
  12612. *
  12613. * @param {TypedArray} array - The array holding the attribute data.
  12614. * @param {number} itemSize - The item size.
  12615. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  12616. */
  12617. constructor( array, itemSize, normalized = false ) {
  12618. super();
  12619. if ( Array.isArray( array ) ) {
  12620. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12621. }
  12622. /**
  12623. * This flag can be used for type testing.
  12624. *
  12625. * @type {boolean}
  12626. * @readonly
  12627. * @default true
  12628. */
  12629. this.isBufferAttribute = true;
  12630. /**
  12631. * The ID of the buffer attribute.
  12632. *
  12633. * @name BufferAttribute#id
  12634. * @type {number}
  12635. * @readonly
  12636. */
  12637. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  12638. /**
  12639. * The name of the buffer attribute.
  12640. *
  12641. * @type {string}
  12642. */
  12643. this.name = '';
  12644. /**
  12645. * The array holding the attribute data. It should have `itemSize * numVertices`
  12646. * elements, where `numVertices` is the number of vertices in the associated geometry.
  12647. *
  12648. * @type {TypedArray}
  12649. */
  12650. this.array = array;
  12651. /**
  12652. * The number of values of the array that should be associated with a particular vertex.
  12653. * For instance, if this attribute is storing a 3-component vector (such as a position,
  12654. * normal, or color), then the value should be `3`.
  12655. *
  12656. * @type {number}
  12657. */
  12658. this.itemSize = itemSize;
  12659. /**
  12660. * Represents the number of items this buffer attribute stores. It is internally computed
  12661. * by dividing the `array` length by the `itemSize`.
  12662. *
  12663. * @type {number}
  12664. * @readonly
  12665. */
  12666. this.count = array !== undefined ? array.length / itemSize : 0;
  12667. /**
  12668. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  12669. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  12670. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  12671. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  12672. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  12673. *
  12674. * @type {boolean}
  12675. */
  12676. this.normalized = normalized;
  12677. /**
  12678. * Defines the intended usage pattern of the data store for optimization purposes.
  12679. *
  12680. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  12681. * instantiate a new one and set the desired usage before the next render.
  12682. *
  12683. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  12684. * @default StaticDrawUsage
  12685. */
  12686. this.usage = StaticDrawUsage;
  12687. /**
  12688. * This can be used to only update some components of stored vectors (for example, just the
  12689. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  12690. *
  12691. * @type {Array<Object>}
  12692. */
  12693. this.updateRanges = [];
  12694. /**
  12695. * Configures the bound GPU type for use in shaders.
  12696. *
  12697. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  12698. * For lower precision float types, use `Float16BufferAttribute`.
  12699. *
  12700. * @type {(FloatType|IntType)}
  12701. * @default FloatType
  12702. */
  12703. this.gpuType = FloatType;
  12704. /**
  12705. * A version number, incremented every time the `needsUpdate` is set to `true`.
  12706. *
  12707. * @type {number}
  12708. */
  12709. this.version = 0;
  12710. }
  12711. /**
  12712. * A callback function that is executed after the renderer has transferred the attribute
  12713. * array data to the GPU.
  12714. */
  12715. onUploadCallback() {}
  12716. /**
  12717. * Flag to indicate that this attribute has changed and should be re-sent to
  12718. * the GPU. Set this to `true` when you modify the value of the array.
  12719. *
  12720. * @type {number}
  12721. * @default false
  12722. * @param {boolean} value
  12723. */
  12724. set needsUpdate( value ) {
  12725. if ( value === true ) this.version ++;
  12726. }
  12727. /**
  12728. * Sets the usage of this buffer attribute.
  12729. *
  12730. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  12731. * @return {BufferAttribute} A reference to this buffer attribute.
  12732. */
  12733. setUsage( value ) {
  12734. this.usage = value;
  12735. return this;
  12736. }
  12737. /**
  12738. * Adds a range of data in the data array to be updated on the GPU.
  12739. *
  12740. * @param {number} start - Position at which to start update.
  12741. * @param {number} count - The number of components to update.
  12742. */
  12743. addUpdateRange( start, count ) {
  12744. this.updateRanges.push( { start, count } );
  12745. }
  12746. /**
  12747. * Clears the update ranges.
  12748. */
  12749. clearUpdateRanges() {
  12750. this.updateRanges.length = 0;
  12751. }
  12752. /**
  12753. * Copies the values of the given buffer attribute to this instance.
  12754. *
  12755. * @param {BufferAttribute} source - The buffer attribute to copy.
  12756. * @return {BufferAttribute} A reference to this instance.
  12757. */
  12758. copy( source ) {
  12759. this.name = source.name;
  12760. this.array = new source.array.constructor( source.array );
  12761. this.itemSize = source.itemSize;
  12762. this.count = source.count;
  12763. this.normalized = source.normalized;
  12764. this.usage = source.usage;
  12765. this.gpuType = source.gpuType;
  12766. return this;
  12767. }
  12768. /**
  12769. * Copies a vector from the given buffer attribute to this one. The start
  12770. * and destination position in the attribute buffers are represented by the
  12771. * given indices.
  12772. *
  12773. * @param {number} index1 - The destination index into this buffer attribute.
  12774. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  12775. * @param {number} index2 - The source index into the given buffer attribute.
  12776. * @return {BufferAttribute} A reference to this instance.
  12777. */
  12778. copyAt( index1, attribute, index2 ) {
  12779. index1 *= this.itemSize;
  12780. index2 *= attribute.itemSize;
  12781. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  12782. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  12783. }
  12784. return this;
  12785. }
  12786. /**
  12787. * Copies the given array data into this buffer attribute.
  12788. *
  12789. * @param {(TypedArray|Array)} array - The array to copy.
  12790. * @return {BufferAttribute} A reference to this instance.
  12791. */
  12792. copyArray( array ) {
  12793. this.array.set( array );
  12794. return this;
  12795. }
  12796. /**
  12797. * Applies the given 3x3 matrix to the given attribute. Works with
  12798. * item size `2` and `3`.
  12799. *
  12800. * @param {Matrix3} m - The matrix to apply.
  12801. * @return {BufferAttribute} A reference to this instance.
  12802. */
  12803. applyMatrix3( m ) {
  12804. if ( this.itemSize === 2 ) {
  12805. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12806. _vector2$1.fromBufferAttribute( this, i );
  12807. _vector2$1.applyMatrix3( m );
  12808. this.setXY( i, _vector2$1.x, _vector2$1.y );
  12809. }
  12810. } else if ( this.itemSize === 3 ) {
  12811. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12812. _vector$a.fromBufferAttribute( this, i );
  12813. _vector$a.applyMatrix3( m );
  12814. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12815. }
  12816. }
  12817. return this;
  12818. }
  12819. /**
  12820. * Applies the given 4x4 matrix to the given attribute. Only works with
  12821. * item size `3`.
  12822. *
  12823. * @param {Matrix4} m - The matrix to apply.
  12824. * @return {BufferAttribute} A reference to this instance.
  12825. */
  12826. applyMatrix4( m ) {
  12827. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12828. _vector$a.fromBufferAttribute( this, i );
  12829. _vector$a.applyMatrix4( m );
  12830. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12831. }
  12832. return this;
  12833. }
  12834. /**
  12835. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  12836. * item size `3`.
  12837. *
  12838. * @param {Matrix3} m - The normal matrix to apply.
  12839. * @return {BufferAttribute} A reference to this instance.
  12840. */
  12841. applyNormalMatrix( m ) {
  12842. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12843. _vector$a.fromBufferAttribute( this, i );
  12844. _vector$a.applyNormalMatrix( m );
  12845. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12846. }
  12847. return this;
  12848. }
  12849. /**
  12850. * Applies the given 4x4 matrix to the given attribute. Only works with
  12851. * item size `3` and with direction vectors.
  12852. *
  12853. * @param {Matrix4} m - The matrix to apply.
  12854. * @return {BufferAttribute} A reference to this instance.
  12855. */
  12856. transformDirection( m ) {
  12857. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12858. _vector$a.fromBufferAttribute( this, i );
  12859. _vector$a.transformDirection( m );
  12860. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12861. }
  12862. return this;
  12863. }
  12864. /**
  12865. * Sets the given array data in the buffer attribute.
  12866. *
  12867. * @param {(TypedArray|Array)} value - The array data to set.
  12868. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  12869. * @return {BufferAttribute} A reference to this instance.
  12870. */
  12871. set( value, offset = 0 ) {
  12872. // Matching BufferAttribute constructor, do not normalize the array.
  12873. this.array.set( value, offset );
  12874. return this;
  12875. }
  12876. /**
  12877. * Returns the given component of the vector at the given index.
  12878. *
  12879. * @param {number} index - The index into the buffer attribute.
  12880. * @param {number} component - The component index.
  12881. * @return {number} The returned value.
  12882. */
  12883. getComponent( index, component ) {
  12884. let value = this.array[ index * this.itemSize + component ];
  12885. if ( this.normalized ) value = denormalize( value, this.array );
  12886. return value;
  12887. }
  12888. /**
  12889. * Sets the given value to the given component of the vector at the given index.
  12890. *
  12891. * @param {number} index - The index into the buffer attribute.
  12892. * @param {number} component - The component index.
  12893. * @param {number} value - The value to set.
  12894. * @return {BufferAttribute} A reference to this instance.
  12895. */
  12896. setComponent( index, component, value ) {
  12897. if ( this.normalized ) value = normalize( value, this.array );
  12898. this.array[ index * this.itemSize + component ] = value;
  12899. return this;
  12900. }
  12901. /**
  12902. * Returns the x component of the vector at the given index.
  12903. *
  12904. * @param {number} index - The index into the buffer attribute.
  12905. * @return {number} The x component.
  12906. */
  12907. getX( index ) {
  12908. let x = this.array[ index * this.itemSize ];
  12909. if ( this.normalized ) x = denormalize( x, this.array );
  12910. return x;
  12911. }
  12912. /**
  12913. * Sets the x component of the vector at the given index.
  12914. *
  12915. * @param {number} index - The index into the buffer attribute.
  12916. * @param {number} x - The value to set.
  12917. * @return {BufferAttribute} A reference to this instance.
  12918. */
  12919. setX( index, x ) {
  12920. if ( this.normalized ) x = normalize( x, this.array );
  12921. this.array[ index * this.itemSize ] = x;
  12922. return this;
  12923. }
  12924. /**
  12925. * Returns the y component of the vector at the given index.
  12926. *
  12927. * @param {number} index - The index into the buffer attribute.
  12928. * @return {number} The y component.
  12929. */
  12930. getY( index ) {
  12931. let y = this.array[ index * this.itemSize + 1 ];
  12932. if ( this.normalized ) y = denormalize( y, this.array );
  12933. return y;
  12934. }
  12935. /**
  12936. * Sets the y component of the vector at the given index.
  12937. *
  12938. * @param {number} index - The index into the buffer attribute.
  12939. * @param {number} y - The value to set.
  12940. * @return {BufferAttribute} A reference to this instance.
  12941. */
  12942. setY( index, y ) {
  12943. if ( this.normalized ) y = normalize( y, this.array );
  12944. this.array[ index * this.itemSize + 1 ] = y;
  12945. return this;
  12946. }
  12947. /**
  12948. * Returns the z component of the vector at the given index.
  12949. *
  12950. * @param {number} index - The index into the buffer attribute.
  12951. * @return {number} The z component.
  12952. */
  12953. getZ( index ) {
  12954. let z = this.array[ index * this.itemSize + 2 ];
  12955. if ( this.normalized ) z = denormalize( z, this.array );
  12956. return z;
  12957. }
  12958. /**
  12959. * Sets the z component of the vector at the given index.
  12960. *
  12961. * @param {number} index - The index into the buffer attribute.
  12962. * @param {number} z - The value to set.
  12963. * @return {BufferAttribute} A reference to this instance.
  12964. */
  12965. setZ( index, z ) {
  12966. if ( this.normalized ) z = normalize( z, this.array );
  12967. this.array[ index * this.itemSize + 2 ] = z;
  12968. return this;
  12969. }
  12970. /**
  12971. * Returns the w component of the vector at the given index.
  12972. *
  12973. * @param {number} index - The index into the buffer attribute.
  12974. * @return {number} The w component.
  12975. */
  12976. getW( index ) {
  12977. let w = this.array[ index * this.itemSize + 3 ];
  12978. if ( this.normalized ) w = denormalize( w, this.array );
  12979. return w;
  12980. }
  12981. /**
  12982. * Sets the w component of the vector at the given index.
  12983. *
  12984. * @param {number} index - The index into the buffer attribute.
  12985. * @param {number} w - The value to set.
  12986. * @return {BufferAttribute} A reference to this instance.
  12987. */
  12988. setW( index, w ) {
  12989. if ( this.normalized ) w = normalize( w, this.array );
  12990. this.array[ index * this.itemSize + 3 ] = w;
  12991. return this;
  12992. }
  12993. /**
  12994. * Sets the x and y component of the vector at the given index.
  12995. *
  12996. * @param {number} index - The index into the buffer attribute.
  12997. * @param {number} x - The value for the x component to set.
  12998. * @param {number} y - The value for the y component to set.
  12999. * @return {BufferAttribute} A reference to this instance.
  13000. */
  13001. setXY( index, x, y ) {
  13002. index *= this.itemSize;
  13003. if ( this.normalized ) {
  13004. x = normalize( x, this.array );
  13005. y = normalize( y, this.array );
  13006. }
  13007. this.array[ index + 0 ] = x;
  13008. this.array[ index + 1 ] = y;
  13009. return this;
  13010. }
  13011. /**
  13012. * Sets the x, y and z component of the vector at the given index.
  13013. *
  13014. * @param {number} index - The index into the buffer attribute.
  13015. * @param {number} x - The value for the x component to set.
  13016. * @param {number} y - The value for the y component to set.
  13017. * @param {number} z - The value for the z component to set.
  13018. * @return {BufferAttribute} A reference to this instance.
  13019. */
  13020. setXYZ( index, x, y, z ) {
  13021. index *= this.itemSize;
  13022. if ( this.normalized ) {
  13023. x = normalize( x, this.array );
  13024. y = normalize( y, this.array );
  13025. z = normalize( z, this.array );
  13026. }
  13027. this.array[ index + 0 ] = x;
  13028. this.array[ index + 1 ] = y;
  13029. this.array[ index + 2 ] = z;
  13030. return this;
  13031. }
  13032. /**
  13033. * Sets the x, y, z and w component of the vector at the given index.
  13034. *
  13035. * @param {number} index - The index into the buffer attribute.
  13036. * @param {number} x - The value for the x component to set.
  13037. * @param {number} y - The value for the y component to set.
  13038. * @param {number} z - The value for the z component to set.
  13039. * @param {number} w - The value for the w component to set.
  13040. * @return {BufferAttribute} A reference to this instance.
  13041. */
  13042. setXYZW( index, x, y, z, w ) {
  13043. index *= this.itemSize;
  13044. if ( this.normalized ) {
  13045. x = normalize( x, this.array );
  13046. y = normalize( y, this.array );
  13047. z = normalize( z, this.array );
  13048. w = normalize( w, this.array );
  13049. }
  13050. this.array[ index + 0 ] = x;
  13051. this.array[ index + 1 ] = y;
  13052. this.array[ index + 2 ] = z;
  13053. this.array[ index + 3 ] = w;
  13054. return this;
  13055. }
  13056. /**
  13057. * Sets the given callback function that is executed after the Renderer has transferred
  13058. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13059. * the upload when attribute data are not needed anymore on the CPU side.
  13060. *
  13061. * @param {Function} callback - The `onUpload()` callback.
  13062. * @return {BufferAttribute} A reference to this instance.
  13063. */
  13064. onUpload( callback ) {
  13065. this.onUploadCallback = callback;
  13066. return this;
  13067. }
  13068. /**
  13069. * Returns a new buffer attribute with copied values from this instance.
  13070. *
  13071. * @return {BufferAttribute} A clone of this instance.
  13072. */
  13073. clone() {
  13074. return new this.constructor( this.array, this.itemSize ).copy( this );
  13075. }
  13076. /**
  13077. * Serializes the buffer attribute into JSON.
  13078. *
  13079. * @return {Object} A JSON object representing the serialized buffer attribute.
  13080. */
  13081. toJSON() {
  13082. const data = {
  13083. itemSize: this.itemSize,
  13084. type: this.array.constructor.name,
  13085. array: Array.from( this.array ),
  13086. normalized: this.normalized
  13087. };
  13088. if ( this.name !== '' ) data.name = this.name;
  13089. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13090. return data;
  13091. }
  13092. /**
  13093. * Disposes of the buffer attribute. Available only in {@link WebGPURenderer}.
  13094. */
  13095. dispose() {
  13096. this.dispatchEvent( { type: 'dispose' } );
  13097. }
  13098. }
  13099. /**
  13100. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13101. * a plain `Array` instance.
  13102. *
  13103. * @augments BufferAttribute
  13104. */
  13105. class Int8BufferAttribute extends BufferAttribute {
  13106. /**
  13107. * Constructs a new buffer attribute.
  13108. *
  13109. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13110. * @param {number} itemSize - The item size.
  13111. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13112. */
  13113. constructor( array, itemSize, normalized ) {
  13114. super( new Int8Array( array ), itemSize, normalized );
  13115. }
  13116. }
  13117. /**
  13118. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13119. * a plain `Array` instance.
  13120. *
  13121. * @augments BufferAttribute
  13122. */
  13123. class Uint8BufferAttribute extends BufferAttribute {
  13124. /**
  13125. * Constructs a new buffer attribute.
  13126. *
  13127. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13128. * @param {number} itemSize - The item size.
  13129. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13130. */
  13131. constructor( array, itemSize, normalized ) {
  13132. super( new Uint8Array( array ), itemSize, normalized );
  13133. }
  13134. }
  13135. /**
  13136. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13137. * a plain `Array` instance.
  13138. *
  13139. * @augments BufferAttribute
  13140. */
  13141. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13142. /**
  13143. * Constructs a new buffer attribute.
  13144. *
  13145. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13146. * @param {number} itemSize - The item size.
  13147. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13148. */
  13149. constructor( array, itemSize, normalized ) {
  13150. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13151. }
  13152. }
  13153. /**
  13154. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13155. * a plain `Array` instance.
  13156. *
  13157. * @augments BufferAttribute
  13158. */
  13159. class Int16BufferAttribute extends BufferAttribute {
  13160. /**
  13161. * Constructs a new buffer attribute.
  13162. *
  13163. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13164. * @param {number} itemSize - The item size.
  13165. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13166. */
  13167. constructor( array, itemSize, normalized ) {
  13168. super( new Int16Array( array ), itemSize, normalized );
  13169. }
  13170. }
  13171. /**
  13172. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13173. * a plain `Array` instance.
  13174. *
  13175. * @augments BufferAttribute
  13176. */
  13177. class Uint16BufferAttribute extends BufferAttribute {
  13178. /**
  13179. * Constructs a new buffer attribute.
  13180. *
  13181. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13182. * @param {number} itemSize - The item size.
  13183. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13184. */
  13185. constructor( array, itemSize, normalized ) {
  13186. super( new Uint16Array( array ), itemSize, normalized );
  13187. }
  13188. }
  13189. /**
  13190. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13191. * a plain `Array` instance.
  13192. *
  13193. * @augments BufferAttribute
  13194. */
  13195. class Int32BufferAttribute extends BufferAttribute {
  13196. /**
  13197. * Constructs a new buffer attribute.
  13198. *
  13199. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13200. * @param {number} itemSize - The item size.
  13201. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13202. */
  13203. constructor( array, itemSize, normalized ) {
  13204. super( new Int32Array( array ), itemSize, normalized );
  13205. }
  13206. }
  13207. /**
  13208. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13209. * a plain `Array` instance.
  13210. *
  13211. * @augments BufferAttribute
  13212. */
  13213. class Uint32BufferAttribute extends BufferAttribute {
  13214. /**
  13215. * Constructs a new buffer attribute.
  13216. *
  13217. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13218. * @param {number} itemSize - The item size.
  13219. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13220. */
  13221. constructor( array, itemSize, normalized ) {
  13222. super( new Uint32Array( array ), itemSize, normalized );
  13223. }
  13224. }
  13225. /**
  13226. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13227. * a plain `Array` instance.
  13228. *
  13229. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  13230. * browser support is still problematic.
  13231. *
  13232. * @augments BufferAttribute
  13233. */
  13234. class Float16BufferAttribute extends BufferAttribute {
  13235. /**
  13236. * Constructs a new buffer attribute.
  13237. *
  13238. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13239. * @param {number} itemSize - The item size.
  13240. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13241. */
  13242. constructor( array, itemSize, normalized ) {
  13243. super( new Uint16Array( array ), itemSize, normalized );
  13244. this.isFloat16BufferAttribute = true;
  13245. }
  13246. getX( index ) {
  13247. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  13248. if ( this.normalized ) x = denormalize( x, this.array );
  13249. return x;
  13250. }
  13251. setX( index, x ) {
  13252. if ( this.normalized ) x = normalize( x, this.array );
  13253. this.array[ index * this.itemSize ] = toHalfFloat( x );
  13254. return this;
  13255. }
  13256. getY( index ) {
  13257. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  13258. if ( this.normalized ) y = denormalize( y, this.array );
  13259. return y;
  13260. }
  13261. setY( index, y ) {
  13262. if ( this.normalized ) y = normalize( y, this.array );
  13263. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  13264. return this;
  13265. }
  13266. getZ( index ) {
  13267. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  13268. if ( this.normalized ) z = denormalize( z, this.array );
  13269. return z;
  13270. }
  13271. setZ( index, z ) {
  13272. if ( this.normalized ) z = normalize( z, this.array );
  13273. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  13274. return this;
  13275. }
  13276. getW( index ) {
  13277. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  13278. if ( this.normalized ) w = denormalize( w, this.array );
  13279. return w;
  13280. }
  13281. setW( index, w ) {
  13282. if ( this.normalized ) w = normalize( w, this.array );
  13283. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  13284. return this;
  13285. }
  13286. setXY( index, x, y ) {
  13287. index *= this.itemSize;
  13288. if ( this.normalized ) {
  13289. x = normalize( x, this.array );
  13290. y = normalize( y, this.array );
  13291. }
  13292. this.array[ index + 0 ] = toHalfFloat( x );
  13293. this.array[ index + 1 ] = toHalfFloat( y );
  13294. return this;
  13295. }
  13296. setXYZ( index, x, y, z ) {
  13297. index *= this.itemSize;
  13298. if ( this.normalized ) {
  13299. x = normalize( x, this.array );
  13300. y = normalize( y, this.array );
  13301. z = normalize( z, this.array );
  13302. }
  13303. this.array[ index + 0 ] = toHalfFloat( x );
  13304. this.array[ index + 1 ] = toHalfFloat( y );
  13305. this.array[ index + 2 ] = toHalfFloat( z );
  13306. return this;
  13307. }
  13308. setXYZW( index, x, y, z, w ) {
  13309. index *= this.itemSize;
  13310. if ( this.normalized ) {
  13311. x = normalize( x, this.array );
  13312. y = normalize( y, this.array );
  13313. z = normalize( z, this.array );
  13314. w = normalize( w, this.array );
  13315. }
  13316. this.array[ index + 0 ] = toHalfFloat( x );
  13317. this.array[ index + 1 ] = toHalfFloat( y );
  13318. this.array[ index + 2 ] = toHalfFloat( z );
  13319. this.array[ index + 3 ] = toHalfFloat( w );
  13320. return this;
  13321. }
  13322. }
  13323. /**
  13324. * Convenient class that can be used when creating a `Float32` buffer attribute with
  13325. * a plain `Array` instance.
  13326. *
  13327. * @augments BufferAttribute
  13328. */
  13329. class Float32BufferAttribute extends BufferAttribute {
  13330. /**
  13331. * Constructs a new buffer attribute.
  13332. *
  13333. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  13334. * @param {number} itemSize - The item size.
  13335. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13336. */
  13337. constructor( array, itemSize, normalized ) {
  13338. super( new Float32Array( array ), itemSize, normalized );
  13339. }
  13340. }
  13341. const _box$3 = /*@__PURE__*/ new Box3();
  13342. const _v1$3 = /*@__PURE__*/ new Vector3();
  13343. const _v2$2 = /*@__PURE__*/ new Vector3();
  13344. /**
  13345. * An analytical 3D sphere defined by a center and radius. This class is mainly
  13346. * used as a Bounding Sphere for 3D objects.
  13347. */
  13348. class Sphere {
  13349. /**
  13350. * Constructs a new sphere.
  13351. *
  13352. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  13353. * @param {number} [radius=-1] - The radius of the sphere.
  13354. */
  13355. constructor( center = new Vector3(), radius = -1 ) {
  13356. /**
  13357. * This flag can be used for type testing.
  13358. *
  13359. * @type {boolean}
  13360. * @readonly
  13361. * @default true
  13362. */
  13363. this.isSphere = true;
  13364. /**
  13365. * The center of the sphere
  13366. *
  13367. * @type {Vector3}
  13368. */
  13369. this.center = center;
  13370. /**
  13371. * The radius of the sphere.
  13372. *
  13373. * @type {number}
  13374. */
  13375. this.radius = radius;
  13376. }
  13377. /**
  13378. * Sets the sphere's components by copying the given values.
  13379. *
  13380. * @param {Vector3} center - The center.
  13381. * @param {number} radius - The radius.
  13382. * @return {Sphere} A reference to this sphere.
  13383. */
  13384. set( center, radius ) {
  13385. this.center.copy( center );
  13386. this.radius = radius;
  13387. return this;
  13388. }
  13389. /**
  13390. * Computes the minimum bounding sphere for list of points.
  13391. * If the optional center point is given, it is used as the sphere's
  13392. * center. Otherwise, the center of the axis-aligned bounding box
  13393. * encompassing the points is calculated.
  13394. *
  13395. * @param {Array<Vector3>} points - A list of points in 3D space.
  13396. * @param {Vector3} [optionalCenter] - The center of the sphere.
  13397. * @return {Sphere} A reference to this sphere.
  13398. */
  13399. setFromPoints( points, optionalCenter ) {
  13400. const center = this.center;
  13401. if ( optionalCenter !== undefined ) {
  13402. center.copy( optionalCenter );
  13403. } else {
  13404. _box$3.setFromPoints( points ).getCenter( center );
  13405. }
  13406. let maxRadiusSq = 0;
  13407. for ( let i = 0, il = points.length; i < il; i ++ ) {
  13408. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  13409. }
  13410. this.radius = Math.sqrt( maxRadiusSq );
  13411. return this;
  13412. }
  13413. /**
  13414. * Copies the values of the given sphere to this instance.
  13415. *
  13416. * @param {Sphere} sphere - The sphere to copy.
  13417. * @return {Sphere} A reference to this sphere.
  13418. */
  13419. copy( sphere ) {
  13420. this.center.copy( sphere.center );
  13421. this.radius = sphere.radius;
  13422. return this;
  13423. }
  13424. /**
  13425. * Returns `true` if the sphere is empty (the radius set to a negative number).
  13426. *
  13427. * Spheres with a radius of `0` contain only their center point and are not
  13428. * considered to be empty.
  13429. *
  13430. * @return {boolean} Whether this sphere is empty or not.
  13431. */
  13432. isEmpty() {
  13433. return ( this.radius < 0 );
  13434. }
  13435. /**
  13436. * Makes this sphere empty which means in encloses a zero space in 3D.
  13437. *
  13438. * @return {Sphere} A reference to this sphere.
  13439. */
  13440. makeEmpty() {
  13441. this.center.set( 0, 0, 0 );
  13442. this.radius = -1;
  13443. return this;
  13444. }
  13445. /**
  13446. * Returns `true` if this sphere contains the given point inclusive of
  13447. * the surface of the sphere.
  13448. *
  13449. * @param {Vector3} point - The point to check.
  13450. * @return {boolean} Whether this sphere contains the given point or not.
  13451. */
  13452. containsPoint( point ) {
  13453. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  13454. }
  13455. /**
  13456. * Returns the closest distance from the boundary of the sphere to the
  13457. * given point. If the sphere contains the point, the distance will
  13458. * be negative.
  13459. *
  13460. * @param {Vector3} point - The point to compute the distance to.
  13461. * @return {number} The distance to the point.
  13462. */
  13463. distanceToPoint( point ) {
  13464. return ( point.distanceTo( this.center ) - this.radius );
  13465. }
  13466. /**
  13467. * Returns `true` if this sphere intersects with the given one.
  13468. *
  13469. * @param {Sphere} sphere - The sphere to test.
  13470. * @return {boolean} Whether this sphere intersects with the given one or not.
  13471. */
  13472. intersectsSphere( sphere ) {
  13473. const radiusSum = this.radius + sphere.radius;
  13474. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  13475. }
  13476. /**
  13477. * Returns `true` if this sphere intersects with the given box.
  13478. *
  13479. * @param {Box3} box - The box to test.
  13480. * @return {boolean} Whether this sphere intersects with the given box or not.
  13481. */
  13482. intersectsBox( box ) {
  13483. return box.intersectsSphere( this );
  13484. }
  13485. /**
  13486. * Returns `true` if this sphere intersects with the given plane.
  13487. *
  13488. * @param {Plane} plane - The plane to test.
  13489. * @return {boolean} Whether this sphere intersects with the given plane or not.
  13490. */
  13491. intersectsPlane( plane ) {
  13492. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  13493. }
  13494. /**
  13495. * Clamps a point within the sphere. If the point is outside the sphere, it
  13496. * will clamp it to the closest point on the edge of the sphere. Points
  13497. * already inside the sphere will not be affected.
  13498. *
  13499. * @param {Vector3} point - The plane to clamp.
  13500. * @param {Vector3} target - The target vector that is used to store the method's result.
  13501. * @return {Vector3} The clamped point.
  13502. */
  13503. clampPoint( point, target ) {
  13504. const deltaLengthSq = this.center.distanceToSquared( point );
  13505. target.copy( point );
  13506. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  13507. target.sub( this.center ).normalize();
  13508. target.multiplyScalar( this.radius ).add( this.center );
  13509. }
  13510. return target;
  13511. }
  13512. /**
  13513. * Returns a bounding box that encloses this sphere.
  13514. *
  13515. * @param {Box3} target - The target box that is used to store the method's result.
  13516. * @return {Box3} The bounding box that encloses this sphere.
  13517. */
  13518. getBoundingBox( target ) {
  13519. if ( this.isEmpty() ) {
  13520. // Empty sphere produces empty bounding box
  13521. target.makeEmpty();
  13522. return target;
  13523. }
  13524. target.set( this.center, this.center );
  13525. target.expandByScalar( this.radius );
  13526. return target;
  13527. }
  13528. /**
  13529. * Transforms this sphere with the given 4x4 transformation matrix.
  13530. *
  13531. * @param {Matrix4} matrix - The transformation matrix.
  13532. * @return {Sphere} A reference to this sphere.
  13533. */
  13534. applyMatrix4( matrix ) {
  13535. this.center.applyMatrix4( matrix );
  13536. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  13537. return this;
  13538. }
  13539. /**
  13540. * Translates the sphere's center by the given offset.
  13541. *
  13542. * @param {Vector3} offset - The offset.
  13543. * @return {Sphere} A reference to this sphere.
  13544. */
  13545. translate( offset ) {
  13546. this.center.add( offset );
  13547. return this;
  13548. }
  13549. /**
  13550. * Expands the boundaries of this sphere to include the given point.
  13551. *
  13552. * @param {Vector3} point - The point to include.
  13553. * @return {Sphere} A reference to this sphere.
  13554. */
  13555. expandByPoint( point ) {
  13556. if ( this.isEmpty() ) {
  13557. this.center.copy( point );
  13558. this.radius = 0;
  13559. return this;
  13560. }
  13561. _v1$3.subVectors( point, this.center );
  13562. const lengthSq = _v1$3.lengthSq();
  13563. if ( lengthSq > ( this.radius * this.radius ) ) {
  13564. // calculate the minimal sphere
  13565. const length = Math.sqrt( lengthSq );
  13566. const delta = ( length - this.radius ) * 0.5;
  13567. this.center.addScaledVector( _v1$3, delta / length );
  13568. this.radius += delta;
  13569. }
  13570. return this;
  13571. }
  13572. /**
  13573. * Expands this sphere to enclose both the original sphere and the given sphere.
  13574. *
  13575. * @param {Sphere} sphere - The sphere to include.
  13576. * @return {Sphere} A reference to this sphere.
  13577. */
  13578. union( sphere ) {
  13579. if ( sphere.isEmpty() ) {
  13580. return this;
  13581. }
  13582. if ( this.isEmpty() ) {
  13583. this.copy( sphere );
  13584. return this;
  13585. }
  13586. if ( this.center.equals( sphere.center ) === true ) {
  13587. this.radius = Math.max( this.radius, sphere.radius );
  13588. } else {
  13589. _v2$2.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  13590. this.expandByPoint( _v1$3.copy( sphere.center ).add( _v2$2 ) );
  13591. this.expandByPoint( _v1$3.copy( sphere.center ).sub( _v2$2 ) );
  13592. }
  13593. return this;
  13594. }
  13595. /**
  13596. * Returns `true` if this sphere is equal with the given one.
  13597. *
  13598. * @param {Sphere} sphere - The sphere to test for equality.
  13599. * @return {boolean} Whether this bounding sphere is equal with the given one.
  13600. */
  13601. equals( sphere ) {
  13602. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  13603. }
  13604. /**
  13605. * Returns a new sphere with copied values from this instance.
  13606. *
  13607. * @return {Sphere} A clone of this instance.
  13608. */
  13609. clone() {
  13610. return new this.constructor().copy( this );
  13611. }
  13612. /**
  13613. * Returns a serialized structure of the bounding sphere.
  13614. *
  13615. * @return {Object} Serialized structure with fields representing the object state.
  13616. */
  13617. toJSON() {
  13618. return {
  13619. radius: this.radius,
  13620. center: this.center.toArray()
  13621. };
  13622. }
  13623. /**
  13624. * Returns a serialized structure of the bounding sphere.
  13625. *
  13626. * @param {Object} json - The serialized json to set the sphere from.
  13627. * @return {Sphere} A reference to this bounding sphere.
  13628. */
  13629. fromJSON( json ) {
  13630. this.radius = json.radius;
  13631. this.center.fromArray( json.center );
  13632. return this;
  13633. }
  13634. }
  13635. let _id$1 = 0;
  13636. const _m1 = /*@__PURE__*/ new Matrix4();
  13637. const _obj = /*@__PURE__*/ new Object3D();
  13638. const _offset = /*@__PURE__*/ new Vector3();
  13639. const _box$2 = /*@__PURE__*/ new Box3();
  13640. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  13641. const _vector$9 = /*@__PURE__*/ new Vector3();
  13642. /**
  13643. * A representation of mesh, line, or point geometry. Includes vertex
  13644. * positions, face indices, normals, colors, UVs, and custom attributes
  13645. * within buffers, reducing the cost of passing all this data to the GPU.
  13646. *
  13647. * ```js
  13648. * const geometry = new THREE.BufferGeometry();
  13649. * // create a simple square shape. We duplicate the top left and bottom right
  13650. * // vertices because each vertex needs to appear once per triangle.
  13651. * const vertices = new Float32Array( [
  13652. * -1.0, -1.0, 1.0, // v0
  13653. * 1.0, -1.0, 1.0, // v1
  13654. * 1.0, 1.0, 1.0, // v2
  13655. *
  13656. * 1.0, 1.0, 1.0, // v3
  13657. * -1.0, 1.0, 1.0, // v4
  13658. * -1.0, -1.0, 1.0 // v5
  13659. * ] );
  13660. * // itemSize = 3 because there are 3 values (components) per vertex
  13661. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13662. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  13663. * const mesh = new THREE.Mesh( geometry, material );
  13664. * ```
  13665. *
  13666. * @augments EventDispatcher
  13667. */
  13668. class BufferGeometry extends EventDispatcher {
  13669. /**
  13670. * Constructs a new geometry.
  13671. */
  13672. constructor() {
  13673. super();
  13674. /**
  13675. * This flag can be used for type testing.
  13676. *
  13677. * @type {boolean}
  13678. * @readonly
  13679. * @default true
  13680. */
  13681. this.isBufferGeometry = true;
  13682. /**
  13683. * The ID of the geometry.
  13684. *
  13685. * @name BufferGeometry#id
  13686. * @type {number}
  13687. * @readonly
  13688. */
  13689. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  13690. /**
  13691. * The UUID of the geometry.
  13692. *
  13693. * @type {string}
  13694. * @readonly
  13695. */
  13696. this.uuid = generateUUID();
  13697. /**
  13698. * The name of the geometry.
  13699. *
  13700. * @type {string}
  13701. */
  13702. this.name = '';
  13703. this.type = 'BufferGeometry';
  13704. /**
  13705. * Allows for vertices to be re-used across multiple triangles; this is
  13706. * called using "indexed triangles". Each triangle is associated with the
  13707. * indices of three vertices. This attribute therefore stores the index of
  13708. * each vertex for each triangular face. If this attribute is not set, the
  13709. * renderer assumes that each three contiguous positions represent a single triangle.
  13710. *
  13711. * @type {?BufferAttribute}
  13712. * @default null
  13713. */
  13714. this.index = null;
  13715. /**
  13716. * A (storage) buffer attribute which was generated with a compute shader and
  13717. * now defines indirect draw calls.
  13718. *
  13719. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13720. *
  13721. * @type {?BufferAttribute}
  13722. * @default null
  13723. */
  13724. this.indirect = null;
  13725. /**
  13726. * 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.
  13727. *
  13728. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13729. *
  13730. * @type {number|Array<number>}
  13731. * @default 0
  13732. */
  13733. this.indirectOffset = 0;
  13734. /**
  13735. * This dictionary has as id the name of the attribute to be set and as value
  13736. * the buffer attribute to set it to. Rather than accessing this property directly,
  13737. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  13738. *
  13739. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  13740. */
  13741. this.attributes = {};
  13742. /**
  13743. * This dictionary holds the morph targets of the geometry.
  13744. *
  13745. * Note: Once the geometry has been rendered, the morph attribute data cannot
  13746. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  13747. *
  13748. * @type {Object}
  13749. */
  13750. this.morphAttributes = {};
  13751. /**
  13752. * Used to control the morph target behavior; when set to `true`, the morph
  13753. * target data is treated as relative offsets, rather than as absolute
  13754. * positions/normals.
  13755. *
  13756. * @type {boolean}
  13757. * @default false
  13758. */
  13759. this.morphTargetsRelative = false;
  13760. /**
  13761. * Split the geometry into groups, each of which will be rendered in a
  13762. * separate draw call. This allows an array of materials to be used with the geometry.
  13763. *
  13764. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  13765. *
  13766. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  13767. * indices, and must not leave vertices or indices unused.
  13768. *
  13769. * @type {Array<Object>}
  13770. */
  13771. this.groups = [];
  13772. /**
  13773. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  13774. *
  13775. * @type {?Box3}
  13776. * @default null
  13777. */
  13778. this.boundingBox = null;
  13779. /**
  13780. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  13781. *
  13782. * @type {?Sphere}
  13783. * @default null
  13784. */
  13785. this.boundingSphere = null;
  13786. /**
  13787. * Determines the part of the geometry to render. This should not be set directly,
  13788. * instead use `setDrawRange()`.
  13789. *
  13790. * @type {{start:number,count:number}}
  13791. */
  13792. this.drawRange = { start: 0, count: Infinity };
  13793. /**
  13794. * An object that can be used to store custom data about the geometry.
  13795. * It should not hold references to functions as these will not be cloned.
  13796. *
  13797. * @type {Object}
  13798. */
  13799. this.userData = {};
  13800. }
  13801. /**
  13802. * Returns the index of this geometry.
  13803. *
  13804. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  13805. */
  13806. getIndex() {
  13807. return this.index;
  13808. }
  13809. /**
  13810. * Sets the given index to this geometry.
  13811. *
  13812. * @param {Array<number>|BufferAttribute} index - The index to set.
  13813. * @return {BufferGeometry} A reference to this instance.
  13814. */
  13815. setIndex( index ) {
  13816. if ( Array.isArray( index ) ) {
  13817. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  13818. } else {
  13819. this.index = index;
  13820. }
  13821. return this;
  13822. }
  13823. /**
  13824. * Sets the given indirect attribute to this geometry.
  13825. *
  13826. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  13827. * @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.
  13828. * @return {BufferGeometry} A reference to this instance.
  13829. */
  13830. setIndirect( indirect, indirectOffset = 0 ) {
  13831. this.indirect = indirect;
  13832. this.indirectOffset = indirectOffset;
  13833. return this;
  13834. }
  13835. /**
  13836. * Returns the indirect attribute of this geometry.
  13837. *
  13838. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  13839. */
  13840. getIndirect() {
  13841. return this.indirect;
  13842. }
  13843. /**
  13844. * Returns the buffer attribute for the given name.
  13845. *
  13846. * @param {string} name - The attribute name.
  13847. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  13848. * Returns `undefined` if not attribute has been found.
  13849. */
  13850. getAttribute( name ) {
  13851. return this.attributes[ name ];
  13852. }
  13853. /**
  13854. * Sets the given attribute for the given name.
  13855. *
  13856. * @param {string} name - The attribute name.
  13857. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  13858. * @return {BufferGeometry} A reference to this instance.
  13859. */
  13860. setAttribute( name, attribute ) {
  13861. this.attributes[ name ] = attribute;
  13862. return this;
  13863. }
  13864. /**
  13865. * Deletes the attribute for the given name.
  13866. *
  13867. * @param {string} name - The attribute name to delete.
  13868. * @return {BufferGeometry} A reference to this instance.
  13869. */
  13870. deleteAttribute( name ) {
  13871. delete this.attributes[ name ];
  13872. return this;
  13873. }
  13874. /**
  13875. * Returns `true` if this geometry has an attribute for the given name.
  13876. *
  13877. * @param {string} name - The attribute name.
  13878. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  13879. */
  13880. hasAttribute( name ) {
  13881. return this.attributes[ name ] !== undefined;
  13882. }
  13883. /**
  13884. * Adds a group to this geometry.
  13885. *
  13886. * @param {number} start - The first element in this draw call. That is the first
  13887. * vertex for non-indexed geometry, otherwise the first triangle index.
  13888. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  13889. * @param {number} [materialIndex=0] - The material array index to use.
  13890. */
  13891. addGroup( start, count, materialIndex = 0 ) {
  13892. this.groups.push( {
  13893. start: start,
  13894. count: count,
  13895. materialIndex: materialIndex
  13896. } );
  13897. }
  13898. /**
  13899. * Clears all groups.
  13900. */
  13901. clearGroups() {
  13902. this.groups = [];
  13903. }
  13904. /**
  13905. * Sets the draw range for this geometry.
  13906. *
  13907. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  13908. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  13909. * For indexed BufferGeometry, `count` is the number of indices to render.
  13910. */
  13911. setDrawRange( start, count ) {
  13912. this.drawRange.start = start;
  13913. this.drawRange.count = count;
  13914. }
  13915. /**
  13916. * Applies the given 4x4 transformation matrix to the geometry.
  13917. *
  13918. * @param {Matrix4} matrix - The matrix to apply.
  13919. * @return {BufferGeometry} A reference to this instance.
  13920. */
  13921. applyMatrix4( matrix ) {
  13922. const position = this.attributes.position;
  13923. if ( position !== undefined ) {
  13924. position.applyMatrix4( matrix );
  13925. position.needsUpdate = true;
  13926. }
  13927. const normal = this.attributes.normal;
  13928. if ( normal !== undefined ) {
  13929. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  13930. normal.applyNormalMatrix( normalMatrix );
  13931. normal.needsUpdate = true;
  13932. }
  13933. const tangent = this.attributes.tangent;
  13934. if ( tangent !== undefined ) {
  13935. tangent.transformDirection( matrix );
  13936. tangent.needsUpdate = true;
  13937. }
  13938. if ( this.boundingBox !== null ) {
  13939. this.computeBoundingBox();
  13940. }
  13941. if ( this.boundingSphere !== null ) {
  13942. this.computeBoundingSphere();
  13943. }
  13944. return this;
  13945. }
  13946. /**
  13947. * Applies the rotation represented by the Quaternion to the geometry.
  13948. *
  13949. * @param {Quaternion} q - The Quaternion to apply.
  13950. * @return {BufferGeometry} A reference to this instance.
  13951. */
  13952. applyQuaternion( q ) {
  13953. _m1.makeRotationFromQuaternion( q );
  13954. this.applyMatrix4( _m1 );
  13955. return this;
  13956. }
  13957. /**
  13958. * Rotates the geometry about the X axis. This is typically done as a one time
  13959. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13960. * real-time mesh rotation.
  13961. *
  13962. * @param {number} angle - The angle in radians.
  13963. * @return {BufferGeometry} A reference to this instance.
  13964. */
  13965. rotateX( angle ) {
  13966. // rotate geometry around world x-axis
  13967. _m1.makeRotationX( angle );
  13968. this.applyMatrix4( _m1 );
  13969. return this;
  13970. }
  13971. /**
  13972. * Rotates the geometry about the Y axis. This is typically done as a one time
  13973. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13974. * real-time mesh rotation.
  13975. *
  13976. * @param {number} angle - The angle in radians.
  13977. * @return {BufferGeometry} A reference to this instance.
  13978. */
  13979. rotateY( angle ) {
  13980. // rotate geometry around world y-axis
  13981. _m1.makeRotationY( angle );
  13982. this.applyMatrix4( _m1 );
  13983. return this;
  13984. }
  13985. /**
  13986. * Rotates the geometry about the Z axis. This is typically done as a one time
  13987. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13988. * real-time mesh rotation.
  13989. *
  13990. * @param {number} angle - The angle in radians.
  13991. * @return {BufferGeometry} A reference to this instance.
  13992. */
  13993. rotateZ( angle ) {
  13994. // rotate geometry around world z-axis
  13995. _m1.makeRotationZ( angle );
  13996. this.applyMatrix4( _m1 );
  13997. return this;
  13998. }
  13999. /**
  14000. * Translates the geometry. This is typically done as a one time
  14001. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14002. * real-time mesh rotation.
  14003. *
  14004. * @param {number} x - The x offset.
  14005. * @param {number} y - The y offset.
  14006. * @param {number} z - The z offset.
  14007. * @return {BufferGeometry} A reference to this instance.
  14008. */
  14009. translate( x, y, z ) {
  14010. // translate geometry
  14011. _m1.makeTranslation( x, y, z );
  14012. this.applyMatrix4( _m1 );
  14013. return this;
  14014. }
  14015. /**
  14016. * Scales the geometry. This is typically done as a one time
  14017. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14018. * real-time mesh rotation.
  14019. *
  14020. * @param {number} x - The x scale.
  14021. * @param {number} y - The y scale.
  14022. * @param {number} z - The z scale.
  14023. * @return {BufferGeometry} A reference to this instance.
  14024. */
  14025. scale( x, y, z ) {
  14026. // scale geometry
  14027. _m1.makeScale( x, y, z );
  14028. this.applyMatrix4( _m1 );
  14029. return this;
  14030. }
  14031. /**
  14032. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14033. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14034. * real-time mesh rotation.
  14035. *
  14036. * @param {Vector3} vector - The target point.
  14037. * @return {BufferGeometry} A reference to this instance.
  14038. */
  14039. lookAt( vector ) {
  14040. _obj.lookAt( vector );
  14041. _obj.updateMatrix();
  14042. this.applyMatrix4( _obj.matrix );
  14043. return this;
  14044. }
  14045. /**
  14046. * Center the geometry based on its bounding box.
  14047. *
  14048. * @return {BufferGeometry} A reference to this instance.
  14049. */
  14050. center() {
  14051. this.computeBoundingBox();
  14052. this.boundingBox.getCenter( _offset ).negate();
  14053. this.translate( _offset.x, _offset.y, _offset.z );
  14054. return this;
  14055. }
  14056. /**
  14057. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14058. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14059. * set to `0`.
  14060. *
  14061. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14062. * data from the array. The length of the array must match the vertex count.
  14063. *
  14064. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14065. * @return {BufferGeometry} A reference to this instance.
  14066. */
  14067. setFromPoints( points ) {
  14068. const positionAttribute = this.getAttribute( 'position' );
  14069. if ( positionAttribute === undefined ) {
  14070. const position = [];
  14071. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14072. const point = points[ i ];
  14073. position.push( point.x, point.y, point.z || 0 );
  14074. }
  14075. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14076. } else {
  14077. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14078. for ( let i = 0; i < l; i ++ ) {
  14079. const point = points[ i ];
  14080. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14081. }
  14082. if ( points.length > positionAttribute.count ) {
  14083. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14084. }
  14085. positionAttribute.needsUpdate = true;
  14086. }
  14087. return this;
  14088. }
  14089. /**
  14090. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14091. * The bounding box is not computed by the engine; it must be computed by your app.
  14092. * You may need to recompute the bounding box if the geometry vertices are modified.
  14093. */
  14094. computeBoundingBox() {
  14095. if ( this.boundingBox === null ) {
  14096. this.boundingBox = new Box3();
  14097. }
  14098. const position = this.attributes.position;
  14099. const morphAttributesPosition = this.morphAttributes.position;
  14100. if ( position && position.isGLBufferAttribute ) {
  14101. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14102. this.boundingBox.set(
  14103. new Vector3( - Infinity, - Infinity, - Infinity ),
  14104. new Vector3( + Infinity, + Infinity, + Infinity )
  14105. );
  14106. return;
  14107. }
  14108. if ( position !== undefined ) {
  14109. this.boundingBox.setFromBufferAttribute( position );
  14110. // process morph attributes if present
  14111. if ( morphAttributesPosition ) {
  14112. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14113. const morphAttribute = morphAttributesPosition[ i ];
  14114. _box$2.setFromBufferAttribute( morphAttribute );
  14115. if ( this.morphTargetsRelative ) {
  14116. _vector$9.addVectors( this.boundingBox.min, _box$2.min );
  14117. this.boundingBox.expandByPoint( _vector$9 );
  14118. _vector$9.addVectors( this.boundingBox.max, _box$2.max );
  14119. this.boundingBox.expandByPoint( _vector$9 );
  14120. } else {
  14121. this.boundingBox.expandByPoint( _box$2.min );
  14122. this.boundingBox.expandByPoint( _box$2.max );
  14123. }
  14124. }
  14125. }
  14126. } else {
  14127. this.boundingBox.makeEmpty();
  14128. }
  14129. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14130. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14131. }
  14132. }
  14133. /**
  14134. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14135. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14136. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14137. */
  14138. computeBoundingSphere() {
  14139. if ( this.boundingSphere === null ) {
  14140. this.boundingSphere = new Sphere();
  14141. }
  14142. const position = this.attributes.position;
  14143. const morphAttributesPosition = this.morphAttributes.position;
  14144. if ( position && position.isGLBufferAttribute ) {
  14145. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14146. this.boundingSphere.set( new Vector3(), Infinity );
  14147. return;
  14148. }
  14149. if ( position ) {
  14150. // first, find the center of the bounding sphere
  14151. const center = this.boundingSphere.center;
  14152. _box$2.setFromBufferAttribute( position );
  14153. // process morph attributes if present
  14154. if ( morphAttributesPosition ) {
  14155. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14156. const morphAttribute = morphAttributesPosition[ i ];
  14157. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14158. if ( this.morphTargetsRelative ) {
  14159. _vector$9.addVectors( _box$2.min, _boxMorphTargets.min );
  14160. _box$2.expandByPoint( _vector$9 );
  14161. _vector$9.addVectors( _box$2.max, _boxMorphTargets.max );
  14162. _box$2.expandByPoint( _vector$9 );
  14163. } else {
  14164. _box$2.expandByPoint( _boxMorphTargets.min );
  14165. _box$2.expandByPoint( _boxMorphTargets.max );
  14166. }
  14167. }
  14168. }
  14169. _box$2.getCenter( center );
  14170. // second, try to find a boundingSphere with a radius smaller than the
  14171. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14172. let maxRadiusSq = 0;
  14173. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14174. _vector$9.fromBufferAttribute( position, i );
  14175. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14176. }
  14177. // process morph attributes if present
  14178. if ( morphAttributesPosition ) {
  14179. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14180. const morphAttribute = morphAttributesPosition[ i ];
  14181. const morphTargetsRelative = this.morphTargetsRelative;
  14182. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14183. _vector$9.fromBufferAttribute( morphAttribute, j );
  14184. if ( morphTargetsRelative ) {
  14185. _offset.fromBufferAttribute( position, j );
  14186. _vector$9.add( _offset );
  14187. }
  14188. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14189. }
  14190. }
  14191. }
  14192. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14193. if ( isNaN( this.boundingSphere.radius ) ) {
  14194. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14195. }
  14196. }
  14197. }
  14198. /**
  14199. * Calculates and adds a tangent attribute to this geometry.
  14200. *
  14201. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14202. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14203. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14204. */
  14205. computeTangents() {
  14206. const index = this.index;
  14207. const attributes = this.attributes;
  14208. // based on http://www.terathon.com/code/tangent.html
  14209. // (per vertex tangents)
  14210. if ( index === null ||
  14211. attributes.position === undefined ||
  14212. attributes.normal === undefined ||
  14213. attributes.uv === undefined ) {
  14214. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14215. return;
  14216. }
  14217. const positionAttribute = attributes.position;
  14218. const normalAttribute = attributes.normal;
  14219. const uvAttribute = attributes.uv;
  14220. if ( this.hasAttribute( 'tangent' ) === false ) {
  14221. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14222. }
  14223. const tangentAttribute = this.getAttribute( 'tangent' );
  14224. const tan1 = [], tan2 = [];
  14225. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14226. tan1[ i ] = new Vector3();
  14227. tan2[ i ] = new Vector3();
  14228. }
  14229. const vA = new Vector3(),
  14230. vB = new Vector3(),
  14231. vC = new Vector3(),
  14232. uvA = new Vector2(),
  14233. uvB = new Vector2(),
  14234. uvC = new Vector2(),
  14235. sdir = new Vector3(),
  14236. tdir = new Vector3();
  14237. function handleTriangle( a, b, c ) {
  14238. vA.fromBufferAttribute( positionAttribute, a );
  14239. vB.fromBufferAttribute( positionAttribute, b );
  14240. vC.fromBufferAttribute( positionAttribute, c );
  14241. uvA.fromBufferAttribute( uvAttribute, a );
  14242. uvB.fromBufferAttribute( uvAttribute, b );
  14243. uvC.fromBufferAttribute( uvAttribute, c );
  14244. vB.sub( vA );
  14245. vC.sub( vA );
  14246. uvB.sub( uvA );
  14247. uvC.sub( uvA );
  14248. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14249. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14250. if ( ! isFinite( r ) ) return;
  14251. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14252. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14253. tan1[ a ].add( sdir );
  14254. tan1[ b ].add( sdir );
  14255. tan1[ c ].add( sdir );
  14256. tan2[ a ].add( tdir );
  14257. tan2[ b ].add( tdir );
  14258. tan2[ c ].add( tdir );
  14259. }
  14260. let groups = this.groups;
  14261. if ( groups.length === 0 ) {
  14262. groups = [ {
  14263. start: 0,
  14264. count: index.count
  14265. } ];
  14266. }
  14267. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14268. const group = groups[ i ];
  14269. const start = group.start;
  14270. const count = group.count;
  14271. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14272. handleTriangle(
  14273. index.getX( j + 0 ),
  14274. index.getX( j + 1 ),
  14275. index.getX( j + 2 )
  14276. );
  14277. }
  14278. }
  14279. const tmp = new Vector3(), tmp2 = new Vector3();
  14280. const n = new Vector3(), n2 = new Vector3();
  14281. function handleVertex( v ) {
  14282. n.fromBufferAttribute( normalAttribute, v );
  14283. n2.copy( n );
  14284. const t = tan1[ v ];
  14285. // Gram-Schmidt orthogonalize
  14286. tmp.copy( t );
  14287. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14288. // Calculate handedness
  14289. tmp2.crossVectors( n2, t );
  14290. const test = tmp2.dot( tan2[ v ] );
  14291. const w = ( test < 0.0 ) ? -1 : 1.0;
  14292. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14293. }
  14294. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14295. const group = groups[ i ];
  14296. const start = group.start;
  14297. const count = group.count;
  14298. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14299. handleVertex( index.getX( j + 0 ) );
  14300. handleVertex( index.getX( j + 1 ) );
  14301. handleVertex( index.getX( j + 2 ) );
  14302. }
  14303. }
  14304. }
  14305. /**
  14306. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14307. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14308. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14309. * to be the same as the face normal.
  14310. */
  14311. computeVertexNormals() {
  14312. const index = this.index;
  14313. const positionAttribute = this.getAttribute( 'position' );
  14314. if ( positionAttribute !== undefined ) {
  14315. let normalAttribute = this.getAttribute( 'normal' );
  14316. if ( normalAttribute === undefined ) {
  14317. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14318. this.setAttribute( 'normal', normalAttribute );
  14319. } else {
  14320. // reset existing normals to zero
  14321. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14322. normalAttribute.setXYZ( i, 0, 0, 0 );
  14323. }
  14324. }
  14325. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14326. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14327. const cb = new Vector3(), ab = new Vector3();
  14328. // indexed elements
  14329. if ( index ) {
  14330. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14331. const vA = index.getX( i + 0 );
  14332. const vB = index.getX( i + 1 );
  14333. const vC = index.getX( i + 2 );
  14334. pA.fromBufferAttribute( positionAttribute, vA );
  14335. pB.fromBufferAttribute( positionAttribute, vB );
  14336. pC.fromBufferAttribute( positionAttribute, vC );
  14337. cb.subVectors( pC, pB );
  14338. ab.subVectors( pA, pB );
  14339. cb.cross( ab );
  14340. nA.fromBufferAttribute( normalAttribute, vA );
  14341. nB.fromBufferAttribute( normalAttribute, vB );
  14342. nC.fromBufferAttribute( normalAttribute, vC );
  14343. nA.add( cb );
  14344. nB.add( cb );
  14345. nC.add( cb );
  14346. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14347. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14348. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14349. }
  14350. } else {
  14351. // non-indexed elements (unconnected triangle soup)
  14352. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14353. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14354. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14355. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14356. cb.subVectors( pC, pB );
  14357. ab.subVectors( pA, pB );
  14358. cb.cross( ab );
  14359. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14360. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14361. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14362. }
  14363. }
  14364. this.normalizeNormals();
  14365. normalAttribute.needsUpdate = true;
  14366. }
  14367. }
  14368. /**
  14369. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14370. * correct lighting on the geometry surfaces.
  14371. */
  14372. normalizeNormals() {
  14373. const normals = this.attributes.normal;
  14374. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14375. _vector$9.fromBufferAttribute( normals, i );
  14376. _vector$9.normalize();
  14377. normals.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  14378. }
  14379. }
  14380. /**
  14381. * Return a new non-index version of this indexed geometry. If the geometry
  14382. * is already non-indexed, the method is a NOOP.
  14383. *
  14384. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14385. */
  14386. toNonIndexed() {
  14387. function convertBufferAttribute( attribute, indices ) {
  14388. const array = attribute.array;
  14389. const itemSize = attribute.itemSize;
  14390. const normalized = attribute.normalized;
  14391. const array2 = new array.constructor( indices.length * itemSize );
  14392. let index = 0, index2 = 0;
  14393. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14394. if ( attribute.isInterleavedBufferAttribute ) {
  14395. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14396. } else {
  14397. index = indices[ i ] * itemSize;
  14398. }
  14399. for ( let j = 0; j < itemSize; j ++ ) {
  14400. array2[ index2 ++ ] = array[ index ++ ];
  14401. }
  14402. }
  14403. return new BufferAttribute( array2, itemSize, normalized );
  14404. }
  14405. //
  14406. if ( this.index === null ) {
  14407. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14408. return this;
  14409. }
  14410. const geometry2 = new BufferGeometry();
  14411. const indices = this.index.array;
  14412. const attributes = this.attributes;
  14413. // attributes
  14414. for ( const name in attributes ) {
  14415. const attribute = attributes[ name ];
  14416. const newAttribute = convertBufferAttribute( attribute, indices );
  14417. geometry2.setAttribute( name, newAttribute );
  14418. }
  14419. // morph attributes
  14420. const morphAttributes = this.morphAttributes;
  14421. for ( const name in morphAttributes ) {
  14422. const morphArray = [];
  14423. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14424. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14425. const attribute = morphAttribute[ i ];
  14426. const newAttribute = convertBufferAttribute( attribute, indices );
  14427. morphArray.push( newAttribute );
  14428. }
  14429. geometry2.morphAttributes[ name ] = morphArray;
  14430. }
  14431. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14432. // groups
  14433. const groups = this.groups;
  14434. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14435. const group = groups[ i ];
  14436. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14437. }
  14438. return geometry2;
  14439. }
  14440. /**
  14441. * Serializes the geometry into JSON.
  14442. *
  14443. * @return {Object} A JSON object representing the serialized geometry.
  14444. */
  14445. toJSON() {
  14446. const data = {
  14447. metadata: {
  14448. version: 4.7,
  14449. type: 'BufferGeometry',
  14450. generator: 'BufferGeometry.toJSON'
  14451. }
  14452. };
  14453. // standard BufferGeometry serialization
  14454. data.uuid = this.uuid;
  14455. data.type = this.type;
  14456. if ( this.name !== '' ) data.name = this.name;
  14457. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14458. if ( this.parameters !== undefined ) {
  14459. const parameters = this.parameters;
  14460. for ( const key in parameters ) {
  14461. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14462. }
  14463. return data;
  14464. }
  14465. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14466. data.data = { attributes: {} };
  14467. const index = this.index;
  14468. if ( index !== null ) {
  14469. data.data.index = {
  14470. type: index.array.constructor.name,
  14471. array: Array.prototype.slice.call( index.array )
  14472. };
  14473. }
  14474. const attributes = this.attributes;
  14475. for ( const key in attributes ) {
  14476. const attribute = attributes[ key ];
  14477. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14478. }
  14479. const morphAttributes = {};
  14480. let hasMorphAttributes = false;
  14481. for ( const key in this.morphAttributes ) {
  14482. const attributeArray = this.morphAttributes[ key ];
  14483. const array = [];
  14484. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14485. const attribute = attributeArray[ i ];
  14486. array.push( attribute.toJSON( data.data ) );
  14487. }
  14488. if ( array.length > 0 ) {
  14489. morphAttributes[ key ] = array;
  14490. hasMorphAttributes = true;
  14491. }
  14492. }
  14493. if ( hasMorphAttributes ) {
  14494. data.data.morphAttributes = morphAttributes;
  14495. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14496. }
  14497. const groups = this.groups;
  14498. if ( groups.length > 0 ) {
  14499. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14500. }
  14501. const boundingSphere = this.boundingSphere;
  14502. if ( boundingSphere !== null ) {
  14503. data.data.boundingSphere = boundingSphere.toJSON();
  14504. }
  14505. return data;
  14506. }
  14507. /**
  14508. * Returns a new geometry with copied values from this instance.
  14509. *
  14510. * @return {BufferGeometry} A clone of this instance.
  14511. */
  14512. clone() {
  14513. return new this.constructor().copy( this );
  14514. }
  14515. /**
  14516. * Copies the values of the given geometry to this instance.
  14517. *
  14518. * @param {BufferGeometry} source - The geometry to copy.
  14519. * @return {BufferGeometry} A reference to this instance.
  14520. */
  14521. copy( source ) {
  14522. // reset
  14523. this.index = null;
  14524. this.attributes = {};
  14525. this.morphAttributes = {};
  14526. this.groups = [];
  14527. this.boundingBox = null;
  14528. this.boundingSphere = null;
  14529. // used for storing cloned, shared data
  14530. const data = {};
  14531. // name
  14532. this.name = source.name;
  14533. // index
  14534. const index = source.index;
  14535. if ( index !== null ) {
  14536. this.setIndex( index.clone() );
  14537. }
  14538. // attributes
  14539. const attributes = source.attributes;
  14540. for ( const name in attributes ) {
  14541. const attribute = attributes[ name ];
  14542. this.setAttribute( name, attribute.clone( data ) );
  14543. }
  14544. // morph attributes
  14545. const morphAttributes = source.morphAttributes;
  14546. for ( const name in morphAttributes ) {
  14547. const array = [];
  14548. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14549. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  14550. array.push( morphAttribute[ i ].clone( data ) );
  14551. }
  14552. this.morphAttributes[ name ] = array;
  14553. }
  14554. this.morphTargetsRelative = source.morphTargetsRelative;
  14555. // groups
  14556. const groups = source.groups;
  14557. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14558. const group = groups[ i ];
  14559. this.addGroup( group.start, group.count, group.materialIndex );
  14560. }
  14561. // bounding box
  14562. const boundingBox = source.boundingBox;
  14563. if ( boundingBox !== null ) {
  14564. this.boundingBox = boundingBox.clone();
  14565. }
  14566. // bounding sphere
  14567. const boundingSphere = source.boundingSphere;
  14568. if ( boundingSphere !== null ) {
  14569. this.boundingSphere = boundingSphere.clone();
  14570. }
  14571. // draw range
  14572. this.drawRange.start = source.drawRange.start;
  14573. this.drawRange.count = source.drawRange.count;
  14574. // user data
  14575. this.userData = source.userData;
  14576. return this;
  14577. }
  14578. /**
  14579. * Frees the GPU-related resources allocated by this instance. Call this
  14580. * method whenever this instance is no longer used in your app.
  14581. *
  14582. * @fires BufferGeometry#dispose
  14583. */
  14584. dispose() {
  14585. this.dispatchEvent( { type: 'dispose' } );
  14586. }
  14587. }
  14588. /**
  14589. * "Interleaved" means that multiple attributes, possibly of different types,
  14590. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  14591. *
  14592. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  14593. */
  14594. class InterleavedBuffer {
  14595. /**
  14596. * Constructs a new interleaved buffer.
  14597. *
  14598. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  14599. * @param {number} stride - The number of typed-array elements per vertex.
  14600. */
  14601. constructor( array, stride ) {
  14602. /**
  14603. * This flag can be used for type testing.
  14604. *
  14605. * @type {boolean}
  14606. * @readonly
  14607. * @default true
  14608. */
  14609. this.isInterleavedBuffer = true;
  14610. /**
  14611. * A typed array with a shared buffer storing attribute data.
  14612. *
  14613. * @type {TypedArray}
  14614. */
  14615. this.array = array;
  14616. /**
  14617. * The number of typed-array elements per vertex.
  14618. *
  14619. * @type {number}
  14620. */
  14621. this.stride = stride;
  14622. /**
  14623. * The total number of elements in the array
  14624. *
  14625. * @type {number}
  14626. * @readonly
  14627. */
  14628. this.count = array !== undefined ? array.length / stride : 0;
  14629. /**
  14630. * Defines the intended usage pattern of the data store for optimization purposes.
  14631. *
  14632. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  14633. * instantiate a new one and set the desired usage before the next render.
  14634. *
  14635. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  14636. * @default StaticDrawUsage
  14637. */
  14638. this.usage = StaticDrawUsage;
  14639. /**
  14640. * This can be used to only update some components of stored vectors (for example, just the
  14641. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  14642. *
  14643. * @type {Array<Object>}
  14644. */
  14645. this.updateRanges = [];
  14646. /**
  14647. * A version number, incremented every time the `needsUpdate` is set to `true`.
  14648. *
  14649. * @type {number}
  14650. */
  14651. this.version = 0;
  14652. /**
  14653. * The UUID of the interleaved buffer.
  14654. *
  14655. * @type {string}
  14656. * @readonly
  14657. */
  14658. this.uuid = generateUUID();
  14659. }
  14660. /**
  14661. * A callback function that is executed after the renderer has transferred the attribute array
  14662. * data to the GPU.
  14663. */
  14664. onUploadCallback() {}
  14665. /**
  14666. * Flag to indicate that this attribute has changed and should be re-sent to
  14667. * the GPU. Set this to `true` when you modify the value of the array.
  14668. *
  14669. * @type {number}
  14670. * @default false
  14671. * @param {boolean} value
  14672. */
  14673. set needsUpdate( value ) {
  14674. if ( value === true ) this.version ++;
  14675. }
  14676. /**
  14677. * Sets the usage of this interleaved buffer.
  14678. *
  14679. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  14680. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  14681. */
  14682. setUsage( value ) {
  14683. this.usage = value;
  14684. return this;
  14685. }
  14686. /**
  14687. * Adds a range of data in the data array to be updated on the GPU.
  14688. *
  14689. * @param {number} start - Position at which to start update.
  14690. * @param {number} count - The number of components to update.
  14691. */
  14692. addUpdateRange( start, count ) {
  14693. this.updateRanges.push( { start, count } );
  14694. }
  14695. /**
  14696. * Clears the update ranges.
  14697. */
  14698. clearUpdateRanges() {
  14699. this.updateRanges.length = 0;
  14700. }
  14701. /**
  14702. * Copies the values of the given interleaved buffer to this instance.
  14703. *
  14704. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  14705. * @return {InterleavedBuffer} A reference to this instance.
  14706. */
  14707. copy( source ) {
  14708. this.array = new source.array.constructor( source.array );
  14709. this.count = source.count;
  14710. this.stride = source.stride;
  14711. this.usage = source.usage;
  14712. return this;
  14713. }
  14714. /**
  14715. * Copies a vector from the given interleaved buffer to this one. The start
  14716. * and destination position in the attribute buffers are represented by the
  14717. * given indices.
  14718. *
  14719. * @param {number} index1 - The destination index into this interleaved buffer.
  14720. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  14721. * @param {number} index2 - The source index into the given interleaved buffer.
  14722. * @return {InterleavedBuffer} A reference to this instance.
  14723. */
  14724. copyAt( index1, interleavedBuffer, index2 ) {
  14725. index1 *= this.stride;
  14726. index2 *= interleavedBuffer.stride;
  14727. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  14728. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  14729. }
  14730. return this;
  14731. }
  14732. /**
  14733. * Sets the given array data in the interleaved buffer.
  14734. *
  14735. * @param {(TypedArray|Array)} value - The array data to set.
  14736. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  14737. * @return {InterleavedBuffer} A reference to this instance.
  14738. */
  14739. set( value, offset = 0 ) {
  14740. this.array.set( value, offset );
  14741. return this;
  14742. }
  14743. /**
  14744. * Returns a new interleaved buffer with copied values from this instance.
  14745. *
  14746. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  14747. * @return {InterleavedBuffer} A clone of this instance.
  14748. */
  14749. clone( data ) {
  14750. if ( data.arrayBuffers === undefined ) {
  14751. data.arrayBuffers = {};
  14752. }
  14753. if ( this.array.buffer._uuid === undefined ) {
  14754. this.array.buffer._uuid = generateUUID();
  14755. }
  14756. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14757. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  14758. }
  14759. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  14760. const ib = new this.constructor( array, this.stride );
  14761. ib.setUsage( this.usage );
  14762. return ib;
  14763. }
  14764. /**
  14765. * Sets the given callback function that is executed after the Renderer has transferred
  14766. * the array data to the GPU. Can be used to perform clean-up operations after
  14767. * the upload when data are not needed anymore on the CPU side.
  14768. *
  14769. * @param {Function} callback - The `onUpload()` callback.
  14770. * @return {InterleavedBuffer} A reference to this instance.
  14771. */
  14772. onUpload( callback ) {
  14773. this.onUploadCallback = callback;
  14774. return this;
  14775. }
  14776. /**
  14777. * Serializes the interleaved buffer into JSON.
  14778. *
  14779. * @param {Object} [data] - An optional value holding meta information about the serialization.
  14780. * @return {Object} A JSON object representing the serialized interleaved buffer.
  14781. */
  14782. toJSON( data ) {
  14783. if ( data.arrayBuffers === undefined ) {
  14784. data.arrayBuffers = {};
  14785. }
  14786. // generate UUID for array buffer if necessary
  14787. if ( this.array.buffer._uuid === undefined ) {
  14788. this.array.buffer._uuid = generateUUID();
  14789. }
  14790. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14791. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  14792. }
  14793. //
  14794. return {
  14795. uuid: this.uuid,
  14796. buffer: this.array.buffer._uuid,
  14797. type: this.array.constructor.name,
  14798. stride: this.stride
  14799. };
  14800. }
  14801. }
  14802. const _vector$8 = /*@__PURE__*/ new Vector3();
  14803. /**
  14804. * An alternative version of a buffer attribute with interleaved data. Interleaved
  14805. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  14806. * different offsets into the buffer.
  14807. */
  14808. class InterleavedBufferAttribute {
  14809. /**
  14810. * Constructs a new interleaved buffer attribute.
  14811. *
  14812. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  14813. * @param {number} itemSize - The item size.
  14814. * @param {number} offset - The attribute offset into the buffer.
  14815. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14816. */
  14817. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  14818. /**
  14819. * This flag can be used for type testing.
  14820. *
  14821. * @type {boolean}
  14822. * @readonly
  14823. * @default true
  14824. */
  14825. this.isInterleavedBufferAttribute = true;
  14826. /**
  14827. * The name of the buffer attribute.
  14828. *
  14829. * @type {string}
  14830. */
  14831. this.name = '';
  14832. /**
  14833. * The buffer holding the interleaved data.
  14834. *
  14835. * @type {InterleavedBuffer}
  14836. */
  14837. this.data = interleavedBuffer;
  14838. /**
  14839. * The item size, see {@link BufferAttribute#itemSize}.
  14840. *
  14841. * @type {number}
  14842. */
  14843. this.itemSize = itemSize;
  14844. /**
  14845. * The attribute offset into the buffer.
  14846. *
  14847. * @type {number}
  14848. */
  14849. this.offset = offset;
  14850. /**
  14851. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  14852. *
  14853. * @type {InterleavedBuffer}
  14854. */
  14855. this.normalized = normalized;
  14856. }
  14857. /**
  14858. * The item count of this buffer attribute.
  14859. *
  14860. * @type {number}
  14861. * @readonly
  14862. */
  14863. get count() {
  14864. return this.data.count;
  14865. }
  14866. /**
  14867. * The array holding the interleaved buffer attribute data.
  14868. *
  14869. * @type {TypedArray}
  14870. */
  14871. get array() {
  14872. return this.data.array;
  14873. }
  14874. /**
  14875. * Flag to indicate that this attribute has changed and should be re-sent to
  14876. * the GPU. Set this to `true` when you modify the value of the array.
  14877. *
  14878. * @type {number}
  14879. * @default false
  14880. * @param {boolean} value
  14881. */
  14882. set needsUpdate( value ) {
  14883. this.data.needsUpdate = value;
  14884. }
  14885. /**
  14886. * Applies the given 4x4 matrix to the given attribute. Only works with
  14887. * item size `3`.
  14888. *
  14889. * @param {Matrix4} m - The matrix to apply.
  14890. * @return {InterleavedBufferAttribute} A reference to this instance.
  14891. */
  14892. applyMatrix4( m ) {
  14893. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  14894. _vector$8.fromBufferAttribute( this, i );
  14895. _vector$8.applyMatrix4( m );
  14896. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14897. }
  14898. return this;
  14899. }
  14900. /**
  14901. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  14902. * item size `3`.
  14903. *
  14904. * @param {Matrix3} m - The normal matrix to apply.
  14905. * @return {InterleavedBufferAttribute} A reference to this instance.
  14906. */
  14907. applyNormalMatrix( m ) {
  14908. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14909. _vector$8.fromBufferAttribute( this, i );
  14910. _vector$8.applyNormalMatrix( m );
  14911. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14912. }
  14913. return this;
  14914. }
  14915. /**
  14916. * Applies the given 4x4 matrix to the given attribute. Only works with
  14917. * item size `3` and with direction vectors.
  14918. *
  14919. * @param {Matrix4} m - The matrix to apply.
  14920. * @return {InterleavedBufferAttribute} A reference to this instance.
  14921. */
  14922. transformDirection( m ) {
  14923. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14924. _vector$8.fromBufferAttribute( this, i );
  14925. _vector$8.transformDirection( m );
  14926. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14927. }
  14928. return this;
  14929. }
  14930. /**
  14931. * Returns the given component of the vector at the given index.
  14932. *
  14933. * @param {number} index - The index into the buffer attribute.
  14934. * @param {number} component - The component index.
  14935. * @return {number} The returned value.
  14936. */
  14937. getComponent( index, component ) {
  14938. let value = this.array[ index * this.data.stride + this.offset + component ];
  14939. if ( this.normalized ) value = denormalize( value, this.array );
  14940. return value;
  14941. }
  14942. /**
  14943. * Sets the given value to the given component of the vector at the given index.
  14944. *
  14945. * @param {number} index - The index into the buffer attribute.
  14946. * @param {number} component - The component index.
  14947. * @param {number} value - The value to set.
  14948. * @return {InterleavedBufferAttribute} A reference to this instance.
  14949. */
  14950. setComponent( index, component, value ) {
  14951. if ( this.normalized ) value = normalize( value, this.array );
  14952. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  14953. return this;
  14954. }
  14955. /**
  14956. * Sets the x component of the vector at the given index.
  14957. *
  14958. * @param {number} index - The index into the buffer attribute.
  14959. * @param {number} x - The value to set.
  14960. * @return {InterleavedBufferAttribute} A reference to this instance.
  14961. */
  14962. setX( index, x ) {
  14963. if ( this.normalized ) x = normalize( x, this.array );
  14964. this.data.array[ index * this.data.stride + this.offset ] = x;
  14965. return this;
  14966. }
  14967. /**
  14968. * Sets the y component of the vector at the given index.
  14969. *
  14970. * @param {number} index - The index into the buffer attribute.
  14971. * @param {number} y - The value to set.
  14972. * @return {InterleavedBufferAttribute} A reference to this instance.
  14973. */
  14974. setY( index, y ) {
  14975. if ( this.normalized ) y = normalize( y, this.array );
  14976. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  14977. return this;
  14978. }
  14979. /**
  14980. * Sets the z component of the vector at the given index.
  14981. *
  14982. * @param {number} index - The index into the buffer attribute.
  14983. * @param {number} z - The value to set.
  14984. * @return {InterleavedBufferAttribute} A reference to this instance.
  14985. */
  14986. setZ( index, z ) {
  14987. if ( this.normalized ) z = normalize( z, this.array );
  14988. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  14989. return this;
  14990. }
  14991. /**
  14992. * Sets the w component of the vector at the given index.
  14993. *
  14994. * @param {number} index - The index into the buffer attribute.
  14995. * @param {number} w - The value to set.
  14996. * @return {InterleavedBufferAttribute} A reference to this instance.
  14997. */
  14998. setW( index, w ) {
  14999. if ( this.normalized ) w = normalize( w, this.array );
  15000. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15001. return this;
  15002. }
  15003. /**
  15004. * Returns the x component of the vector at the given index.
  15005. *
  15006. * @param {number} index - The index into the buffer attribute.
  15007. * @return {number} The x component.
  15008. */
  15009. getX( index ) {
  15010. let x = this.data.array[ index * this.data.stride + this.offset ];
  15011. if ( this.normalized ) x = denormalize( x, this.array );
  15012. return x;
  15013. }
  15014. /**
  15015. * Returns the y component of the vector at the given index.
  15016. *
  15017. * @param {number} index - The index into the buffer attribute.
  15018. * @return {number} The y component.
  15019. */
  15020. getY( index ) {
  15021. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  15022. if ( this.normalized ) y = denormalize( y, this.array );
  15023. return y;
  15024. }
  15025. /**
  15026. * Returns the z component of the vector at the given index.
  15027. *
  15028. * @param {number} index - The index into the buffer attribute.
  15029. * @return {number} The z component.
  15030. */
  15031. getZ( index ) {
  15032. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  15033. if ( this.normalized ) z = denormalize( z, this.array );
  15034. return z;
  15035. }
  15036. /**
  15037. * Returns the w component of the vector at the given index.
  15038. *
  15039. * @param {number} index - The index into the buffer attribute.
  15040. * @return {number} The w component.
  15041. */
  15042. getW( index ) {
  15043. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  15044. if ( this.normalized ) w = denormalize( w, this.array );
  15045. return w;
  15046. }
  15047. /**
  15048. * Sets the x and y component of the vector at the given index.
  15049. *
  15050. * @param {number} index - The index into the buffer attribute.
  15051. * @param {number} x - The value for the x component to set.
  15052. * @param {number} y - The value for the y component to set.
  15053. * @return {InterleavedBufferAttribute} A reference to this instance.
  15054. */
  15055. setXY( index, x, y ) {
  15056. index = index * this.data.stride + this.offset;
  15057. if ( this.normalized ) {
  15058. x = normalize( x, this.array );
  15059. y = normalize( y, this.array );
  15060. }
  15061. this.data.array[ index + 0 ] = x;
  15062. this.data.array[ index + 1 ] = y;
  15063. return this;
  15064. }
  15065. /**
  15066. * Sets the x, y and z component of the vector at the given index.
  15067. *
  15068. * @param {number} index - The index into the buffer attribute.
  15069. * @param {number} x - The value for the x component to set.
  15070. * @param {number} y - The value for the y component to set.
  15071. * @param {number} z - The value for the z component to set.
  15072. * @return {InterleavedBufferAttribute} A reference to this instance.
  15073. */
  15074. setXYZ( index, x, y, z ) {
  15075. index = index * this.data.stride + this.offset;
  15076. if ( this.normalized ) {
  15077. x = normalize( x, this.array );
  15078. y = normalize( y, this.array );
  15079. z = normalize( z, this.array );
  15080. }
  15081. this.data.array[ index + 0 ] = x;
  15082. this.data.array[ index + 1 ] = y;
  15083. this.data.array[ index + 2 ] = z;
  15084. return this;
  15085. }
  15086. /**
  15087. * Sets the x, y, z and w component of the vector at the given index.
  15088. *
  15089. * @param {number} index - The index into the buffer attribute.
  15090. * @param {number} x - The value for the x component to set.
  15091. * @param {number} y - The value for the y component to set.
  15092. * @param {number} z - The value for the z component to set.
  15093. * @param {number} w - The value for the w component to set.
  15094. * @return {InterleavedBufferAttribute} A reference to this instance.
  15095. */
  15096. setXYZW( index, x, y, z, w ) {
  15097. index = index * this.data.stride + this.offset;
  15098. if ( this.normalized ) {
  15099. x = normalize( x, this.array );
  15100. y = normalize( y, this.array );
  15101. z = normalize( z, this.array );
  15102. w = normalize( w, this.array );
  15103. }
  15104. this.data.array[ index + 0 ] = x;
  15105. this.data.array[ index + 1 ] = y;
  15106. this.data.array[ index + 2 ] = z;
  15107. this.data.array[ index + 3 ] = w;
  15108. return this;
  15109. }
  15110. /**
  15111. * Returns a new buffer attribute with copied values from this instance.
  15112. *
  15113. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15114. *
  15115. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  15116. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  15117. */
  15118. clone( data ) {
  15119. if ( data === undefined ) {
  15120. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  15121. const array = [];
  15122. for ( let i = 0; i < this.count; i ++ ) {
  15123. const index = i * this.data.stride + this.offset;
  15124. for ( let j = 0; j < this.itemSize; j ++ ) {
  15125. array.push( this.data.array[ index + j ] );
  15126. }
  15127. }
  15128. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15129. } else {
  15130. if ( data.interleavedBuffers === undefined ) {
  15131. data.interleavedBuffers = {};
  15132. }
  15133. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15134. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15135. }
  15136. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15137. }
  15138. }
  15139. /**
  15140. * Serializes the buffer attribute into JSON.
  15141. *
  15142. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15143. *
  15144. * @param {Object} [data] - An optional value holding meta information about the serialization.
  15145. * @return {Object} A JSON object representing the serialized buffer attribute.
  15146. */
  15147. toJSON( data ) {
  15148. if ( data === undefined ) {
  15149. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  15150. const array = [];
  15151. for ( let i = 0; i < this.count; i ++ ) {
  15152. const index = i * this.data.stride + this.offset;
  15153. for ( let j = 0; j < this.itemSize; j ++ ) {
  15154. array.push( this.data.array[ index + j ] );
  15155. }
  15156. }
  15157. // de-interleave data and save it as an ordinary buffer attribute for now
  15158. return {
  15159. itemSize: this.itemSize,
  15160. type: this.array.constructor.name,
  15161. array: array,
  15162. normalized: this.normalized
  15163. };
  15164. } else {
  15165. // save as true interleaved attribute
  15166. if ( data.interleavedBuffers === undefined ) {
  15167. data.interleavedBuffers = {};
  15168. }
  15169. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15170. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15171. }
  15172. return {
  15173. isInterleavedBufferAttribute: true,
  15174. itemSize: this.itemSize,
  15175. data: this.data.uuid,
  15176. offset: this.offset,
  15177. normalized: this.normalized
  15178. };
  15179. }
  15180. }
  15181. }
  15182. let _materialId = 0;
  15183. /**
  15184. * Abstract base class for materials.
  15185. *
  15186. * Materials define the appearance of renderable 3D objects.
  15187. *
  15188. * @abstract
  15189. * @augments EventDispatcher
  15190. */
  15191. class Material extends EventDispatcher {
  15192. /**
  15193. * Constructs a new material.
  15194. */
  15195. constructor() {
  15196. super();
  15197. /**
  15198. * This flag can be used for type testing.
  15199. *
  15200. * @type {boolean}
  15201. * @readonly
  15202. * @default true
  15203. */
  15204. this.isMaterial = true;
  15205. /**
  15206. * The ID of the material.
  15207. *
  15208. * @name Material#id
  15209. * @type {number}
  15210. * @readonly
  15211. */
  15212. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  15213. /**
  15214. * The UUID of the material.
  15215. *
  15216. * @type {string}
  15217. * @readonly
  15218. */
  15219. this.uuid = generateUUID();
  15220. /**
  15221. * The name of the material.
  15222. *
  15223. * @type {string}
  15224. */
  15225. this.name = '';
  15226. /**
  15227. * The type property is used for detecting the object type
  15228. * in context of serialization/deserialization.
  15229. *
  15230. * @type {string}
  15231. * @readonly
  15232. */
  15233. this.type = 'Material';
  15234. /**
  15235. * Defines the blending type of the material.
  15236. *
  15237. * It must be set to `CustomBlending` if custom blending properties like
  15238. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  15239. * should have any effect.
  15240. *
  15241. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  15242. * @default NormalBlending
  15243. */
  15244. this.blending = NormalBlending;
  15245. /**
  15246. * Defines which side of faces will be rendered - front, back or both.
  15247. *
  15248. * @type {(FrontSide|BackSide|DoubleSide)}
  15249. * @default FrontSide
  15250. */
  15251. this.side = FrontSide;
  15252. /**
  15253. * If set to `true`, vertex colors should be used.
  15254. *
  15255. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  15256. * four (RGBA) component color buffer attribute is used.
  15257. *
  15258. * @type {boolean}
  15259. * @default false
  15260. */
  15261. this.vertexColors = false;
  15262. /**
  15263. * Defines how transparent the material is.
  15264. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  15265. *
  15266. * If the {@link Material#transparent} is not set to `true`,
  15267. * the material will remain fully opaque and this value will only affect its color.
  15268. *
  15269. * @type {number}
  15270. * @default 1
  15271. */
  15272. this.opacity = 1;
  15273. /**
  15274. * Defines whether this material is transparent. This has an effect on
  15275. * rendering as transparent objects need special treatment and are rendered
  15276. * after non-transparent objects.
  15277. *
  15278. * When set to true, the extent to which the material is transparent is
  15279. * controlled by {@link Material#opacity}.
  15280. *
  15281. * @type {boolean}
  15282. * @default false
  15283. */
  15284. this.transparent = false;
  15285. /**
  15286. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  15287. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  15288. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  15289. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  15290. *
  15291. * @type {boolean}
  15292. * @default false
  15293. */
  15294. this.alphaHash = false;
  15295. /**
  15296. * Defines the blending source factor.
  15297. *
  15298. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15299. * @default SrcAlphaFactor
  15300. */
  15301. this.blendSrc = SrcAlphaFactor;
  15302. /**
  15303. * Defines the blending destination factor.
  15304. *
  15305. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15306. * @default OneMinusSrcAlphaFactor
  15307. */
  15308. this.blendDst = OneMinusSrcAlphaFactor;
  15309. /**
  15310. * Defines the blending equation.
  15311. *
  15312. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15313. * @default AddEquation
  15314. */
  15315. this.blendEquation = AddEquation;
  15316. /**
  15317. * Defines the blending source alpha factor.
  15318. *
  15319. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15320. * @default null
  15321. */
  15322. this.blendSrcAlpha = null;
  15323. /**
  15324. * Defines the blending destination alpha factor.
  15325. *
  15326. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15327. * @default null
  15328. */
  15329. this.blendDstAlpha = null;
  15330. /**
  15331. * Defines the blending equation of the alpha channel.
  15332. *
  15333. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15334. * @default null
  15335. */
  15336. this.blendEquationAlpha = null;
  15337. /**
  15338. * Represents the RGB values of the constant blend color.
  15339. *
  15340. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  15341. *
  15342. * @type {Color}
  15343. * @default (0,0,0)
  15344. */
  15345. this.blendColor = new Color( 0, 0, 0 );
  15346. /**
  15347. * Represents the alpha value of the constant blend color.
  15348. *
  15349. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  15350. *
  15351. * @type {number}
  15352. * @default 0
  15353. */
  15354. this.blendAlpha = 0;
  15355. /**
  15356. * Defines the depth function.
  15357. *
  15358. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  15359. * @default LessEqualDepth
  15360. */
  15361. this.depthFunc = LessEqualDepth;
  15362. /**
  15363. * Whether to have depth test enabled when rendering this material.
  15364. * When the depth test is disabled, the depth write will also be implicitly disabled.
  15365. *
  15366. * @type {boolean}
  15367. * @default true
  15368. */
  15369. this.depthTest = true;
  15370. /**
  15371. * Whether rendering this material has any effect on the depth buffer.
  15372. *
  15373. * When drawing 2D overlays it can be useful to disable the depth writing in
  15374. * order to layer several things together without creating z-index artifacts.
  15375. *
  15376. * @type {boolean}
  15377. * @default true
  15378. */
  15379. this.depthWrite = true;
  15380. /**
  15381. * The bit mask to use when writing to the stencil buffer.
  15382. *
  15383. * @type {number}
  15384. * @default 0xff
  15385. */
  15386. this.stencilWriteMask = 0xff;
  15387. /**
  15388. * The stencil comparison function to use.
  15389. *
  15390. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  15391. * @default AlwaysStencilFunc
  15392. */
  15393. this.stencilFunc = AlwaysStencilFunc;
  15394. /**
  15395. * The value to use when performing stencil comparisons or stencil operations.
  15396. *
  15397. * @type {number}
  15398. * @default 0
  15399. */
  15400. this.stencilRef = 0;
  15401. /**
  15402. * The bit mask to use when comparing against the stencil buffer.
  15403. *
  15404. * @type {number}
  15405. * @default 0xff
  15406. */
  15407. this.stencilFuncMask = 0xff;
  15408. /**
  15409. * Which stencil operation to perform when the comparison function returns `false`.
  15410. *
  15411. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15412. * @default KeepStencilOp
  15413. */
  15414. this.stencilFail = KeepStencilOp;
  15415. /**
  15416. * Which stencil operation to perform when the comparison function returns
  15417. * `true` but the depth test fails.
  15418. *
  15419. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15420. * @default KeepStencilOp
  15421. */
  15422. this.stencilZFail = KeepStencilOp;
  15423. /**
  15424. * Which stencil operation to perform when the comparison function returns
  15425. * `true` and the depth test passes.
  15426. *
  15427. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15428. * @default KeepStencilOp
  15429. */
  15430. this.stencilZPass = KeepStencilOp;
  15431. /**
  15432. * Whether stencil operations are performed against the stencil buffer. In
  15433. * order to perform writes or comparisons against the stencil buffer this
  15434. * value must be `true`.
  15435. *
  15436. * @type {boolean}
  15437. * @default false
  15438. */
  15439. this.stencilWrite = false;
  15440. /**
  15441. * User-defined clipping planes specified as THREE.Plane objects in world
  15442. * space. These planes apply to the objects this material is attached to.
  15443. * Points in space whose signed distance to the plane is negative are clipped
  15444. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  15445. * be `true`.
  15446. *
  15447. * @type {?Array<Plane>}
  15448. * @default null
  15449. */
  15450. this.clippingPlanes = null;
  15451. /**
  15452. * Changes the behavior of clipping planes so that only their intersection is
  15453. * clipped, rather than their union.
  15454. *
  15455. * @type {boolean}
  15456. * @default false
  15457. */
  15458. this.clipIntersection = false;
  15459. /**
  15460. * Defines whether to clip shadows according to the clipping planes specified
  15461. * on this material.
  15462. *
  15463. * @type {boolean}
  15464. * @default false
  15465. */
  15466. this.clipShadows = false;
  15467. /**
  15468. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  15469. * is determined as follows:
  15470. *
  15471. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  15472. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  15473. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  15474. *
  15475. * @type {?(FrontSide|BackSide|DoubleSide)}
  15476. * @default null
  15477. */
  15478. this.shadowSide = null;
  15479. /**
  15480. * Whether to render the material's color.
  15481. *
  15482. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  15483. * objects that occlude other objects.
  15484. *
  15485. * @type {boolean}
  15486. * @default true
  15487. */
  15488. this.colorWrite = true;
  15489. /**
  15490. * Override the renderer's default precision for this material.
  15491. *
  15492. * @type {?('highp'|'mediump'|'lowp')}
  15493. * @default null
  15494. */
  15495. this.precision = null;
  15496. /**
  15497. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  15498. * be offset after it is interpolated from the depth values of the appropriate vertices.
  15499. * The offset is added before the depth test is performed and before the value is written
  15500. * into the depth buffer.
  15501. *
  15502. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  15503. * rendering solids with highlighted edges.
  15504. *
  15505. * @type {boolean}
  15506. * @default false
  15507. */
  15508. this.polygonOffset = false;
  15509. /**
  15510. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  15511. *
  15512. * @type {number}
  15513. * @default 0
  15514. */
  15515. this.polygonOffsetFactor = 0;
  15516. /**
  15517. * Is multiplied by an implementation-specific value to create a constant depth offset.
  15518. *
  15519. * @type {number}
  15520. * @default 0
  15521. */
  15522. this.polygonOffsetUnits = 0;
  15523. /**
  15524. * Whether to apply dithering to the color to remove the appearance of banding.
  15525. *
  15526. * @type {boolean}
  15527. * @default false
  15528. */
  15529. this.dithering = false;
  15530. /**
  15531. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  15532. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  15533. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  15534. *
  15535. * @type {boolean}
  15536. * @default false
  15537. */
  15538. this.alphaToCoverage = false;
  15539. /**
  15540. * Whether to premultiply the alpha (transparency) value.
  15541. *
  15542. * @type {boolean}
  15543. * @default false
  15544. */
  15545. this.premultipliedAlpha = false;
  15546. /**
  15547. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  15548. *
  15549. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  15550. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  15551. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  15552. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  15553. * disable the two pass rendering to avoid performance issues.
  15554. *
  15555. * @type {boolean}
  15556. * @default false
  15557. */
  15558. this.forceSinglePass = false;
  15559. /**
  15560. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  15561. *
  15562. * @type {boolean}
  15563. * @default true
  15564. */
  15565. this.allowOverride = true;
  15566. /**
  15567. * Defines whether 3D objects using this material are visible.
  15568. *
  15569. * @type {boolean}
  15570. * @default true
  15571. */
  15572. this.visible = true;
  15573. /**
  15574. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  15575. *
  15576. * It is ignored when rendering to a render target or using post processing or when using
  15577. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  15578. *
  15579. * @type {boolean}
  15580. * @default true
  15581. */
  15582. this.toneMapped = true;
  15583. /**
  15584. * An object that can be used to store custom data about the Material. It
  15585. * should not hold references to functions as these will not be cloned.
  15586. *
  15587. * @type {Object}
  15588. */
  15589. this.userData = {};
  15590. /**
  15591. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  15592. *
  15593. * @type {number}
  15594. * @readonly
  15595. * @default 0
  15596. */
  15597. this.version = 0;
  15598. this._alphaTest = 0;
  15599. }
  15600. /**
  15601. * Sets the alpha value to be used when running an alpha test. The material
  15602. * will not be rendered if the opacity is lower than this value.
  15603. *
  15604. * @type {number}
  15605. * @readonly
  15606. * @default 0
  15607. */
  15608. get alphaTest() {
  15609. return this._alphaTest;
  15610. }
  15611. set alphaTest( value ) {
  15612. if ( this._alphaTest > 0 !== value > 0 ) {
  15613. this.version ++;
  15614. }
  15615. this._alphaTest = value;
  15616. }
  15617. /**
  15618. * An optional callback that is executed immediately before the material is used to render a 3D object.
  15619. *
  15620. * This method can only be used when rendering with {@link WebGLRenderer}.
  15621. *
  15622. * @param {WebGLRenderer} renderer - The renderer.
  15623. * @param {Scene} scene - The scene.
  15624. * @param {Camera} camera - The camera that is used to render the scene.
  15625. * @param {BufferGeometry} geometry - The 3D object's geometry.
  15626. * @param {Object3D} object - The 3D object.
  15627. * @param {Object} group - The geometry group data.
  15628. */
  15629. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  15630. /**
  15631. * An optional callback that is executed immediately before the shader
  15632. * program is compiled. This function is called with the shader source code
  15633. * as a parameter. Useful for the modification of built-in materials.
  15634. *
  15635. * This method can only be used when rendering with {@link WebGLRenderer}. The
  15636. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  15637. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  15638. *
  15639. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  15640. * @param {WebGLRenderer} renderer - A reference to the renderer.
  15641. */
  15642. onBeforeCompile( /* shaderobject, renderer */ ) {}
  15643. /**
  15644. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  15645. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  15646. * shader or recompile the shader for this material as needed.
  15647. *
  15648. * This method can only be used when rendering with {@link WebGLRenderer}.
  15649. *
  15650. * @return {string} The custom program cache key.
  15651. */
  15652. customProgramCacheKey() {
  15653. return this.onBeforeCompile.toString();
  15654. }
  15655. /**
  15656. * This method can be used to set default values from parameter objects.
  15657. * It is a generic implementation so it can be used with different types
  15658. * of materials.
  15659. *
  15660. * @param {Object} [values] - The material values to set.
  15661. */
  15662. setValues( values ) {
  15663. if ( values === undefined ) return;
  15664. for ( const key in values ) {
  15665. const newValue = values[ key ];
  15666. if ( newValue === undefined ) {
  15667. warn( `Material: parameter '${ key }' has value of undefined.` );
  15668. continue;
  15669. }
  15670. const currentValue = this[ key ];
  15671. if ( currentValue === undefined ) {
  15672. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  15673. continue;
  15674. }
  15675. if ( currentValue && currentValue.isColor ) {
  15676. currentValue.set( newValue );
  15677. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  15678. currentValue.copy( newValue );
  15679. } else {
  15680. this[ key ] = newValue;
  15681. }
  15682. }
  15683. }
  15684. /**
  15685. * Serializes the material into JSON.
  15686. *
  15687. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  15688. * @return {Object} A JSON object representing the serialized material.
  15689. * @see {@link ObjectLoader#parse}
  15690. */
  15691. toJSON( meta ) {
  15692. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  15693. if ( isRootObject ) {
  15694. meta = {
  15695. textures: {},
  15696. images: {}
  15697. };
  15698. }
  15699. const data = {
  15700. metadata: {
  15701. version: 4.7,
  15702. type: 'Material',
  15703. generator: 'Material.toJSON'
  15704. }
  15705. };
  15706. // standard Material serialization
  15707. data.uuid = this.uuid;
  15708. data.type = this.type;
  15709. if ( this.name !== '' ) data.name = this.name;
  15710. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  15711. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  15712. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  15713. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  15714. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  15715. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  15716. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  15717. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  15718. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  15719. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  15720. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  15721. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  15722. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  15723. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  15724. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  15725. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  15726. }
  15727. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  15728. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  15729. }
  15730. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  15731. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  15732. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  15733. }
  15734. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  15735. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  15736. }
  15737. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  15738. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  15739. }
  15740. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  15741. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  15742. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  15743. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  15744. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  15745. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  15746. }
  15747. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  15748. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  15749. }
  15750. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  15751. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  15752. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  15753. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  15754. }
  15755. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  15756. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  15757. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  15758. if ( this.lightMap && this.lightMap.isTexture ) {
  15759. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  15760. data.lightMapIntensity = this.lightMapIntensity;
  15761. }
  15762. if ( this.aoMap && this.aoMap.isTexture ) {
  15763. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  15764. data.aoMapIntensity = this.aoMapIntensity;
  15765. }
  15766. if ( this.bumpMap && this.bumpMap.isTexture ) {
  15767. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  15768. data.bumpScale = this.bumpScale;
  15769. }
  15770. if ( this.normalMap && this.normalMap.isTexture ) {
  15771. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  15772. data.normalMapType = this.normalMapType;
  15773. data.normalScale = this.normalScale.toArray();
  15774. }
  15775. if ( this.displacementMap && this.displacementMap.isTexture ) {
  15776. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  15777. data.displacementScale = this.displacementScale;
  15778. data.displacementBias = this.displacementBias;
  15779. }
  15780. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  15781. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  15782. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  15783. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  15784. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  15785. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  15786. if ( this.envMap && this.envMap.isTexture ) {
  15787. data.envMap = this.envMap.toJSON( meta ).uuid;
  15788. if ( this.combine !== undefined ) data.combine = this.combine;
  15789. }
  15790. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  15791. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  15792. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  15793. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  15794. if ( this.gradientMap && this.gradientMap.isTexture ) {
  15795. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  15796. }
  15797. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  15798. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  15799. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  15800. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  15801. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  15802. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  15803. if ( this.size !== undefined ) data.size = this.size;
  15804. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  15805. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  15806. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  15807. if ( this.side !== FrontSide ) data.side = this.side;
  15808. if ( this.vertexColors === true ) data.vertexColors = true;
  15809. if ( this.opacity < 1 ) data.opacity = this.opacity;
  15810. if ( this.transparent === true ) data.transparent = true;
  15811. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  15812. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  15813. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  15814. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  15815. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  15816. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  15817. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  15818. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  15819. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  15820. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  15821. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  15822. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  15823. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  15824. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  15825. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  15826. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  15827. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  15828. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  15829. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  15830. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  15831. // rotation (SpriteMaterial)
  15832. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  15833. if ( this.polygonOffset === true ) data.polygonOffset = true;
  15834. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  15835. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  15836. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  15837. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  15838. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  15839. if ( this.scale !== undefined ) data.scale = this.scale;
  15840. if ( this.dithering === true ) data.dithering = true;
  15841. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  15842. if ( this.alphaHash === true ) data.alphaHash = true;
  15843. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  15844. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  15845. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  15846. if ( this.allowOverride === false ) data.allowOverride = false;
  15847. if ( this.wireframe === true ) data.wireframe = true;
  15848. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  15849. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  15850. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  15851. if ( this.flatShading === true ) data.flatShading = true;
  15852. if ( this.visible === false ) data.visible = false;
  15853. if ( this.toneMapped === false ) data.toneMapped = false;
  15854. if ( this.fog === false ) data.fog = false;
  15855. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15856. // TODO: Copied from Object3D.toJSON
  15857. function extractFromCache( cache ) {
  15858. const values = [];
  15859. for ( const key in cache ) {
  15860. const data = cache[ key ];
  15861. delete data.metadata;
  15862. values.push( data );
  15863. }
  15864. return values;
  15865. }
  15866. if ( isRootObject ) {
  15867. const textures = extractFromCache( meta.textures );
  15868. const images = extractFromCache( meta.images );
  15869. if ( textures.length > 0 ) data.textures = textures;
  15870. if ( images.length > 0 ) data.images = images;
  15871. }
  15872. return data;
  15873. }
  15874. /**
  15875. * Returns a new material with copied values from this instance.
  15876. *
  15877. * @return {Material} A clone of this instance.
  15878. */
  15879. clone() {
  15880. return new this.constructor().copy( this );
  15881. }
  15882. /**
  15883. * Copies the values of the given material to this instance.
  15884. *
  15885. * @param {Material} source - The material to copy.
  15886. * @return {Material} A reference to this instance.
  15887. */
  15888. copy( source ) {
  15889. this.name = source.name;
  15890. this.blending = source.blending;
  15891. this.side = source.side;
  15892. this.vertexColors = source.vertexColors;
  15893. this.opacity = source.opacity;
  15894. this.transparent = source.transparent;
  15895. this.blendSrc = source.blendSrc;
  15896. this.blendDst = source.blendDst;
  15897. this.blendEquation = source.blendEquation;
  15898. this.blendSrcAlpha = source.blendSrcAlpha;
  15899. this.blendDstAlpha = source.blendDstAlpha;
  15900. this.blendEquationAlpha = source.blendEquationAlpha;
  15901. this.blendColor.copy( source.blendColor );
  15902. this.blendAlpha = source.blendAlpha;
  15903. this.depthFunc = source.depthFunc;
  15904. this.depthTest = source.depthTest;
  15905. this.depthWrite = source.depthWrite;
  15906. this.stencilWriteMask = source.stencilWriteMask;
  15907. this.stencilFunc = source.stencilFunc;
  15908. this.stencilRef = source.stencilRef;
  15909. this.stencilFuncMask = source.stencilFuncMask;
  15910. this.stencilFail = source.stencilFail;
  15911. this.stencilZFail = source.stencilZFail;
  15912. this.stencilZPass = source.stencilZPass;
  15913. this.stencilWrite = source.stencilWrite;
  15914. const srcPlanes = source.clippingPlanes;
  15915. let dstPlanes = null;
  15916. if ( srcPlanes !== null ) {
  15917. const n = srcPlanes.length;
  15918. dstPlanes = new Array( n );
  15919. for ( let i = 0; i !== n; ++ i ) {
  15920. dstPlanes[ i ] = srcPlanes[ i ].clone();
  15921. }
  15922. }
  15923. this.clippingPlanes = dstPlanes;
  15924. this.clipIntersection = source.clipIntersection;
  15925. this.clipShadows = source.clipShadows;
  15926. this.shadowSide = source.shadowSide;
  15927. this.colorWrite = source.colorWrite;
  15928. this.precision = source.precision;
  15929. this.polygonOffset = source.polygonOffset;
  15930. this.polygonOffsetFactor = source.polygonOffsetFactor;
  15931. this.polygonOffsetUnits = source.polygonOffsetUnits;
  15932. this.dithering = source.dithering;
  15933. this.alphaTest = source.alphaTest;
  15934. this.alphaHash = source.alphaHash;
  15935. this.alphaToCoverage = source.alphaToCoverage;
  15936. this.premultipliedAlpha = source.premultipliedAlpha;
  15937. this.forceSinglePass = source.forceSinglePass;
  15938. this.allowOverride = source.allowOverride;
  15939. this.visible = source.visible;
  15940. this.toneMapped = source.toneMapped;
  15941. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  15942. return this;
  15943. }
  15944. /**
  15945. * Frees the GPU-related resources allocated by this instance. Call this
  15946. * method whenever this instance is no longer used in your app.
  15947. *
  15948. * @fires Material#dispose
  15949. */
  15950. dispose() {
  15951. /**
  15952. * Fires when the material has been disposed of.
  15953. *
  15954. * @event Material#dispose
  15955. * @type {Object}
  15956. */
  15957. this.dispatchEvent( { type: 'dispose' } );
  15958. }
  15959. /**
  15960. * Setting this property to `true` indicates the engine the material
  15961. * needs to be recompiled.
  15962. *
  15963. * @type {boolean}
  15964. * @default false
  15965. * @param {boolean} value
  15966. */
  15967. set needsUpdate( value ) {
  15968. if ( value === true ) this.version ++;
  15969. }
  15970. }
  15971. /**
  15972. * A material for rendering instances of {@link Sprite}.
  15973. *
  15974. * ```js
  15975. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  15976. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  15977. *
  15978. * const sprite = new THREE.Sprite( material );
  15979. * sprite.scale.set(200, 200, 1)
  15980. * scene.add( sprite );
  15981. * ```
  15982. *
  15983. * @augments Material
  15984. */
  15985. class SpriteMaterial extends Material {
  15986. /**
  15987. * Constructs a new sprite material.
  15988. *
  15989. * @param {Object} [parameters] - An object with one or more properties
  15990. * defining the material's appearance. Any property of the material
  15991. * (including any property from inherited materials) can be passed
  15992. * in here. Color values can be passed any type of value accepted
  15993. * by {@link Color#set}.
  15994. */
  15995. constructor( parameters ) {
  15996. super();
  15997. /**
  15998. * This flag can be used for type testing.
  15999. *
  16000. * @type {boolean}
  16001. * @readonly
  16002. * @default true
  16003. */
  16004. this.isSpriteMaterial = true;
  16005. this.type = 'SpriteMaterial';
  16006. /**
  16007. * Color of the material.
  16008. *
  16009. * @type {Color}
  16010. * @default (1,1,1)
  16011. */
  16012. this.color = new Color( 0xffffff );
  16013. /**
  16014. * The color map. May optionally include an alpha channel, typically combined
  16015. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  16016. * color is modulated by the diffuse `color`.
  16017. *
  16018. * @type {?Texture}
  16019. * @default null
  16020. */
  16021. this.map = null;
  16022. /**
  16023. * The alpha map is a grayscale texture that controls the opacity across the
  16024. * surface (black: fully transparent; white: fully opaque).
  16025. *
  16026. * Only the color of the texture is used, ignoring the alpha channel if one
  16027. * exists. For RGB and RGBA textures, the renderer will use the green channel
  16028. * when sampling this texture due to the extra bit of precision provided for
  16029. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  16030. * luminance/alpha textures will also still work as expected.
  16031. *
  16032. * @type {?Texture}
  16033. * @default null
  16034. */
  16035. this.alphaMap = null;
  16036. /**
  16037. * The rotation of the sprite in radians.
  16038. *
  16039. * @type {number}
  16040. * @default 0
  16041. */
  16042. this.rotation = 0;
  16043. /**
  16044. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  16045. *
  16046. * @type {boolean}
  16047. * @default true
  16048. */
  16049. this.sizeAttenuation = true;
  16050. /**
  16051. * Overwritten since sprite materials are transparent
  16052. * by default.
  16053. *
  16054. * @type {boolean}
  16055. * @default true
  16056. */
  16057. this.transparent = true;
  16058. /**
  16059. * Whether the material is affected by fog or not.
  16060. *
  16061. * @type {boolean}
  16062. * @default true
  16063. */
  16064. this.fog = true;
  16065. this.setValues( parameters );
  16066. }
  16067. copy( source ) {
  16068. super.copy( source );
  16069. this.color.copy( source.color );
  16070. this.map = source.map;
  16071. this.alphaMap = source.alphaMap;
  16072. this.rotation = source.rotation;
  16073. this.sizeAttenuation = source.sizeAttenuation;
  16074. this.fog = source.fog;
  16075. return this;
  16076. }
  16077. }
  16078. let _geometry;
  16079. const _intersectPoint = /*@__PURE__*/ new Vector3();
  16080. const _worldScale = /*@__PURE__*/ new Vector3();
  16081. const _mvPosition = /*@__PURE__*/ new Vector3();
  16082. const _alignedPosition = /*@__PURE__*/ new Vector2();
  16083. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  16084. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  16085. const _vA$1 = /*@__PURE__*/ new Vector3();
  16086. const _vB$1 = /*@__PURE__*/ new Vector3();
  16087. const _vC$1 = /*@__PURE__*/ new Vector3();
  16088. const _uvA = /*@__PURE__*/ new Vector2();
  16089. const _uvB = /*@__PURE__*/ new Vector2();
  16090. const _uvC = /*@__PURE__*/ new Vector2();
  16091. /**
  16092. * A sprite is a plane that always faces towards the camera, generally with a
  16093. * partially transparent texture applied.
  16094. *
  16095. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  16096. * have no effect.
  16097. *
  16098. * ```js
  16099. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  16100. * const material = new THREE.SpriteMaterial( { map: map } );
  16101. *
  16102. * const sprite = new THREE.Sprite( material );
  16103. * scene.add( sprite );
  16104. * ```
  16105. *
  16106. * @augments Object3D
  16107. */
  16108. class Sprite extends Object3D {
  16109. /**
  16110. * Constructs a new sprite.
  16111. *
  16112. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  16113. */
  16114. constructor( material = new SpriteMaterial() ) {
  16115. super();
  16116. /**
  16117. * This flag can be used for type testing.
  16118. *
  16119. * @type {boolean}
  16120. * @readonly
  16121. * @default true
  16122. */
  16123. this.isSprite = true;
  16124. this.type = 'Sprite';
  16125. if ( _geometry === undefined ) {
  16126. _geometry = new BufferGeometry();
  16127. const float32Array = new Float32Array( [
  16128. -0.5, -0.5, 0, 0, 0,
  16129. 0.5, -0.5, 0, 1, 0,
  16130. 0.5, 0.5, 0, 1, 1,
  16131. -0.5, 0.5, 0, 0, 1
  16132. ] );
  16133. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16134. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16135. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16136. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16137. }
  16138. /**
  16139. * The sprite geometry.
  16140. *
  16141. * @type {BufferGeometry}
  16142. */
  16143. this.geometry = _geometry;
  16144. /**
  16145. * The sprite material.
  16146. *
  16147. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  16148. */
  16149. this.material = material;
  16150. /**
  16151. * The sprite's anchor point, and the point around which the sprite rotates.
  16152. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  16153. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  16154. *
  16155. * @type {Vector2}
  16156. * @default (0.5,0.5)
  16157. */
  16158. this.center = new Vector2( 0.5, 0.5 );
  16159. /**
  16160. * The number of instances of this sprite.
  16161. * Can only be used with {@link WebGPURenderer}.
  16162. *
  16163. * @type {number}
  16164. * @default 1
  16165. */
  16166. this.count = 1;
  16167. }
  16168. /**
  16169. * Computes intersection points between a casted ray and this sprite.
  16170. *
  16171. * @param {Raycaster} raycaster - The raycaster.
  16172. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16173. */
  16174. raycast( raycaster, intersects ) {
  16175. if ( raycaster.camera === null ) {
  16176. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16177. }
  16178. _worldScale.setFromMatrixScale( this.matrixWorld );
  16179. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16180. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16181. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16182. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16183. _worldScale.multiplyScalar( - _mvPosition.z );
  16184. }
  16185. const rotation = this.material.rotation;
  16186. let sin, cos;
  16187. if ( rotation !== 0 ) {
  16188. cos = Math.cos( rotation );
  16189. sin = Math.sin( rotation );
  16190. }
  16191. const center = this.center;
  16192. transformVertex( _vA$1.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16193. transformVertex( _vB$1.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16194. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16195. _uvA.set( 0, 0 );
  16196. _uvB.set( 1, 0 );
  16197. _uvC.set( 1, 1 );
  16198. // check first triangle
  16199. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16200. if ( intersect === null ) {
  16201. // check second triangle
  16202. transformVertex( _vB$1.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16203. _uvB.set( 0, 1 );
  16204. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16205. if ( intersect === null ) {
  16206. return;
  16207. }
  16208. }
  16209. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16210. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16211. intersects.push( {
  16212. distance: distance,
  16213. point: _intersectPoint.clone(),
  16214. uv: Triangle.getInterpolation( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA, _uvB, _uvC, new Vector2() ),
  16215. face: null,
  16216. object: this
  16217. } );
  16218. }
  16219. copy( source, recursive ) {
  16220. super.copy( source, recursive );
  16221. if ( source.center !== undefined ) this.center.copy( source.center );
  16222. this.material = source.material;
  16223. return this;
  16224. }
  16225. }
  16226. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16227. // compute position in camera space
  16228. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16229. // to check if rotation is not zero
  16230. if ( sin !== undefined ) {
  16231. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16232. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16233. } else {
  16234. _rotatedPosition.copy( _alignedPosition );
  16235. }
  16236. vertexPosition.copy( mvPosition );
  16237. vertexPosition.x += _rotatedPosition.x;
  16238. vertexPosition.y += _rotatedPosition.y;
  16239. // transform to world space
  16240. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16241. }
  16242. const _v1$2 = /*@__PURE__*/ new Vector3();
  16243. const _v2$1 = /*@__PURE__*/ new Vector3();
  16244. /**
  16245. * A component for providing a basic Level of Detail (LOD) mechanism.
  16246. *
  16247. * Every LOD level is associated with an object, and rendering can be switched
  16248. * between them at the distances specified. Typically you would create, say,
  16249. * three meshes, one for far away (low detail), one for mid range (medium
  16250. * detail) and one for close up (high detail).
  16251. *
  16252. * ```js
  16253. * const lod = new THREE.LOD();
  16254. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  16255. *
  16256. * //Create spheres with 3 levels of detail and create new LOD levels for them
  16257. * for( let i = 0; i < 3; i++ ) {
  16258. *
  16259. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  16260. * const mesh = new THREE.Mesh( geometry, material );
  16261. * lod.addLevel( mesh, i * 75 );
  16262. *
  16263. * }
  16264. *
  16265. * scene.add( lod );
  16266. * ```
  16267. *
  16268. * @augments Object3D
  16269. */
  16270. class LOD extends Object3D {
  16271. /**
  16272. * Constructs a new LOD.
  16273. */
  16274. constructor() {
  16275. super();
  16276. /**
  16277. * This flag can be used for type testing.
  16278. *
  16279. * @type {boolean}
  16280. * @readonly
  16281. * @default true
  16282. */
  16283. this.isLOD = true;
  16284. /**
  16285. * The current LOD index.
  16286. *
  16287. * @private
  16288. * @type {number}
  16289. * @default 0
  16290. */
  16291. this._currentLevel = 0;
  16292. this.type = 'LOD';
  16293. Object.defineProperties( this, {
  16294. /**
  16295. * This array holds the LOD levels.
  16296. *
  16297. * @name LOD#levels
  16298. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  16299. */
  16300. levels: {
  16301. enumerable: true,
  16302. value: []
  16303. }
  16304. } );
  16305. /**
  16306. * Whether the LOD object is updated automatically by the renderer per frame
  16307. * or not. If set to `false`, you have to call {@link LOD#update} in the
  16308. * render loop by yourself.
  16309. *
  16310. * @type {boolean}
  16311. * @default true
  16312. */
  16313. this.autoUpdate = true;
  16314. }
  16315. copy( source ) {
  16316. super.copy( source, false );
  16317. const levels = source.levels;
  16318. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16319. const level = levels[ i ];
  16320. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  16321. }
  16322. this.autoUpdate = source.autoUpdate;
  16323. return this;
  16324. }
  16325. /**
  16326. * Adds a mesh that will display at a certain distance and greater. Typically
  16327. * the further away the distance, the lower the detail on the mesh.
  16328. *
  16329. * @param {Object3D} object - The 3D object to display at this level.
  16330. * @param {number} [distance=0] - The distance at which to display this level of detail.
  16331. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  16332. * @return {LOD} A reference to this instance.
  16333. */
  16334. addLevel( object, distance = 0, hysteresis = 0 ) {
  16335. distance = Math.abs( distance );
  16336. const levels = this.levels;
  16337. let l;
  16338. for ( l = 0; l < levels.length; l ++ ) {
  16339. if ( distance < levels[ l ].distance ) {
  16340. break;
  16341. }
  16342. }
  16343. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  16344. this.add( object );
  16345. return this;
  16346. }
  16347. /**
  16348. * Removes an existing level, based on the distance from the camera.
  16349. * Returns `true` when the level has been removed. Otherwise `false`.
  16350. *
  16351. * @param {number} distance - Distance of the level to remove.
  16352. * @return {boolean} Whether the level has been removed or not.
  16353. */
  16354. removeLevel( distance ) {
  16355. const levels = this.levels;
  16356. for ( let i = 0; i < levels.length; i ++ ) {
  16357. if ( levels[ i ].distance === distance ) {
  16358. const removedElements = levels.splice( i, 1 );
  16359. this.remove( removedElements[ 0 ].object );
  16360. return true;
  16361. }
  16362. }
  16363. return false;
  16364. }
  16365. /**
  16366. * Returns the currently active LOD level index.
  16367. *
  16368. * @return {number} The current active LOD level index.
  16369. */
  16370. getCurrentLevel() {
  16371. return this._currentLevel;
  16372. }
  16373. /**
  16374. * Returns a reference to the first 3D object that is greater than
  16375. * the given distance.
  16376. *
  16377. * @param {number} distance - The LOD distance.
  16378. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  16379. */
  16380. getObjectForDistance( distance ) {
  16381. const levels = this.levels;
  16382. if ( levels.length > 0 ) {
  16383. let i, l;
  16384. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16385. let levelDistance = levels[ i ].distance;
  16386. if ( levels[ i ].object.visible ) {
  16387. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16388. }
  16389. if ( distance < levelDistance ) {
  16390. break;
  16391. }
  16392. }
  16393. return levels[ i - 1 ].object;
  16394. }
  16395. return null;
  16396. }
  16397. /**
  16398. * Computes intersection points between a casted ray and this LOD.
  16399. *
  16400. * @param {Raycaster} raycaster - The raycaster.
  16401. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16402. */
  16403. raycast( raycaster, intersects ) {
  16404. const levels = this.levels;
  16405. if ( levels.length > 0 ) {
  16406. _v1$2.setFromMatrixPosition( this.matrixWorld );
  16407. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  16408. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16409. }
  16410. }
  16411. /**
  16412. * Updates the LOD by computing which LOD level should be visible according
  16413. * to the current distance of the given camera.
  16414. *
  16415. * @param {Camera} camera - The camera the scene is rendered with.
  16416. */
  16417. update( camera ) {
  16418. const levels = this.levels;
  16419. if ( levels.length > 1 ) {
  16420. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  16421. _v2$1.setFromMatrixPosition( this.matrixWorld );
  16422. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  16423. levels[ 0 ].object.visible = true;
  16424. let i, l;
  16425. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16426. let levelDistance = levels[ i ].distance;
  16427. if ( levels[ i ].object.visible ) {
  16428. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16429. }
  16430. if ( distance >= levelDistance ) {
  16431. levels[ i - 1 ].object.visible = false;
  16432. levels[ i ].object.visible = true;
  16433. } else {
  16434. break;
  16435. }
  16436. }
  16437. this._currentLevel = i - 1;
  16438. for ( ; i < l; i ++ ) {
  16439. levels[ i ].object.visible = false;
  16440. }
  16441. }
  16442. }
  16443. toJSON( meta ) {
  16444. const data = super.toJSON( meta );
  16445. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16446. data.object.levels = [];
  16447. const levels = this.levels;
  16448. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16449. const level = levels[ i ];
  16450. data.object.levels.push( {
  16451. object: level.object.uuid,
  16452. distance: level.distance,
  16453. hysteresis: level.hysteresis
  16454. } );
  16455. }
  16456. return data;
  16457. }
  16458. }
  16459. const _vector$7 = /*@__PURE__*/ new Vector3();
  16460. const _segCenter = /*@__PURE__*/ new Vector3();
  16461. const _segDir = /*@__PURE__*/ new Vector3();
  16462. const _diff = /*@__PURE__*/ new Vector3();
  16463. const _edge1 = /*@__PURE__*/ new Vector3();
  16464. const _edge2 = /*@__PURE__*/ new Vector3();
  16465. const _normal$1 = /*@__PURE__*/ new Vector3();
  16466. /**
  16467. * A ray that emits from an origin in a certain direction. The class is used by
  16468. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  16469. * mouse picking (working out what objects in the 3D space the mouse is over)
  16470. * amongst other things.
  16471. */
  16472. class Ray {
  16473. /**
  16474. * Constructs a new ray.
  16475. *
  16476. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  16477. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  16478. */
  16479. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  16480. /**
  16481. * The origin of the ray.
  16482. *
  16483. * @type {Vector3}
  16484. */
  16485. this.origin = origin;
  16486. /**
  16487. * The (normalized) direction of the ray.
  16488. *
  16489. * @type {Vector3}
  16490. */
  16491. this.direction = direction;
  16492. }
  16493. /**
  16494. * Sets the ray's components by copying the given values.
  16495. *
  16496. * @param {Vector3} origin - The origin.
  16497. * @param {Vector3} direction - The direction.
  16498. * @return {Ray} A reference to this ray.
  16499. */
  16500. set( origin, direction ) {
  16501. this.origin.copy( origin );
  16502. this.direction.copy( direction );
  16503. return this;
  16504. }
  16505. /**
  16506. * Copies the values of the given ray to this instance.
  16507. *
  16508. * @param {Ray} ray - The ray to copy.
  16509. * @return {Ray} A reference to this ray.
  16510. */
  16511. copy( ray ) {
  16512. this.origin.copy( ray.origin );
  16513. this.direction.copy( ray.direction );
  16514. return this;
  16515. }
  16516. /**
  16517. * Returns a vector that is located at a given distance along this ray.
  16518. *
  16519. * @param {number} t - The distance along the ray to retrieve a position for.
  16520. * @param {Vector3} target - The target vector that is used to store the method's result.
  16521. * @return {Vector3} A position on the ray.
  16522. */
  16523. at( t, target ) {
  16524. return target.copy( this.origin ).addScaledVector( this.direction, t );
  16525. }
  16526. /**
  16527. * Adjusts the direction of the ray to point at the given vector in world space.
  16528. *
  16529. * @param {Vector3} v - The target position.
  16530. * @return {Ray} A reference to this ray.
  16531. */
  16532. lookAt( v ) {
  16533. this.direction.copy( v ).sub( this.origin ).normalize();
  16534. return this;
  16535. }
  16536. /**
  16537. * Shift the origin of this ray along its direction by the given distance.
  16538. *
  16539. * @param {number} t - The distance along the ray to interpolate.
  16540. * @return {Ray} A reference to this ray.
  16541. */
  16542. recast( t ) {
  16543. this.origin.copy( this.at( t, _vector$7 ) );
  16544. return this;
  16545. }
  16546. /**
  16547. * Returns the point along this ray that is closest to the given point.
  16548. *
  16549. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  16550. * @param {Vector3} target - The target vector that is used to store the method's result.
  16551. * @return {Vector3} The closest point on this ray.
  16552. */
  16553. closestPointToPoint( point, target ) {
  16554. target.subVectors( point, this.origin );
  16555. const directionDistance = target.dot( this.direction );
  16556. if ( directionDistance < 0 ) {
  16557. return target.copy( this.origin );
  16558. }
  16559. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16560. }
  16561. /**
  16562. * Returns the distance of the closest approach between this ray and the given point.
  16563. *
  16564. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16565. * @return {number} The distance.
  16566. */
  16567. distanceToPoint( point ) {
  16568. return Math.sqrt( this.distanceSqToPoint( point ) );
  16569. }
  16570. /**
  16571. * Returns the squared distance of the closest approach between this ray and the given point.
  16572. *
  16573. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16574. * @return {number} The squared distance.
  16575. */
  16576. distanceSqToPoint( point ) {
  16577. const directionDistance = _vector$7.subVectors( point, this.origin ).dot( this.direction );
  16578. // point behind the ray
  16579. if ( directionDistance < 0 ) {
  16580. return this.origin.distanceToSquared( point );
  16581. }
  16582. _vector$7.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16583. return _vector$7.distanceToSquared( point );
  16584. }
  16585. /**
  16586. * Returns the squared distance between this ray and the given line segment.
  16587. *
  16588. * @param {Vector3} v0 - The start point of the line segment.
  16589. * @param {Vector3} v1 - The end point of the line segment.
  16590. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  16591. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  16592. * @return {number} The squared distance.
  16593. */
  16594. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  16595. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  16596. // It returns the min distance between the ray and the segment
  16597. // defined by v0 and v1
  16598. // It can also set two optional targets :
  16599. // - The closest point on the ray
  16600. // - The closest point on the segment
  16601. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  16602. _segDir.copy( v1 ).sub( v0 ).normalize();
  16603. _diff.copy( this.origin ).sub( _segCenter );
  16604. const segExtent = v0.distanceTo( v1 ) * 0.5;
  16605. const a01 = - this.direction.dot( _segDir );
  16606. const b0 = _diff.dot( this.direction );
  16607. const b1 = - _diff.dot( _segDir );
  16608. const c = _diff.lengthSq();
  16609. const det = Math.abs( 1 - a01 * a01 );
  16610. let s0, s1, sqrDist, extDet;
  16611. if ( det > 0 ) {
  16612. // The ray and segment are not parallel.
  16613. s0 = a01 * b1 - b0;
  16614. s1 = a01 * b0 - b1;
  16615. extDet = segExtent * det;
  16616. if ( s0 >= 0 ) {
  16617. if ( s1 >= - extDet ) {
  16618. if ( s1 <= extDet ) {
  16619. // region 0
  16620. // Minimum at interior points of ray and segment.
  16621. const invDet = 1 / det;
  16622. s0 *= invDet;
  16623. s1 *= invDet;
  16624. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  16625. } else {
  16626. // region 1
  16627. s1 = segExtent;
  16628. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16629. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16630. }
  16631. } else {
  16632. // region 5
  16633. s1 = - segExtent;
  16634. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16635. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16636. }
  16637. } else {
  16638. if ( s1 <= - extDet ) {
  16639. // region 4
  16640. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  16641. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16642. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16643. } else if ( s1 <= extDet ) {
  16644. // region 3
  16645. s0 = 0;
  16646. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16647. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  16648. } else {
  16649. // region 2
  16650. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  16651. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16652. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16653. }
  16654. }
  16655. } else {
  16656. // Ray and segment are parallel.
  16657. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  16658. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16659. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16660. }
  16661. if ( optionalPointOnRay ) {
  16662. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  16663. }
  16664. if ( optionalPointOnSegment ) {
  16665. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  16666. }
  16667. return sqrDist;
  16668. }
  16669. /**
  16670. * Intersects this ray with the given sphere, returning the intersection
  16671. * point or `null` if there is no intersection.
  16672. *
  16673. * @param {Sphere} sphere - The sphere to intersect.
  16674. * @param {Vector3} target - The target vector that is used to store the method's result.
  16675. * @return {?Vector3} The intersection point.
  16676. */
  16677. intersectSphere( sphere, target ) {
  16678. _vector$7.subVectors( sphere.center, this.origin );
  16679. const tca = _vector$7.dot( this.direction );
  16680. const d2 = _vector$7.dot( _vector$7 ) - tca * tca;
  16681. const radius2 = sphere.radius * sphere.radius;
  16682. if ( d2 > radius2 ) return null;
  16683. const thc = Math.sqrt( radius2 - d2 );
  16684. // t0 = first intersect point - entrance on front of sphere
  16685. const t0 = tca - thc;
  16686. // t1 = second intersect point - exit point on back of sphere
  16687. const t1 = tca + thc;
  16688. // test to see if t1 is behind the ray - if so, return null
  16689. if ( t1 < 0 ) return null;
  16690. // test to see if t0 is behind the ray:
  16691. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  16692. // in order to always return an intersect point that is in front of the ray.
  16693. if ( t0 < 0 ) return this.at( t1, target );
  16694. // else t0 is in front of the ray, so return the first collision point scaled by t0
  16695. return this.at( t0, target );
  16696. }
  16697. /**
  16698. * Returns `true` if this ray intersects with the given sphere.
  16699. *
  16700. * @param {Sphere} sphere - The sphere to intersect.
  16701. * @return {boolean} Whether this ray intersects with the given sphere or not.
  16702. */
  16703. intersectsSphere( sphere ) {
  16704. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  16705. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  16706. }
  16707. /**
  16708. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  16709. * does not intersect with the plane.
  16710. *
  16711. * @param {Plane} plane - The plane to compute the distance to.
  16712. * @return {?number} Whether this ray intersects with the given sphere or not.
  16713. */
  16714. distanceToPlane( plane ) {
  16715. const denominator = plane.normal.dot( this.direction );
  16716. if ( denominator === 0 ) {
  16717. // line is coplanar, return origin
  16718. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  16719. return 0;
  16720. }
  16721. // Null is preferable to undefined since undefined means.... it is undefined
  16722. return null;
  16723. }
  16724. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  16725. // Return if the ray never intersects the plane
  16726. return t >= 0 ? t : null;
  16727. }
  16728. /**
  16729. * Intersects this ray with the given plane, returning the intersection
  16730. * point or `null` if there is no intersection.
  16731. *
  16732. * @param {Plane} plane - The plane to intersect.
  16733. * @param {Vector3} target - The target vector that is used to store the method's result.
  16734. * @return {?Vector3} The intersection point.
  16735. */
  16736. intersectPlane( plane, target ) {
  16737. const t = this.distanceToPlane( plane );
  16738. if ( t === null ) {
  16739. return null;
  16740. }
  16741. return this.at( t, target );
  16742. }
  16743. /**
  16744. * Returns `true` if this ray intersects with the given plane.
  16745. *
  16746. * @param {Plane} plane - The plane to intersect.
  16747. * @return {boolean} Whether this ray intersects with the given plane or not.
  16748. */
  16749. intersectsPlane( plane ) {
  16750. // check if the ray lies on the plane first
  16751. const distToPoint = plane.distanceToPoint( this.origin );
  16752. if ( distToPoint === 0 ) {
  16753. return true;
  16754. }
  16755. const denominator = plane.normal.dot( this.direction );
  16756. if ( denominator * distToPoint < 0 ) {
  16757. return true;
  16758. }
  16759. // ray origin is behind the plane (and is pointing behind it)
  16760. return false;
  16761. }
  16762. /**
  16763. * Intersects this ray with the given bounding box, returning the intersection
  16764. * point or `null` if there is no intersection.
  16765. *
  16766. * @param {Box3} box - The box to intersect.
  16767. * @param {Vector3} target - The target vector that is used to store the method's result.
  16768. * @return {?Vector3} The intersection point.
  16769. */
  16770. intersectBox( box, target ) {
  16771. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  16772. const invdirx = 1 / this.direction.x,
  16773. invdiry = 1 / this.direction.y,
  16774. invdirz = 1 / this.direction.z;
  16775. const origin = this.origin;
  16776. if ( invdirx >= 0 ) {
  16777. tmin = ( box.min.x - origin.x ) * invdirx;
  16778. tmax = ( box.max.x - origin.x ) * invdirx;
  16779. } else {
  16780. tmin = ( box.max.x - origin.x ) * invdirx;
  16781. tmax = ( box.min.x - origin.x ) * invdirx;
  16782. }
  16783. if ( invdiry >= 0 ) {
  16784. tymin = ( box.min.y - origin.y ) * invdiry;
  16785. tymax = ( box.max.y - origin.y ) * invdiry;
  16786. } else {
  16787. tymin = ( box.max.y - origin.y ) * invdiry;
  16788. tymax = ( box.min.y - origin.y ) * invdiry;
  16789. }
  16790. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  16791. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  16792. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  16793. if ( invdirz >= 0 ) {
  16794. tzmin = ( box.min.z - origin.z ) * invdirz;
  16795. tzmax = ( box.max.z - origin.z ) * invdirz;
  16796. } else {
  16797. tzmin = ( box.max.z - origin.z ) * invdirz;
  16798. tzmax = ( box.min.z - origin.z ) * invdirz;
  16799. }
  16800. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  16801. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  16802. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  16803. //return point closest to the ray (positive side)
  16804. if ( tmax < 0 ) return null;
  16805. return this.at( tmin >= 0 ? tmin : tmax, target );
  16806. }
  16807. /**
  16808. * Returns `true` if this ray intersects with the given box.
  16809. *
  16810. * @param {Box3} box - The box to intersect.
  16811. * @return {boolean} Whether this ray intersects with the given box or not.
  16812. */
  16813. intersectsBox( box ) {
  16814. return this.intersectBox( box, _vector$7 ) !== null;
  16815. }
  16816. /**
  16817. * Intersects this ray with the given triangle, returning the intersection
  16818. * point or `null` if there is no intersection.
  16819. *
  16820. * @param {Vector3} a - The first vertex of the triangle.
  16821. * @param {Vector3} b - The second vertex of the triangle.
  16822. * @param {Vector3} c - The third vertex of the triangle.
  16823. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  16824. * @param {Vector3} target - The target vector that is used to store the method's result.
  16825. * @return {?Vector3} The intersection point.
  16826. */
  16827. intersectTriangle( a, b, c, backfaceCulling, target ) {
  16828. // Compute the offset origin, edges, and normal.
  16829. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  16830. _edge1.subVectors( b, a );
  16831. _edge2.subVectors( c, a );
  16832. _normal$1.crossVectors( _edge1, _edge2 );
  16833. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  16834. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  16835. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  16836. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  16837. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  16838. let DdN = this.direction.dot( _normal$1 );
  16839. let sign;
  16840. if ( DdN > 0 ) {
  16841. if ( backfaceCulling ) return null;
  16842. sign = 1;
  16843. } else if ( DdN < 0 ) {
  16844. sign = -1;
  16845. DdN = - DdN;
  16846. } else {
  16847. return null;
  16848. }
  16849. _diff.subVectors( this.origin, a );
  16850. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  16851. // b1 < 0, no intersection
  16852. if ( DdQxE2 < 0 ) {
  16853. return null;
  16854. }
  16855. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  16856. // b2 < 0, no intersection
  16857. if ( DdE1xQ < 0 ) {
  16858. return null;
  16859. }
  16860. // b1+b2 > 1, no intersection
  16861. if ( DdQxE2 + DdE1xQ > DdN ) {
  16862. return null;
  16863. }
  16864. // Line intersects triangle, check if ray does.
  16865. const QdN = - sign * _diff.dot( _normal$1 );
  16866. // t < 0, no intersection
  16867. if ( QdN < 0 ) {
  16868. return null;
  16869. }
  16870. // Ray intersects triangle.
  16871. return this.at( QdN / DdN, target );
  16872. }
  16873. /**
  16874. * Transforms this ray with the given 4x4 transformation matrix.
  16875. *
  16876. * @param {Matrix4} matrix4 - The transformation matrix.
  16877. * @return {Ray} A reference to this ray.
  16878. */
  16879. applyMatrix4( matrix4 ) {
  16880. this.origin.applyMatrix4( matrix4 );
  16881. this.direction.transformDirection( matrix4 );
  16882. return this;
  16883. }
  16884. /**
  16885. * Returns `true` if this ray is equal with the given one.
  16886. *
  16887. * @param {Ray} ray - The ray to test for equality.
  16888. * @return {boolean} Whether this ray is equal with the given one.
  16889. */
  16890. equals( ray ) {
  16891. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  16892. }
  16893. /**
  16894. * Returns a new ray with copied values from this instance.
  16895. *
  16896. * @return {Ray} A clone of this instance.
  16897. */
  16898. clone() {
  16899. return new this.constructor().copy( this );
  16900. }
  16901. }
  16902. /**
  16903. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  16904. *
  16905. * This material is not affected by lights.
  16906. *
  16907. * @augments Material
  16908. * @demo scenes/material-browser.html#MeshBasicMaterial
  16909. */
  16910. class MeshBasicMaterial extends Material {
  16911. /**
  16912. * Constructs a new mesh basic material.
  16913. *
  16914. * @param {Object} [parameters] - An object with one or more properties
  16915. * defining the material's appearance. Any property of the material
  16916. * (including any property from inherited materials) can be passed
  16917. * in here. Color values can be passed any type of value accepted
  16918. * by {@link Color#set}.
  16919. */
  16920. constructor( parameters ) {
  16921. super();
  16922. /**
  16923. * This flag can be used for type testing.
  16924. *
  16925. * @type {boolean}
  16926. * @readonly
  16927. * @default true
  16928. */
  16929. this.isMeshBasicMaterial = true;
  16930. this.type = 'MeshBasicMaterial';
  16931. /**
  16932. * Color of the material.
  16933. *
  16934. * @type {Color}
  16935. * @default (1,1,1)
  16936. */
  16937. this.color = new Color( 0xffffff ); // diffuse
  16938. /**
  16939. * The color map. May optionally include an alpha channel, typically combined
  16940. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  16941. * color is modulated by the diffuse `color`.
  16942. *
  16943. * @type {?Texture}
  16944. * @default null
  16945. */
  16946. this.map = null;
  16947. /**
  16948. * The light map. Requires a second set of UVs.
  16949. *
  16950. * @type {?Texture}
  16951. * @default null
  16952. */
  16953. this.lightMap = null;
  16954. /**
  16955. * Intensity of the baked light.
  16956. *
  16957. * @type {number}
  16958. * @default 1
  16959. */
  16960. this.lightMapIntensity = 1.0;
  16961. /**
  16962. * The red channel of this texture is used as the ambient occlusion map.
  16963. * Requires a second set of UVs.
  16964. *
  16965. * @type {?Texture}
  16966. * @default null
  16967. */
  16968. this.aoMap = null;
  16969. /**
  16970. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  16971. * disables ambient occlusion. Where intensity is `1` and the AO map's
  16972. * red channel is also `1`, ambient light is fully occluded on a surface.
  16973. *
  16974. * @type {number}
  16975. * @default 1
  16976. */
  16977. this.aoMapIntensity = 1.0;
  16978. /**
  16979. * Specular map used by the material.
  16980. *
  16981. * @type {?Texture}
  16982. * @default null
  16983. */
  16984. this.specularMap = null;
  16985. /**
  16986. * The alpha map is a grayscale texture that controls the opacity across the
  16987. * surface (black: fully transparent; white: fully opaque).
  16988. *
  16989. * Only the color of the texture is used, ignoring the alpha channel if one
  16990. * exists. For RGB and RGBA textures, the renderer will use the green channel
  16991. * when sampling this texture due to the extra bit of precision provided for
  16992. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  16993. * luminance/alpha textures will also still work as expected.
  16994. *
  16995. * @type {?Texture}
  16996. * @default null
  16997. */
  16998. this.alphaMap = null;
  16999. /**
  17000. * The environment map.
  17001. *
  17002. * @type {?Texture}
  17003. * @default null
  17004. */
  17005. this.envMap = null;
  17006. /**
  17007. * The rotation of the environment map in radians.
  17008. *
  17009. * @type {Euler}
  17010. * @default (0,0,0)
  17011. */
  17012. this.envMapRotation = new Euler();
  17013. /**
  17014. * How to combine the result of the surface's color with the environment map, if any.
  17015. *
  17016. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  17017. * blend between the two colors.
  17018. *
  17019. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  17020. * @default MultiplyOperation
  17021. */
  17022. this.combine = MultiplyOperation;
  17023. /**
  17024. * How much the environment map affects the surface.
  17025. * The valid range is between `0` (no reflections) and `1` (full reflections).
  17026. *
  17027. * @type {number}
  17028. * @default 1
  17029. */
  17030. this.reflectivity = 1;
  17031. /**
  17032. * The index of refraction (IOR) of air (approximately 1) divided by the
  17033. * index of refraction of the material. It is used with environment mapping
  17034. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  17035. * The refraction ratio should not exceed `1`.
  17036. *
  17037. * @type {number}
  17038. * @default 0.98
  17039. */
  17040. this.refractionRatio = 0.98;
  17041. /**
  17042. * Renders the geometry as a wireframe.
  17043. *
  17044. * @type {boolean}
  17045. * @default false
  17046. */
  17047. this.wireframe = false;
  17048. /**
  17049. * Controls the thickness of the wireframe.
  17050. *
  17051. * Can only be used with {@link SVGRenderer}.
  17052. *
  17053. * @type {number}
  17054. * @default 1
  17055. */
  17056. this.wireframeLinewidth = 1;
  17057. /**
  17058. * Defines appearance of wireframe ends.
  17059. *
  17060. * Can only be used with {@link SVGRenderer}.
  17061. *
  17062. * @type {('round'|'bevel'|'miter')}
  17063. * @default 'round'
  17064. */
  17065. this.wireframeLinecap = 'round';
  17066. /**
  17067. * Defines appearance of wireframe joints.
  17068. *
  17069. * Can only be used with {@link SVGRenderer}.
  17070. *
  17071. * @type {('round'|'bevel'|'miter')}
  17072. * @default 'round'
  17073. */
  17074. this.wireframeLinejoin = 'round';
  17075. /**
  17076. * Whether the material is affected by fog or not.
  17077. *
  17078. * @type {boolean}
  17079. * @default true
  17080. */
  17081. this.fog = true;
  17082. this.setValues( parameters );
  17083. }
  17084. copy( source ) {
  17085. super.copy( source );
  17086. this.color.copy( source.color );
  17087. this.map = source.map;
  17088. this.lightMap = source.lightMap;
  17089. this.lightMapIntensity = source.lightMapIntensity;
  17090. this.aoMap = source.aoMap;
  17091. this.aoMapIntensity = source.aoMapIntensity;
  17092. this.specularMap = source.specularMap;
  17093. this.alphaMap = source.alphaMap;
  17094. this.envMap = source.envMap;
  17095. this.envMapRotation.copy( source.envMapRotation );
  17096. this.combine = source.combine;
  17097. this.reflectivity = source.reflectivity;
  17098. this.refractionRatio = source.refractionRatio;
  17099. this.wireframe = source.wireframe;
  17100. this.wireframeLinewidth = source.wireframeLinewidth;
  17101. this.wireframeLinecap = source.wireframeLinecap;
  17102. this.wireframeLinejoin = source.wireframeLinejoin;
  17103. this.fog = source.fog;
  17104. return this;
  17105. }
  17106. }
  17107. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  17108. const _ray$3 = /*@__PURE__*/ new Ray();
  17109. const _sphere$6 = /*@__PURE__*/ new Sphere();
  17110. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  17111. const _vA = /*@__PURE__*/ new Vector3();
  17112. const _vB = /*@__PURE__*/ new Vector3();
  17113. const _vC = /*@__PURE__*/ new Vector3();
  17114. const _tempA = /*@__PURE__*/ new Vector3();
  17115. const _morphA = /*@__PURE__*/ new Vector3();
  17116. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  17117. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  17118. /**
  17119. * Class representing triangular polygon mesh based objects.
  17120. *
  17121. * ```js
  17122. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  17123. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17124. * const mesh = new THREE.Mesh( geometry, material );
  17125. * scene.add( mesh );
  17126. * ```
  17127. *
  17128. * @augments Object3D
  17129. */
  17130. class Mesh extends Object3D {
  17131. /**
  17132. * Constructs a new mesh.
  17133. *
  17134. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17135. * @param {Material|Array<Material>} [material] - The mesh material.
  17136. */
  17137. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  17138. super();
  17139. /**
  17140. * This flag can be used for type testing.
  17141. *
  17142. * @type {boolean}
  17143. * @readonly
  17144. * @default true
  17145. */
  17146. this.isMesh = true;
  17147. this.type = 'Mesh';
  17148. /**
  17149. * The mesh geometry.
  17150. *
  17151. * @type {BufferGeometry}
  17152. */
  17153. this.geometry = geometry;
  17154. /**
  17155. * The mesh material.
  17156. *
  17157. * @type {Material|Array<Material>}
  17158. * @default MeshBasicMaterial
  17159. */
  17160. this.material = material;
  17161. /**
  17162. * A dictionary representing the morph targets in the geometry. The key is the
  17163. * morph targets name, the value its attribute index. This member is `undefined`
  17164. * by default and only set when morph targets are detected in the geometry.
  17165. *
  17166. * @type {Object<string,number>|undefined}
  17167. * @default undefined
  17168. */
  17169. this.morphTargetDictionary = undefined;
  17170. /**
  17171. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  17172. * is applied. This member is `undefined` by default and only set when morph targets are
  17173. * detected in the geometry.
  17174. *
  17175. * @type {Array<number>|undefined}
  17176. * @default undefined
  17177. */
  17178. this.morphTargetInfluences = undefined;
  17179. /**
  17180. * The number of instances of this mesh.
  17181. * Can only be used with {@link WebGPURenderer}.
  17182. *
  17183. * @type {number}
  17184. * @default 1
  17185. */
  17186. this.count = 1;
  17187. this.updateMorphTargets();
  17188. }
  17189. copy( source, recursive ) {
  17190. super.copy( source, recursive );
  17191. if ( source.morphTargetInfluences !== undefined ) {
  17192. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  17193. }
  17194. if ( source.morphTargetDictionary !== undefined ) {
  17195. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  17196. }
  17197. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  17198. this.geometry = source.geometry;
  17199. return this;
  17200. }
  17201. /**
  17202. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  17203. * to make sure existing morph targets can influence this 3D object.
  17204. */
  17205. updateMorphTargets() {
  17206. const geometry = this.geometry;
  17207. const morphAttributes = geometry.morphAttributes;
  17208. const keys = Object.keys( morphAttributes );
  17209. if ( keys.length > 0 ) {
  17210. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17211. if ( morphAttribute !== undefined ) {
  17212. this.morphTargetInfluences = [];
  17213. this.morphTargetDictionary = {};
  17214. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17215. const name = morphAttribute[ m ].name || String( m );
  17216. this.morphTargetInfluences.push( 0 );
  17217. this.morphTargetDictionary[ name ] = m;
  17218. }
  17219. }
  17220. }
  17221. }
  17222. /**
  17223. * Returns the local-space position of the vertex at the given index, taking into
  17224. * account the current animation state of both morph targets and skinning.
  17225. *
  17226. * @param {number} index - The vertex index.
  17227. * @param {Vector3} target - The target object that is used to store the method's result.
  17228. * @return {Vector3} The vertex position in local space.
  17229. */
  17230. getVertexPosition( index, target ) {
  17231. const geometry = this.geometry;
  17232. const position = geometry.attributes.position;
  17233. const morphPosition = geometry.morphAttributes.position;
  17234. const morphTargetsRelative = geometry.morphTargetsRelative;
  17235. target.fromBufferAttribute( position, index );
  17236. const morphInfluences = this.morphTargetInfluences;
  17237. if ( morphPosition && morphInfluences ) {
  17238. _morphA.set( 0, 0, 0 );
  17239. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  17240. const influence = morphInfluences[ i ];
  17241. const morphAttribute = morphPosition[ i ];
  17242. if ( influence === 0 ) continue;
  17243. _tempA.fromBufferAttribute( morphAttribute, index );
  17244. if ( morphTargetsRelative ) {
  17245. _morphA.addScaledVector( _tempA, influence );
  17246. } else {
  17247. _morphA.addScaledVector( _tempA.sub( target ), influence );
  17248. }
  17249. }
  17250. target.add( _morphA );
  17251. }
  17252. return target;
  17253. }
  17254. /**
  17255. * Computes intersection points between a casted ray and this line.
  17256. *
  17257. * @param {Raycaster} raycaster - The raycaster.
  17258. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17259. */
  17260. raycast( raycaster, intersects ) {
  17261. const geometry = this.geometry;
  17262. const material = this.material;
  17263. const matrixWorld = this.matrixWorld;
  17264. if ( material === undefined ) return;
  17265. // test with bounding sphere in world space
  17266. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17267. _sphere$6.copy( geometry.boundingSphere );
  17268. _sphere$6.applyMatrix4( matrixWorld );
  17269. // check distance from ray origin to bounding sphere
  17270. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  17271. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  17272. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  17273. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  17274. }
  17275. // convert ray to local space of mesh
  17276. _inverseMatrix$3.copy( matrixWorld ).invert();
  17277. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  17278. // test with bounding box in local space
  17279. if ( geometry.boundingBox !== null ) {
  17280. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  17281. }
  17282. // test for intersections with geometry
  17283. this._computeIntersections( raycaster, intersects, _ray$3 );
  17284. }
  17285. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  17286. let intersection;
  17287. const geometry = this.geometry;
  17288. const material = this.material;
  17289. const index = geometry.index;
  17290. const position = geometry.attributes.position;
  17291. const uv = geometry.attributes.uv;
  17292. const uv1 = geometry.attributes.uv1;
  17293. const normal = geometry.attributes.normal;
  17294. const groups = geometry.groups;
  17295. const drawRange = geometry.drawRange;
  17296. if ( index !== null ) {
  17297. // indexed buffer geometry
  17298. if ( Array.isArray( material ) ) {
  17299. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17300. const group = groups[ i ];
  17301. const groupMaterial = material[ group.materialIndex ];
  17302. const start = Math.max( group.start, drawRange.start );
  17303. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17304. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17305. const a = index.getX( j );
  17306. const b = index.getX( j + 1 );
  17307. const c = index.getX( j + 2 );
  17308. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17309. if ( intersection ) {
  17310. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  17311. intersection.face.materialIndex = group.materialIndex;
  17312. intersects.push( intersection );
  17313. }
  17314. }
  17315. }
  17316. } else {
  17317. const start = Math.max( 0, drawRange.start );
  17318. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17319. for ( let i = start, il = end; i < il; i += 3 ) {
  17320. const a = index.getX( i );
  17321. const b = index.getX( i + 1 );
  17322. const c = index.getX( i + 2 );
  17323. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17324. if ( intersection ) {
  17325. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  17326. intersects.push( intersection );
  17327. }
  17328. }
  17329. }
  17330. } else if ( position !== undefined ) {
  17331. // non-indexed buffer geometry
  17332. if ( Array.isArray( material ) ) {
  17333. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17334. const group = groups[ i ];
  17335. const groupMaterial = material[ group.materialIndex ];
  17336. const start = Math.max( group.start, drawRange.start );
  17337. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17338. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17339. const a = j;
  17340. const b = j + 1;
  17341. const c = j + 2;
  17342. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17343. if ( intersection ) {
  17344. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  17345. intersection.face.materialIndex = group.materialIndex;
  17346. intersects.push( intersection );
  17347. }
  17348. }
  17349. }
  17350. } else {
  17351. const start = Math.max( 0, drawRange.start );
  17352. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  17353. for ( let i = start, il = end; i < il; i += 3 ) {
  17354. const a = i;
  17355. const b = i + 1;
  17356. const c = i + 2;
  17357. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17358. if ( intersection ) {
  17359. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  17360. intersects.push( intersection );
  17361. }
  17362. }
  17363. }
  17364. }
  17365. }
  17366. }
  17367. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  17368. let intersect;
  17369. if ( material.side === BackSide ) {
  17370. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  17371. } else {
  17372. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  17373. }
  17374. if ( intersect === null ) return null;
  17375. _intersectionPointWorld.copy( point );
  17376. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  17377. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  17378. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  17379. return {
  17380. distance: distance,
  17381. point: _intersectionPointWorld.clone(),
  17382. object: object
  17383. };
  17384. }
  17385. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  17386. object.getVertexPosition( a, _vA );
  17387. object.getVertexPosition( b, _vB );
  17388. object.getVertexPosition( c, _vC );
  17389. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  17390. if ( intersection ) {
  17391. const barycoord = new Vector3();
  17392. Triangle.getBarycoord( _intersectionPoint, _vA, _vB, _vC, barycoord );
  17393. if ( uv ) {
  17394. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  17395. }
  17396. if ( uv1 ) {
  17397. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  17398. }
  17399. if ( normal ) {
  17400. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  17401. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  17402. intersection.normal.multiplyScalar( -1 );
  17403. }
  17404. }
  17405. const face = {
  17406. a: a,
  17407. b: b,
  17408. c: c,
  17409. normal: new Vector3(),
  17410. materialIndex: 0
  17411. };
  17412. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  17413. intersection.face = face;
  17414. intersection.barycoord = barycoord;
  17415. }
  17416. return intersection;
  17417. }
  17418. const _baseVector = /*@__PURE__*/ new Vector4();
  17419. const _skinIndex = /*@__PURE__*/ new Vector4();
  17420. const _skinWeight = /*@__PURE__*/ new Vector4();
  17421. const _vector4 = /*@__PURE__*/ new Vector4();
  17422. const _matrix4 = /*@__PURE__*/ new Matrix4();
  17423. const _vertex = /*@__PURE__*/ new Vector3();
  17424. const _sphere$5 = /*@__PURE__*/ new Sphere();
  17425. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  17426. const _ray$2 = /*@__PURE__*/ new Ray();
  17427. /**
  17428. * A mesh that has a {@link Skeleton} that can then be used to animate the
  17429. * vertices of the geometry with skinning/skeleton animation.
  17430. *
  17431. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  17432. * as buffer attributes in its geometry. These attribute define which bones affect a single
  17433. * vertex to a certain extend.
  17434. *
  17435. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  17436. * or {@link FBXLoader } import respective models.
  17437. *
  17438. * @augments Mesh
  17439. * @demo scenes/bones-browser.html
  17440. */
  17441. class SkinnedMesh extends Mesh {
  17442. /**
  17443. * Constructs a new skinned mesh.
  17444. *
  17445. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17446. * @param {Material|Array<Material>} [material] - The mesh material.
  17447. */
  17448. constructor( geometry, material ) {
  17449. super( geometry, material );
  17450. /**
  17451. * This flag can be used for type testing.
  17452. *
  17453. * @type {boolean}
  17454. * @readonly
  17455. * @default true
  17456. */
  17457. this.isSkinnedMesh = true;
  17458. this.type = 'SkinnedMesh';
  17459. /**
  17460. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  17461. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  17462. * across multiple skinned meshes.
  17463. *
  17464. * @type {(AttachedBindMode|DetachedBindMode)}
  17465. * @default AttachedBindMode
  17466. */
  17467. this.bindMode = AttachedBindMode;
  17468. /**
  17469. * The base matrix that is used for the bound bone transforms.
  17470. *
  17471. * @type {Matrix4}
  17472. */
  17473. this.bindMatrix = new Matrix4();
  17474. /**
  17475. * The base matrix that is used for resetting the bound bone transforms.
  17476. *
  17477. * @type {Matrix4}
  17478. */
  17479. this.bindMatrixInverse = new Matrix4();
  17480. /**
  17481. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  17482. *
  17483. * @type {?Box3}
  17484. * @default null
  17485. */
  17486. this.boundingBox = null;
  17487. /**
  17488. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  17489. *
  17490. * @type {?Sphere}
  17491. * @default null
  17492. */
  17493. this.boundingSphere = null;
  17494. }
  17495. /**
  17496. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  17497. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  17498. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  17499. * the current animation state.
  17500. */
  17501. computeBoundingBox() {
  17502. const geometry = this.geometry;
  17503. if ( this.boundingBox === null ) {
  17504. this.boundingBox = new Box3();
  17505. }
  17506. this.boundingBox.makeEmpty();
  17507. const positionAttribute = geometry.getAttribute( 'position' );
  17508. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17509. this.getVertexPosition( i, _vertex );
  17510. this.boundingBox.expandByPoint( _vertex );
  17511. }
  17512. }
  17513. /**
  17514. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  17515. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  17516. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  17517. * per frame in order to reflect the current animation state.
  17518. */
  17519. computeBoundingSphere() {
  17520. const geometry = this.geometry;
  17521. if ( this.boundingSphere === null ) {
  17522. this.boundingSphere = new Sphere();
  17523. }
  17524. this.boundingSphere.makeEmpty();
  17525. const positionAttribute = geometry.getAttribute( 'position' );
  17526. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17527. this.getVertexPosition( i, _vertex );
  17528. this.boundingSphere.expandByPoint( _vertex );
  17529. }
  17530. }
  17531. copy( source, recursive ) {
  17532. super.copy( source, recursive );
  17533. this.bindMode = source.bindMode;
  17534. this.bindMatrix.copy( source.bindMatrix );
  17535. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17536. this.skeleton = source.skeleton;
  17537. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  17538. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  17539. return this;
  17540. }
  17541. raycast( raycaster, intersects ) {
  17542. const material = this.material;
  17543. const matrixWorld = this.matrixWorld;
  17544. if ( material === undefined ) return;
  17545. // test with bounding sphere in world space
  17546. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  17547. _sphere$5.copy( this.boundingSphere );
  17548. _sphere$5.applyMatrix4( matrixWorld );
  17549. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  17550. // convert ray to local space of skinned mesh
  17551. _inverseMatrix$2.copy( matrixWorld ).invert();
  17552. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  17553. // test with bounding box in local space
  17554. if ( this.boundingBox !== null ) {
  17555. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  17556. }
  17557. // test for intersections with geometry
  17558. this._computeIntersections( raycaster, intersects, _ray$2 );
  17559. }
  17560. getVertexPosition( index, target ) {
  17561. super.getVertexPosition( index, target );
  17562. this.applyBoneTransform( index, target );
  17563. return target;
  17564. }
  17565. /**
  17566. * Binds the given skeleton to the skinned mesh.
  17567. *
  17568. * @param {Skeleton} skeleton - The skeleton to bind.
  17569. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  17570. * the skinned mesh's world matrix will be used instead.
  17571. */
  17572. bind( skeleton, bindMatrix ) {
  17573. this.skeleton = skeleton;
  17574. if ( bindMatrix === undefined ) {
  17575. this.updateMatrixWorld( true );
  17576. this.skeleton.calculateInverses();
  17577. bindMatrix = this.matrixWorld;
  17578. }
  17579. this.bindMatrix.copy( bindMatrix );
  17580. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17581. }
  17582. /**
  17583. * This method sets the skinned mesh in the rest pose).
  17584. */
  17585. pose() {
  17586. this.skeleton.pose();
  17587. }
  17588. /**
  17589. * Normalizes the skin weights which are defined as a buffer attribute
  17590. * in the skinned mesh's geometry.
  17591. */
  17592. normalizeSkinWeights() {
  17593. const vector = new Vector4();
  17594. const skinWeight = this.geometry.attributes.skinWeight;
  17595. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17596. vector.fromBufferAttribute( skinWeight, i );
  17597. const scale = 1.0 / vector.manhattanLength();
  17598. if ( scale !== Infinity ) {
  17599. vector.multiplyScalar( scale );
  17600. } else {
  17601. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17602. }
  17603. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17604. }
  17605. }
  17606. updateMatrixWorld( force ) {
  17607. super.updateMatrixWorld( force );
  17608. if ( this.bindMode === AttachedBindMode ) {
  17609. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17610. } else if ( this.bindMode === DetachedBindMode ) {
  17611. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17612. } else {
  17613. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17614. }
  17615. }
  17616. /**
  17617. * Applies the bone transform associated with the given index to the given
  17618. * vector. Can be used to transform positions or direction vectors by providing
  17619. * a Vector4 with 1 or 0 in the w component respectively. Returns the updated vector.
  17620. *
  17621. * @param {number} index - The vertex index.
  17622. * @param {Vector3|Vector4} target - The target object that is used to store the method's result.
  17623. * @return {Vector3|Vector4} The updated vertex attribute data.
  17624. */
  17625. applyBoneTransform( index, target ) {
  17626. const skeleton = this.skeleton;
  17627. const geometry = this.geometry;
  17628. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17629. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17630. if ( target.isVector4 ) {
  17631. _baseVector.copy( target );
  17632. target.set( 0, 0, 0, 0 );
  17633. } else {
  17634. _baseVector.set( ...target, 1 );
  17635. target.set( 0, 0, 0 );
  17636. }
  17637. _baseVector.applyMatrix4( this.bindMatrix );
  17638. for ( let i = 0; i < 4; i ++ ) {
  17639. const weight = _skinWeight.getComponent( i );
  17640. if ( weight !== 0 ) {
  17641. const boneIndex = _skinIndex.getComponent( i );
  17642. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17643. target.addScaledVector( _vector4.copy( _baseVector ).applyMatrix4( _matrix4 ), weight );
  17644. }
  17645. }
  17646. if ( target.isVector4 ) {
  17647. // ensure the homogenous coordinate remains unchanged after vector operations
  17648. target.w = _baseVector.w;
  17649. }
  17650. return target.applyMatrix4( this.bindMatrixInverse );
  17651. }
  17652. }
  17653. /**
  17654. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  17655. * the {@link SkinnedMesh}.
  17656. *
  17657. * ```js
  17658. * const root = new THREE.Bone();
  17659. * const child = new THREE.Bone();
  17660. *
  17661. * root.add( child );
  17662. * child.position.y = 5;
  17663. * ```
  17664. *
  17665. * @augments Object3D
  17666. */
  17667. class Bone extends Object3D {
  17668. /**
  17669. * Constructs a new bone.
  17670. */
  17671. constructor() {
  17672. super();
  17673. /**
  17674. * This flag can be used for type testing.
  17675. *
  17676. * @type {boolean}
  17677. * @readonly
  17678. * @default true
  17679. */
  17680. this.isBone = true;
  17681. this.type = 'Bone';
  17682. }
  17683. }
  17684. /**
  17685. * Creates a texture directly from raw buffer data.
  17686. *
  17687. * The interpretation of the data depends on type and format: If the type is
  17688. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  17689. * texel data. If the format is `RGBAFormat`, data needs four values for
  17690. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  17691. *
  17692. * @augments Texture
  17693. */
  17694. class DataTexture extends Texture {
  17695. /**
  17696. * Constructs a new data texture.
  17697. *
  17698. * @param {?TypedArray} [data=null] - The buffer data.
  17699. * @param {number} [width=1] - The width of the texture.
  17700. * @param {number} [height=1] - The height of the texture.
  17701. * @param {number} [format=RGBAFormat] - The texture format.
  17702. * @param {number} [type=UnsignedByteType] - The texture type.
  17703. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  17704. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  17705. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  17706. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  17707. * @param {number} [minFilter=NearestFilter] - The min filter value.
  17708. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  17709. * @param {string} [colorSpace=NoColorSpace] - The color space.
  17710. */
  17711. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  17712. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  17713. /**
  17714. * This flag can be used for type testing.
  17715. *
  17716. * @type {boolean}
  17717. * @readonly
  17718. * @default true
  17719. */
  17720. this.isDataTexture = true;
  17721. /**
  17722. * The image definition of a data texture.
  17723. *
  17724. * @type {{data:TypedArray,width:number,height:number}}
  17725. */
  17726. this.image = { data: data, width: width, height: height };
  17727. /**
  17728. * Whether to generate mipmaps (if possible) for a texture.
  17729. *
  17730. * Overwritten and set to `false` by default.
  17731. *
  17732. * @type {boolean}
  17733. * @default false
  17734. */
  17735. this.generateMipmaps = false;
  17736. /**
  17737. * If set to `true`, the texture is flipped along the vertical axis when
  17738. * uploaded to the GPU.
  17739. *
  17740. * Overwritten and set to `false` by default.
  17741. *
  17742. * @type {boolean}
  17743. * @default false
  17744. */
  17745. this.flipY = false;
  17746. /**
  17747. * Specifies the alignment requirements for the start of each pixel row in memory.
  17748. *
  17749. * Overwritten and set to `1` by default.
  17750. *
  17751. * @type {boolean}
  17752. * @default 1
  17753. */
  17754. this.unpackAlignment = 1;
  17755. }
  17756. }
  17757. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17758. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17759. /**
  17760. * Class for representing the armatures in `three.js`. The skeleton
  17761. * is defined by a hierarchy of bones.
  17762. *
  17763. * ```js
  17764. * const bones = [];
  17765. *
  17766. * const shoulder = new THREE.Bone();
  17767. * const elbow = new THREE.Bone();
  17768. * const hand = new THREE.Bone();
  17769. *
  17770. * shoulder.add( elbow );
  17771. * elbow.add( hand );
  17772. *
  17773. * bones.push( shoulder , elbow, hand);
  17774. *
  17775. * shoulder.position.y = -5;
  17776. * elbow.position.y = 0;
  17777. * hand.position.y = 5;
  17778. *
  17779. * const armSkeleton = new THREE.Skeleton( bones );
  17780. * ```
  17781. */
  17782. class Skeleton {
  17783. /**
  17784. * Constructs a new skeleton.
  17785. *
  17786. * @param {Array<Bone>} [bones] - An array of bones.
  17787. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  17788. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  17789. */
  17790. constructor( bones = [], boneInverses = [] ) {
  17791. this.uuid = generateUUID();
  17792. /**
  17793. * An array of bones defining the skeleton.
  17794. *
  17795. * @type {Array<Bone>}
  17796. */
  17797. this.bones = bones.slice( 0 );
  17798. /**
  17799. * An array of bone inverse matrices.
  17800. *
  17801. * @type {Array<Matrix4>}
  17802. */
  17803. this.boneInverses = boneInverses;
  17804. /**
  17805. * An array buffer holding the bone data.
  17806. * Input data for {@link Skeleton#boneTexture}.
  17807. *
  17808. * @type {?Float32Array}
  17809. * @default null
  17810. */
  17811. this.boneMatrices = null;
  17812. /**
  17813. * An array buffer holding the bone data of the previous frame.
  17814. * Required for computing velocity. Maintained in {@link SkinningNode}.
  17815. *
  17816. * @type {?Float32Array}
  17817. * @default null
  17818. */
  17819. this.previousBoneMatrices = null;
  17820. /**
  17821. * A texture holding the bone data for use
  17822. * in the vertex shader.
  17823. *
  17824. * @type {?DataTexture}
  17825. * @default null
  17826. */
  17827. this.boneTexture = null;
  17828. this.init();
  17829. }
  17830. /**
  17831. * Initializes the skeleton. This method gets automatically called by the constructor
  17832. * but depending on how the skeleton is created it might be necessary to call this method
  17833. * manually.
  17834. */
  17835. init() {
  17836. const bones = this.bones;
  17837. const boneInverses = this.boneInverses;
  17838. this.boneMatrices = new Float32Array( bones.length * 16 );
  17839. // calculate inverse bone matrices if necessary
  17840. if ( boneInverses.length === 0 ) {
  17841. this.calculateInverses();
  17842. } else {
  17843. // handle special case
  17844. if ( bones.length !== boneInverses.length ) {
  17845. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  17846. this.boneInverses = [];
  17847. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17848. this.boneInverses.push( new Matrix4() );
  17849. }
  17850. }
  17851. }
  17852. }
  17853. /**
  17854. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  17855. * and fills it with new matrices.
  17856. */
  17857. calculateInverses() {
  17858. this.boneInverses.length = 0;
  17859. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17860. const inverse = new Matrix4();
  17861. if ( this.bones[ i ] ) {
  17862. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  17863. }
  17864. this.boneInverses.push( inverse );
  17865. }
  17866. }
  17867. /**
  17868. * Resets the skeleton to the base pose.
  17869. */
  17870. pose() {
  17871. // recover the bind-time world matrices
  17872. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17873. const bone = this.bones[ i ];
  17874. if ( bone ) {
  17875. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17876. }
  17877. }
  17878. // compute the local matrices, positions, rotations and scales
  17879. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17880. const bone = this.bones[ i ];
  17881. if ( bone ) {
  17882. if ( bone.parent && bone.parent.isBone ) {
  17883. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17884. bone.matrix.multiply( bone.matrixWorld );
  17885. } else {
  17886. bone.matrix.copy( bone.matrixWorld );
  17887. }
  17888. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17889. }
  17890. }
  17891. }
  17892. /**
  17893. * Resets the skeleton to the base pose.
  17894. */
  17895. update() {
  17896. const bones = this.bones;
  17897. const boneInverses = this.boneInverses;
  17898. const boneMatrices = this.boneMatrices;
  17899. const boneTexture = this.boneTexture;
  17900. // flatten bone matrices to array
  17901. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17902. // compute the offset between the current and the original transform
  17903. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17904. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17905. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17906. }
  17907. if ( boneTexture !== null ) {
  17908. boneTexture.needsUpdate = true;
  17909. }
  17910. }
  17911. /**
  17912. * Returns a new skeleton with copied values from this instance.
  17913. *
  17914. * @return {Skeleton} A clone of this instance.
  17915. */
  17916. clone() {
  17917. return new Skeleton( this.bones, this.boneInverses );
  17918. }
  17919. /**
  17920. * Computes a data texture for passing bone data to the vertex shader.
  17921. *
  17922. * @return {Skeleton} A reference of this instance.
  17923. */
  17924. computeBoneTexture() {
  17925. // layout (1 matrix = 4 pixels)
  17926. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17927. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17928. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17929. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17930. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17931. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17932. size = Math.ceil( size / 4 ) * 4;
  17933. size = Math.max( size, 4 );
  17934. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17935. boneMatrices.set( this.boneMatrices ); // copy current values
  17936. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17937. boneTexture.needsUpdate = true;
  17938. this.boneMatrices = boneMatrices;
  17939. this.boneTexture = boneTexture;
  17940. return this;
  17941. }
  17942. /**
  17943. * Searches through the skeleton's bone array and returns the first with a
  17944. * matching name.
  17945. *
  17946. * @param {string} name - The name of the bone.
  17947. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  17948. */
  17949. getBoneByName( name ) {
  17950. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17951. const bone = this.bones[ i ];
  17952. if ( bone.name === name ) {
  17953. return bone;
  17954. }
  17955. }
  17956. return undefined;
  17957. }
  17958. /**
  17959. * Frees the GPU-related resources allocated by this instance. Call this
  17960. * method whenever this instance is no longer used in your app.
  17961. */
  17962. dispose( ) {
  17963. if ( this.boneTexture !== null ) {
  17964. this.boneTexture.dispose();
  17965. this.boneTexture = null;
  17966. }
  17967. }
  17968. /**
  17969. * Setups the skeleton by the given JSON and bones.
  17970. *
  17971. * @param {Object} json - The skeleton as serialized JSON.
  17972. * @param {Object<string, Bone>} bones - An array of bones.
  17973. * @return {Skeleton} A reference of this instance.
  17974. */
  17975. fromJSON( json, bones ) {
  17976. this.uuid = json.uuid;
  17977. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17978. const uuid = json.bones[ i ];
  17979. let bone = bones[ uuid ];
  17980. if ( bone === undefined ) {
  17981. warn( 'Skeleton: No bone found with UUID:', uuid );
  17982. bone = new Bone();
  17983. }
  17984. this.bones.push( bone );
  17985. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17986. }
  17987. this.init();
  17988. return this;
  17989. }
  17990. /**
  17991. * Serializes the skeleton into JSON.
  17992. *
  17993. * @return {Object} A JSON object representing the serialized skeleton.
  17994. * @see {@link ObjectLoader#parse}
  17995. */
  17996. toJSON() {
  17997. const data = {
  17998. metadata: {
  17999. version: 4.7,
  18000. type: 'Skeleton',
  18001. generator: 'Skeleton.toJSON'
  18002. },
  18003. bones: [],
  18004. boneInverses: []
  18005. };
  18006. data.uuid = this.uuid;
  18007. const bones = this.bones;
  18008. const boneInverses = this.boneInverses;
  18009. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18010. const bone = bones[ i ];
  18011. data.bones.push( bone.uuid );
  18012. const boneInverse = boneInverses[ i ];
  18013. data.boneInverses.push( boneInverse.toArray() );
  18014. }
  18015. return data;
  18016. }
  18017. }
  18018. /**
  18019. * An instanced version of a buffer attribute.
  18020. *
  18021. * @augments BufferAttribute
  18022. */
  18023. class InstancedBufferAttribute extends BufferAttribute {
  18024. /**
  18025. * Constructs a new instanced buffer attribute.
  18026. *
  18027. * @param {TypedArray} array - The array holding the attribute data.
  18028. * @param {number} itemSize - The item size.
  18029. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18030. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18031. */
  18032. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18033. super( array, itemSize, normalized );
  18034. /**
  18035. * This flag can be used for type testing.
  18036. *
  18037. * @type {boolean}
  18038. * @readonly
  18039. * @default true
  18040. */
  18041. this.isInstancedBufferAttribute = true;
  18042. /**
  18043. * Defines how often a value of this buffer attribute should be repeated. A
  18044. * value of one means that each value of the instanced attribute is used for
  18045. * a single instance. A value of two means that each value is used for two
  18046. * consecutive instances (and so on).
  18047. *
  18048. * @type {number}
  18049. * @default 1
  18050. */
  18051. this.meshPerAttribute = meshPerAttribute;
  18052. }
  18053. copy( source ) {
  18054. super.copy( source );
  18055. this.meshPerAttribute = source.meshPerAttribute;
  18056. return this;
  18057. }
  18058. toJSON() {
  18059. const data = super.toJSON();
  18060. data.meshPerAttribute = this.meshPerAttribute;
  18061. data.isInstancedBufferAttribute = true;
  18062. return data;
  18063. }
  18064. }
  18065. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18066. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18067. const _instanceIntersects = [];
  18068. const _box3 = /*@__PURE__*/ new Box3();
  18069. const _identity = /*@__PURE__*/ new Matrix4();
  18070. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18071. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18072. /**
  18073. * A special version of a mesh with instanced rendering support. Use
  18074. * this class if you have to render a large number of objects with the same
  18075. * geometry and material(s) but with different world transformations. The usage
  18076. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18077. * improve the overall rendering performance in your application.
  18078. *
  18079. * @augments Mesh
  18080. */
  18081. class InstancedMesh extends Mesh {
  18082. /**
  18083. * Constructs a new instanced mesh.
  18084. *
  18085. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18086. * @param {Material|Array<Material>} [material] - The mesh material.
  18087. * @param {number} count - The number of instances.
  18088. */
  18089. constructor( geometry, material, count ) {
  18090. super( geometry, material );
  18091. /**
  18092. * This flag can be used for type testing.
  18093. *
  18094. * @type {boolean}
  18095. * @readonly
  18096. * @default true
  18097. */
  18098. this.isInstancedMesh = true;
  18099. /**
  18100. * Represents the local transformation of all instances. You have to set its
  18101. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18102. * via {@link InstancedMesh#setMatrixAt}.
  18103. *
  18104. * @type {InstancedBufferAttribute}
  18105. */
  18106. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18107. /**
  18108. * Represents the local transformation of all instances of the previous frame.
  18109. * Required for computing velocity. Maintained in {@link InstanceNode}.
  18110. *
  18111. * @type {?InstancedBufferAttribute}
  18112. * @default null
  18113. */
  18114. this.previousInstanceMatrix = null;
  18115. /**
  18116. * Represents the color of all instances. You have to set its
  18117. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18118. * via {@link InstancedMesh#setColorAt}.
  18119. *
  18120. * @type {?InstancedBufferAttribute}
  18121. * @default null
  18122. */
  18123. this.instanceColor = null;
  18124. /**
  18125. * Represents the morph target weights of all instances. You have to set its
  18126. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18127. * via {@link InstancedMesh#setMorphAt}.
  18128. *
  18129. * @type {?DataTexture}
  18130. * @default null
  18131. */
  18132. this.morphTexture = null;
  18133. /**
  18134. * The number of instances.
  18135. *
  18136. * @type {number}
  18137. */
  18138. this.count = count;
  18139. /**
  18140. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18141. *
  18142. * @type {?Box3}
  18143. * @default null
  18144. */
  18145. this.boundingBox = null;
  18146. /**
  18147. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18148. *
  18149. * @type {?Sphere}
  18150. * @default null
  18151. */
  18152. this.boundingSphere = null;
  18153. for ( let i = 0; i < count; i ++ ) {
  18154. this.setMatrixAt( i, _identity );
  18155. }
  18156. }
  18157. /**
  18158. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18159. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18160. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18161. */
  18162. computeBoundingBox() {
  18163. const geometry = this.geometry;
  18164. const count = this.count;
  18165. if ( this.boundingBox === null ) {
  18166. this.boundingBox = new Box3();
  18167. }
  18168. if ( geometry.boundingBox === null ) {
  18169. geometry.computeBoundingBox();
  18170. }
  18171. this.boundingBox.makeEmpty();
  18172. for ( let i = 0; i < count; i ++ ) {
  18173. this.getMatrixAt( i, _instanceLocalMatrix );
  18174. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18175. this.boundingBox.union( _box3 );
  18176. }
  18177. }
  18178. /**
  18179. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18180. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18181. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18182. */
  18183. computeBoundingSphere() {
  18184. const geometry = this.geometry;
  18185. const count = this.count;
  18186. if ( this.boundingSphere === null ) {
  18187. this.boundingSphere = new Sphere();
  18188. }
  18189. if ( geometry.boundingSphere === null ) {
  18190. geometry.computeBoundingSphere();
  18191. }
  18192. this.boundingSphere.makeEmpty();
  18193. for ( let i = 0; i < count; i ++ ) {
  18194. this.getMatrixAt( i, _instanceLocalMatrix );
  18195. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18196. this.boundingSphere.union( _sphere$4 );
  18197. }
  18198. }
  18199. copy( source, recursive ) {
  18200. super.copy( source, recursive );
  18201. this.instanceMatrix.copy( source.instanceMatrix );
  18202. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  18203. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18204. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18205. this.count = source.count;
  18206. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18207. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18208. return this;
  18209. }
  18210. /**
  18211. * Gets the color of the defined instance.
  18212. *
  18213. * @param {number} index - The instance index.
  18214. * @param {Color} color - The target object that is used to store the method's result.
  18215. * @return {Color} A reference to the target color.
  18216. */
  18217. getColorAt( index, color ) {
  18218. if ( this.instanceColor === null ) {
  18219. return color.setRGB( 1, 1, 1 );
  18220. } else {
  18221. return color.fromArray( this.instanceColor.array, index * 3 );
  18222. }
  18223. }
  18224. /**
  18225. * Gets the local transformation matrix of the defined instance.
  18226. *
  18227. * @param {number} index - The instance index.
  18228. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18229. * @return {Matrix4} A reference to the target matrix.
  18230. */
  18231. getMatrixAt( index, matrix ) {
  18232. return matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18233. }
  18234. /**
  18235. * Gets the morph target weights of the defined instance.
  18236. *
  18237. * @param {number} index - The instance index.
  18238. * @param {Mesh} object - The target object that is used to store the method's result.
  18239. */
  18240. getMorphAt( index, object ) {
  18241. const objectInfluences = object.morphTargetInfluences;
  18242. const array = this.morphTexture.source.data.data;
  18243. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18244. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18245. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18246. objectInfluences[ i ] = array[ dataIndex + i ];
  18247. }
  18248. }
  18249. raycast( raycaster, intersects ) {
  18250. const matrixWorld = this.matrixWorld;
  18251. const raycastTimes = this.count;
  18252. _mesh$1.geometry = this.geometry;
  18253. _mesh$1.material = this.material;
  18254. if ( _mesh$1.material === undefined ) return;
  18255. // test with bounding sphere first
  18256. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18257. _sphere$4.copy( this.boundingSphere );
  18258. _sphere$4.applyMatrix4( matrixWorld );
  18259. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18260. // now test each instance
  18261. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18262. // calculate the world matrix for each instance
  18263. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18264. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18265. // the mesh represents this single instance
  18266. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18267. _mesh$1.raycast( raycaster, _instanceIntersects );
  18268. // process the result of raycast
  18269. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18270. const intersect = _instanceIntersects[ i ];
  18271. intersect.instanceId = instanceId;
  18272. intersect.object = this;
  18273. intersects.push( intersect );
  18274. }
  18275. _instanceIntersects.length = 0;
  18276. }
  18277. }
  18278. /**
  18279. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18280. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18281. *
  18282. * @param {number} index - The instance index.
  18283. * @param {Color} color - The instance color.
  18284. * @return {InstancedMesh} A reference to this instanced mesh.
  18285. */
  18286. setColorAt( index, color ) {
  18287. if ( this.instanceColor === null ) {
  18288. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18289. }
  18290. color.toArray( this.instanceColor.array, index * 3 );
  18291. return this;
  18292. }
  18293. /**
  18294. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18295. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the matrices.
  18296. *
  18297. * @param {number} index - The instance index.
  18298. * @param {Matrix4} matrix - The local transformation.
  18299. * @return {InstancedMesh} A reference to this instanced mesh.
  18300. */
  18301. setMatrixAt( index, matrix ) {
  18302. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18303. return this;
  18304. }
  18305. /**
  18306. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18307. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18308. *
  18309. * @param {number} index - The instance index.
  18310. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18311. * of a single instance.
  18312. * @return {InstancedMesh} A reference to this instanced mesh.
  18313. */
  18314. setMorphAt( index, object ) {
  18315. const objectInfluences = object.morphTargetInfluences;
  18316. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18317. if ( this.morphTexture === null ) {
  18318. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18319. }
  18320. const array = this.morphTexture.source.data.data;
  18321. let morphInfluencesSum = 0;
  18322. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18323. morphInfluencesSum += objectInfluences[ i ];
  18324. }
  18325. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18326. const dataIndex = len * index;
  18327. array[ dataIndex ] = morphBaseInfluence;
  18328. array.set( objectInfluences, dataIndex + 1 );
  18329. return this;
  18330. }
  18331. updateMorphTargets() {
  18332. }
  18333. /**
  18334. * Frees the GPU-related resources allocated by this instance. Call this
  18335. * method whenever this instance is no longer used in your app.
  18336. */
  18337. dispose() {
  18338. this.dispatchEvent( { type: 'dispose' } );
  18339. if ( this.morphTexture !== null ) {
  18340. this.morphTexture.dispose();
  18341. this.morphTexture = null;
  18342. }
  18343. }
  18344. }
  18345. const _vector1 = /*@__PURE__*/ new Vector3();
  18346. const _vector2 = /*@__PURE__*/ new Vector3();
  18347. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  18348. /**
  18349. * A two dimensional surface that extends infinitely in 3D space, represented
  18350. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  18351. * by a unit length normal vector and a constant.
  18352. */
  18353. class Plane {
  18354. /**
  18355. * Constructs a new plane.
  18356. *
  18357. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  18358. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  18359. */
  18360. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  18361. /**
  18362. * This flag can be used for type testing.
  18363. *
  18364. * @type {boolean}
  18365. * @readonly
  18366. * @default true
  18367. */
  18368. this.isPlane = true;
  18369. /**
  18370. * A unit length vector defining the normal of the plane.
  18371. *
  18372. * @type {Vector3}
  18373. */
  18374. this.normal = normal;
  18375. /**
  18376. * The signed distance from the origin to the plane.
  18377. *
  18378. * @type {number}
  18379. * @default 0
  18380. */
  18381. this.constant = constant;
  18382. }
  18383. /**
  18384. * Sets the plane components by copying the given values.
  18385. *
  18386. * @param {Vector3} normal - The normal.
  18387. * @param {number} constant - The constant.
  18388. * @return {Plane} A reference to this plane.
  18389. */
  18390. set( normal, constant ) {
  18391. this.normal.copy( normal );
  18392. this.constant = constant;
  18393. return this;
  18394. }
  18395. /**
  18396. * Sets the plane components by defining `x`, `y`, `z` as the
  18397. * plane normal and `w` as the constant.
  18398. *
  18399. * @param {number} x - The value for the normal's x component.
  18400. * @param {number} y - The value for the normal's y component.
  18401. * @param {number} z - The value for the normal's z component.
  18402. * @param {number} w - The constant value.
  18403. * @return {Plane} A reference to this plane.
  18404. */
  18405. setComponents( x, y, z, w ) {
  18406. this.normal.set( x, y, z );
  18407. this.constant = w;
  18408. return this;
  18409. }
  18410. /**
  18411. * Sets the plane from the given normal and coplanar point (that is a point
  18412. * that lies onto the plane).
  18413. *
  18414. * @param {Vector3} normal - The normal.
  18415. * @param {Vector3} point - A coplanar point.
  18416. * @return {Plane} A reference to this plane.
  18417. */
  18418. setFromNormalAndCoplanarPoint( normal, point ) {
  18419. this.normal.copy( normal );
  18420. this.constant = - point.dot( this.normal );
  18421. return this;
  18422. }
  18423. /**
  18424. * Sets the plane from three coplanar points. The winding order is
  18425. * assumed to be counter-clockwise, and determines the direction of
  18426. * the plane normal.
  18427. *
  18428. * @param {Vector3} a - The first coplanar point.
  18429. * @param {Vector3} b - The second coplanar point.
  18430. * @param {Vector3} c - The third coplanar point.
  18431. * @return {Plane} A reference to this plane.
  18432. */
  18433. setFromCoplanarPoints( a, b, c ) {
  18434. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  18435. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  18436. this.setFromNormalAndCoplanarPoint( normal, a );
  18437. return this;
  18438. }
  18439. /**
  18440. * Copies the values of the given plane to this instance.
  18441. *
  18442. * @param {Plane} plane - The plane to copy.
  18443. * @return {Plane} A reference to this plane.
  18444. */
  18445. copy( plane ) {
  18446. this.normal.copy( plane.normal );
  18447. this.constant = plane.constant;
  18448. return this;
  18449. }
  18450. /**
  18451. * Normalizes the plane normal and adjusts the constant accordingly.
  18452. *
  18453. * @return {Plane} A reference to this plane.
  18454. */
  18455. normalize() {
  18456. // Note: will lead to a divide by zero if the plane is invalid.
  18457. const inverseNormalLength = 1.0 / this.normal.length();
  18458. this.normal.multiplyScalar( inverseNormalLength );
  18459. this.constant *= inverseNormalLength;
  18460. return this;
  18461. }
  18462. /**
  18463. * Negates both the plane normal and the constant.
  18464. *
  18465. * @return {Plane} A reference to this plane.
  18466. */
  18467. negate() {
  18468. this.constant *= -1;
  18469. this.normal.negate();
  18470. return this;
  18471. }
  18472. /**
  18473. * Returns the signed distance from the given point to this plane.
  18474. *
  18475. * @param {Vector3} point - The point to compute the distance for.
  18476. * @return {number} The signed distance.
  18477. */
  18478. distanceToPoint( point ) {
  18479. return this.normal.dot( point ) + this.constant;
  18480. }
  18481. /**
  18482. * Returns the signed distance from the given sphere to this plane.
  18483. *
  18484. * @param {Sphere} sphere - The sphere to compute the distance for.
  18485. * @return {number} The signed distance.
  18486. */
  18487. distanceToSphere( sphere ) {
  18488. return this.distanceToPoint( sphere.center ) - sphere.radius;
  18489. }
  18490. /**
  18491. * Projects a the given point onto the plane.
  18492. *
  18493. * @param {Vector3} point - The point to project.
  18494. * @param {Vector3} target - The target vector that is used to store the method's result.
  18495. * @return {Vector3} The projected point on the plane.
  18496. */
  18497. projectPoint( point, target ) {
  18498. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  18499. }
  18500. /**
  18501. * Returns the intersection point of the passed line and the plane. Returns
  18502. * `null` if the line does not intersect. Returns the line's starting point if
  18503. * the line is coplanar with the plane.
  18504. *
  18505. * @param {Line3} line - The line to compute the intersection for.
  18506. * @param {Vector3} target - The target vector that is used to store the method's result.
  18507. * @param {boolean} [clampToLine=true] - Whether to clamp the intersection to the line segment.
  18508. * @return {?Vector3} The intersection point. Returns `null` if no intersection is detected.
  18509. */
  18510. intersectLine( line, target, clampToLine = true ) {
  18511. const direction = line.delta( _vector1 );
  18512. const denominator = this.normal.dot( direction );
  18513. if ( denominator === 0 ) {
  18514. // line is coplanar, return origin
  18515. if ( this.distanceToPoint( line.start ) === 0 ) {
  18516. return target.copy( line.start );
  18517. }
  18518. // Unsure if this is the correct method to handle this case.
  18519. return null;
  18520. }
  18521. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  18522. if ( ( clampToLine === true ) && ( t < 0 || t > 1 ) ) {
  18523. return null;
  18524. }
  18525. return target.copy( line.start ).addScaledVector( direction, t );
  18526. }
  18527. /**
  18528. * Returns `true` if the given line segment intersects with (passes through) the plane.
  18529. *
  18530. * @param {Line3} line - The line to test.
  18531. * @return {boolean} Whether the given line segment intersects with the plane or not.
  18532. */
  18533. intersectsLine( line ) {
  18534. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  18535. const startSign = this.distanceToPoint( line.start );
  18536. const endSign = this.distanceToPoint( line.end );
  18537. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  18538. }
  18539. /**
  18540. * Returns `true` if the given bounding box intersects with the plane.
  18541. *
  18542. * @param {Box3} box - The bounding box to test.
  18543. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  18544. */
  18545. intersectsBox( box ) {
  18546. return box.intersectsPlane( this );
  18547. }
  18548. /**
  18549. * Returns `true` if the given bounding sphere intersects with the plane.
  18550. *
  18551. * @param {Sphere} sphere - The bounding sphere to test.
  18552. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  18553. */
  18554. intersectsSphere( sphere ) {
  18555. return sphere.intersectsPlane( this );
  18556. }
  18557. /**
  18558. * Returns a coplanar vector to the plane, by calculating the
  18559. * projection of the normal at the origin onto the plane.
  18560. *
  18561. * @param {Vector3} target - The target vector that is used to store the method's result.
  18562. * @return {Vector3} The coplanar point.
  18563. */
  18564. coplanarPoint( target ) {
  18565. return target.copy( this.normal ).multiplyScalar( - this.constant );
  18566. }
  18567. /**
  18568. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  18569. *
  18570. * The optional normal matrix can be pre-computed like so:
  18571. * ```js
  18572. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  18573. * ```
  18574. *
  18575. * @param {Matrix4} matrix - The transformation matrix.
  18576. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  18577. * @return {Plane} A reference to this plane.
  18578. */
  18579. applyMatrix4( matrix, optionalNormalMatrix ) {
  18580. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  18581. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  18582. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  18583. this.constant = - referencePoint.dot( normal );
  18584. return this;
  18585. }
  18586. /**
  18587. * Translates the plane by the distance defined by the given offset vector.
  18588. * Note that this only affects the plane constant and will not affect the normal vector.
  18589. *
  18590. * @param {Vector3} offset - The offset vector.
  18591. * @return {Plane} A reference to this plane.
  18592. */
  18593. translate( offset ) {
  18594. this.constant -= offset.dot( this.normal );
  18595. return this;
  18596. }
  18597. /**
  18598. * Returns `true` if this plane is equal with the given one.
  18599. *
  18600. * @param {Plane} plane - The plane to test for equality.
  18601. * @return {boolean} Whether this plane is equal with the given one.
  18602. */
  18603. equals( plane ) {
  18604. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  18605. }
  18606. /**
  18607. * Returns a new plane with copied values from this instance.
  18608. *
  18609. * @return {Plane} A clone of this instance.
  18610. */
  18611. clone() {
  18612. return new this.constructor().copy( this );
  18613. }
  18614. }
  18615. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18616. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  18617. const _vector$6 = /*@__PURE__*/ new Vector3();
  18618. /**
  18619. * Frustums are used to determine what is inside the camera's field of view.
  18620. * They help speed up the rendering process - objects which lie outside a camera's
  18621. * frustum can safely be excluded from rendering.
  18622. *
  18623. * This class is mainly intended for use internally by a renderer.
  18624. */
  18625. class Frustum {
  18626. /**
  18627. * Constructs a new frustum.
  18628. *
  18629. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18630. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18631. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18632. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18633. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18634. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18635. */
  18636. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  18637. /**
  18638. * This array holds the planes that enclose the frustum.
  18639. *
  18640. * @type {Array<Plane>}
  18641. */
  18642. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  18643. }
  18644. /**
  18645. * Sets the frustum planes by copying the given planes.
  18646. *
  18647. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18648. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18649. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18650. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18651. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18652. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18653. * @return {Frustum} A reference to this frustum.
  18654. */
  18655. set( p0, p1, p2, p3, p4, p5 ) {
  18656. const planes = this.planes;
  18657. planes[ 0 ].copy( p0 );
  18658. planes[ 1 ].copy( p1 );
  18659. planes[ 2 ].copy( p2 );
  18660. planes[ 3 ].copy( p3 );
  18661. planes[ 4 ].copy( p4 );
  18662. planes[ 5 ].copy( p5 );
  18663. return this;
  18664. }
  18665. /**
  18666. * Copies the values of the given frustum to this instance.
  18667. *
  18668. * @param {Frustum} frustum - The frustum to copy.
  18669. * @return {Frustum} A reference to this frustum.
  18670. */
  18671. copy( frustum ) {
  18672. const planes = this.planes;
  18673. for ( let i = 0; i < 6; i ++ ) {
  18674. planes[ i ].copy( frustum.planes[ i ] );
  18675. }
  18676. return this;
  18677. }
  18678. /**
  18679. * Sets the frustum planes from the given projection matrix.
  18680. *
  18681. * @param {Matrix4} m - The projection matrix.
  18682. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  18683. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  18684. * @return {Frustum} A reference to this frustum.
  18685. */
  18686. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  18687. const planes = this.planes;
  18688. const me = m.elements;
  18689. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  18690. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  18691. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  18692. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  18693. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  18694. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  18695. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  18696. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  18697. if ( reversedDepth ) {
  18698. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  18699. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  18700. } else {
  18701. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  18702. if ( coordinateSystem === WebGLCoordinateSystem ) {
  18703. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  18704. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  18705. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  18706. } else {
  18707. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  18708. }
  18709. }
  18710. return this;
  18711. }
  18712. /**
  18713. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  18714. *
  18715. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  18716. *
  18717. * @param {Object3D} object - The 3D object to test.
  18718. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  18719. */
  18720. intersectsObject( object ) {
  18721. if ( object.boundingSphere !== undefined ) {
  18722. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  18723. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  18724. } else {
  18725. const geometry = object.geometry;
  18726. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18727. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  18728. }
  18729. return this.intersectsSphere( _sphere$3 );
  18730. }
  18731. /**
  18732. * Returns `true` if the given sprite is intersecting this frustum.
  18733. *
  18734. * @param {Sprite} sprite - The sprite to test.
  18735. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  18736. */
  18737. intersectsSprite( sprite ) {
  18738. _sphere$3.center.set( 0, 0, 0 );
  18739. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  18740. _sphere$3.radius = 0.7071067811865476 + offset;
  18741. _sphere$3.applyMatrix4( sprite.matrixWorld );
  18742. return this.intersectsSphere( _sphere$3 );
  18743. }
  18744. /**
  18745. * Returns `true` if the given bounding sphere is intersecting this frustum.
  18746. *
  18747. * @param {Sphere} sphere - The bounding sphere to test.
  18748. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  18749. */
  18750. intersectsSphere( sphere ) {
  18751. const planes = this.planes;
  18752. const center = sphere.center;
  18753. const negRadius = - sphere.radius;
  18754. for ( let i = 0; i < 6; i ++ ) {
  18755. const distance = planes[ i ].distanceToPoint( center );
  18756. if ( distance < negRadius ) {
  18757. return false;
  18758. }
  18759. }
  18760. return true;
  18761. }
  18762. /**
  18763. * Returns `true` if the given bounding box is intersecting this frustum.
  18764. *
  18765. * @param {Box3} box - The bounding box to test.
  18766. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  18767. */
  18768. intersectsBox( box ) {
  18769. const planes = this.planes;
  18770. for ( let i = 0; i < 6; i ++ ) {
  18771. const plane = planes[ i ];
  18772. // corner at max distance
  18773. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  18774. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  18775. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  18776. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  18777. return false;
  18778. }
  18779. }
  18780. return true;
  18781. }
  18782. /**
  18783. * Returns `true` if the given point lies within the frustum.
  18784. *
  18785. * @param {Vector3} point - The point to test.
  18786. * @return {boolean} Whether the point lies within this frustum or not.
  18787. */
  18788. containsPoint( point ) {
  18789. const planes = this.planes;
  18790. for ( let i = 0; i < 6; i ++ ) {
  18791. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  18792. return false;
  18793. }
  18794. }
  18795. return true;
  18796. }
  18797. /**
  18798. * Returns a new frustum with copied values from this instance.
  18799. *
  18800. * @return {Frustum} A clone of this instance.
  18801. */
  18802. clone() {
  18803. return new this.constructor().copy( this );
  18804. }
  18805. }
  18806. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  18807. const _frustum$1 = /*@__PURE__*/ new Frustum();
  18808. /**
  18809. * FrustumArray is used to determine if an object is visible in at least one camera
  18810. * from an array of cameras. This is particularly useful for multi-view renderers.
  18811. */
  18812. class FrustumArray {
  18813. /**
  18814. * Constructs a new frustum array.
  18815. *
  18816. */
  18817. constructor() {
  18818. /**
  18819. * The coordinate system to use.
  18820. *
  18821. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  18822. * @default WebGLCoordinateSystem
  18823. */
  18824. this.coordinateSystem = WebGLCoordinateSystem;
  18825. }
  18826. /**
  18827. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  18828. * from the camera array.
  18829. *
  18830. * @param {Object3D} object - The 3D object to test.
  18831. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18832. * @return {boolean} Whether the 3D object is visible in any camera.
  18833. */
  18834. intersectsObject( object, cameraArray ) {
  18835. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  18836. return false;
  18837. }
  18838. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18839. const camera = cameraArray.cameras[ i ];
  18840. _projScreenMatrix$1.multiplyMatrices(
  18841. camera.projectionMatrix,
  18842. camera.matrixWorldInverse
  18843. );
  18844. _frustum$1.setFromProjectionMatrix(
  18845. _projScreenMatrix$1,
  18846. camera.coordinateSystem,
  18847. camera.reversedDepth
  18848. );
  18849. if ( _frustum$1.intersectsObject( object ) ) {
  18850. return true; // Object is visible in at least one camera
  18851. }
  18852. }
  18853. return false; // Not visible in any camera
  18854. }
  18855. /**
  18856. * Returns `true` if the given sprite is intersecting any frustum
  18857. * from the camera array.
  18858. *
  18859. * @param {Sprite} sprite - The sprite to test.
  18860. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18861. * @return {boolean} Whether the sprite is visible in any camera.
  18862. */
  18863. intersectsSprite( sprite, cameraArray ) {
  18864. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18865. return false;
  18866. }
  18867. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18868. const camera = cameraArray.cameras[ i ];
  18869. _projScreenMatrix$1.multiplyMatrices(
  18870. camera.projectionMatrix,
  18871. camera.matrixWorldInverse
  18872. );
  18873. _frustum$1.setFromProjectionMatrix(
  18874. _projScreenMatrix$1,
  18875. camera.coordinateSystem,
  18876. camera.reversedDepth
  18877. );
  18878. if ( _frustum$1.intersectsSprite( sprite ) ) {
  18879. return true; // Sprite is visible in at least one camera
  18880. }
  18881. }
  18882. return false; // Not visible in any camera
  18883. }
  18884. /**
  18885. * Returns `true` if the given bounding sphere is intersecting any frustum
  18886. * from the camera array.
  18887. *
  18888. * @param {Sphere} sphere - The bounding sphere to test.
  18889. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18890. * @return {boolean} Whether the sphere is visible in any camera.
  18891. */
  18892. intersectsSphere( sphere, cameraArray ) {
  18893. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18894. return false;
  18895. }
  18896. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18897. const camera = cameraArray.cameras[ i ];
  18898. _projScreenMatrix$1.multiplyMatrices(
  18899. camera.projectionMatrix,
  18900. camera.matrixWorldInverse
  18901. );
  18902. _frustum$1.setFromProjectionMatrix(
  18903. _projScreenMatrix$1,
  18904. camera.coordinateSystem,
  18905. camera.reversedDepth
  18906. );
  18907. if ( _frustum$1.intersectsSphere( sphere ) ) {
  18908. return true; // Sphere is visible in at least one camera
  18909. }
  18910. }
  18911. return false; // Not visible in any camera
  18912. }
  18913. /**
  18914. * Returns `true` if the given bounding box is intersecting any frustum
  18915. * from the camera array.
  18916. *
  18917. * @param {Box3} box - The bounding box to test.
  18918. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18919. * @return {boolean} Whether the box is visible in any camera.
  18920. */
  18921. intersectsBox( box, cameraArray ) {
  18922. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18923. return false;
  18924. }
  18925. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18926. const camera = cameraArray.cameras[ i ];
  18927. _projScreenMatrix$1.multiplyMatrices(
  18928. camera.projectionMatrix,
  18929. camera.matrixWorldInverse
  18930. );
  18931. _frustum$1.setFromProjectionMatrix(
  18932. _projScreenMatrix$1,
  18933. camera.coordinateSystem,
  18934. camera.reversedDepth
  18935. );
  18936. if ( _frustum$1.intersectsBox( box ) ) {
  18937. return true; // Box is visible in at least one camera
  18938. }
  18939. }
  18940. return false; // Not visible in any camera
  18941. }
  18942. /**
  18943. * Returns `true` if the given point lies within any frustum
  18944. * from the camera array.
  18945. *
  18946. * @param {Vector3} point - The point to test.
  18947. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18948. * @return {boolean} Whether the point is visible in any camera.
  18949. */
  18950. containsPoint( point, cameraArray ) {
  18951. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18952. return false;
  18953. }
  18954. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18955. const camera = cameraArray.cameras[ i ];
  18956. _projScreenMatrix$1.multiplyMatrices(
  18957. camera.projectionMatrix,
  18958. camera.matrixWorldInverse
  18959. );
  18960. _frustum$1.setFromProjectionMatrix(
  18961. _projScreenMatrix$1,
  18962. camera.coordinateSystem,
  18963. camera.reversedDepth
  18964. );
  18965. if ( _frustum$1.containsPoint( point ) ) {
  18966. return true; // Point is visible in at least one camera
  18967. }
  18968. }
  18969. return false; // Not visible in any camera
  18970. }
  18971. /**
  18972. * Returns a new frustum array with copied values from this instance.
  18973. *
  18974. * @return {FrustumArray} A clone of this instance.
  18975. */
  18976. clone() {
  18977. return new FrustumArray();
  18978. }
  18979. }
  18980. function ascIdSort( a, b ) {
  18981. return a - b;
  18982. }
  18983. function sortOpaque( a, b ) {
  18984. return a.z - b.z;
  18985. }
  18986. function sortTransparent( a, b ) {
  18987. return b.z - a.z;
  18988. }
  18989. class MultiDrawRenderList {
  18990. constructor() {
  18991. this.index = 0;
  18992. this.pool = [];
  18993. this.list = [];
  18994. }
  18995. push( start, count, z, index ) {
  18996. const pool = this.pool;
  18997. const list = this.list;
  18998. if ( this.index >= pool.length ) {
  18999. pool.push( {
  19000. start: -1,
  19001. count: -1,
  19002. z: -1,
  19003. index: -1,
  19004. } );
  19005. }
  19006. const item = pool[ this.index ];
  19007. list.push( item );
  19008. this.index ++;
  19009. item.start = start;
  19010. item.count = count;
  19011. item.z = z;
  19012. item.index = index;
  19013. }
  19014. reset() {
  19015. this.list.length = 0;
  19016. this.index = 0;
  19017. }
  19018. }
  19019. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19020. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19021. const _frustum = /*@__PURE__*/ new Frustum();
  19022. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19023. const _box$1 = /*@__PURE__*/ new Box3();
  19024. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19025. const _vector$5 = /*@__PURE__*/ new Vector3();
  19026. const _forward$1 = /*@__PURE__*/ new Vector3();
  19027. const _temp = /*@__PURE__*/ new Vector3();
  19028. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19029. const _mesh = /*@__PURE__*/ new Mesh();
  19030. const _batchIntersects = [];
  19031. // copies data from attribute "src" into "target" starting at "targetOffset"
  19032. function copyAttributeData( src, target, targetOffset = 0 ) {
  19033. const itemSize = target.itemSize;
  19034. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19035. // use the component getters and setters if the array data cannot
  19036. // be copied directly
  19037. const vertexCount = src.count;
  19038. for ( let i = 0; i < vertexCount; i ++ ) {
  19039. for ( let c = 0; c < itemSize; c ++ ) {
  19040. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19041. }
  19042. }
  19043. } else {
  19044. // faster copy approach using typed array set function
  19045. target.array.set( src.array, targetOffset * itemSize );
  19046. }
  19047. target.needsUpdate = true;
  19048. }
  19049. // safely copies array contents to a potentially smaller array
  19050. function copyArrayContents( src, target ) {
  19051. if ( src.constructor !== target.constructor ) {
  19052. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19053. const len = Math.min( src.length, target.length );
  19054. for ( let i = 0; i < len; i ++ ) {
  19055. target[ i ] = src[ i ];
  19056. }
  19057. } else {
  19058. // if the arrays use the same data layout we can use a fast block copy
  19059. const len = Math.min( src.length, target.length );
  19060. target.set( new src.constructor( src.buffer, 0, len ) );
  19061. }
  19062. }
  19063. /**
  19064. * A special version of a mesh with multi draw batch rendering support. Use
  19065. * this class if you have to render a large number of objects with the same
  19066. * material but with different geometries or world transformations. The usage of
  19067. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19068. * rendering performance in your application.
  19069. *
  19070. * ```js
  19071. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19072. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19073. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19074. *
  19075. * // initialize and add geometries into the batched mesh
  19076. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19077. * const boxGeometryId = batchedMesh.addGeometry( box );
  19078. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19079. *
  19080. * // create instances of those geometries
  19081. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19082. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19083. *
  19084. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19085. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19086. *
  19087. * // position the geometries
  19088. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19089. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19090. *
  19091. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19092. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19093. *
  19094. * scene.add( batchedMesh );
  19095. * ```
  19096. *
  19097. * @augments Mesh
  19098. */
  19099. class BatchedMesh extends Mesh {
  19100. /**
  19101. * Constructs a new batched mesh.
  19102. *
  19103. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19104. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19105. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19106. * @param {Material|Array<Material>} [material] - The mesh material.
  19107. */
  19108. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19109. super( new BufferGeometry(), material );
  19110. /**
  19111. * This flag can be used for type testing.
  19112. *
  19113. * @type {boolean}
  19114. * @readonly
  19115. * @default true
  19116. */
  19117. this.isBatchedMesh = true;
  19118. /**
  19119. * When set ot `true`, the individual objects of a batch are frustum culled.
  19120. *
  19121. * @type {boolean}
  19122. * @default true
  19123. */
  19124. this.perObjectFrustumCulled = true;
  19125. /**
  19126. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19127. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19128. * rendered front to back.
  19129. *
  19130. * @type {boolean}
  19131. * @default true
  19132. */
  19133. this.sortObjects = true;
  19134. /**
  19135. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19136. *
  19137. * @type {?Box3}
  19138. * @default null
  19139. */
  19140. this.boundingBox = null;
  19141. /**
  19142. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19143. *
  19144. * @type {?Sphere}
  19145. * @default null
  19146. */
  19147. this.boundingSphere = null;
  19148. /**
  19149. * Takes a sort a function that is run before render. The function takes a list of instances to
  19150. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19151. * sort with.
  19152. *
  19153. * @type {?Function}
  19154. * @default null
  19155. */
  19156. this.customSort = null;
  19157. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19158. this._instanceInfo = [];
  19159. this._geometryInfo = [];
  19160. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19161. this._availableInstanceIds = [];
  19162. this._availableGeometryIds = [];
  19163. // used to track where the next point is that geometry should be inserted
  19164. this._nextIndexStart = 0;
  19165. this._nextVertexStart = 0;
  19166. this._geometryCount = 0;
  19167. // flags
  19168. this._visibilityChanged = true;
  19169. this._geometryInitialized = false;
  19170. // cached user options
  19171. this._maxInstanceCount = maxInstanceCount;
  19172. this._maxVertexCount = maxVertexCount;
  19173. this._maxIndexCount = maxIndexCount;
  19174. // buffers for multi draw
  19175. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19176. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19177. this._multiDrawCount = 0;
  19178. // Local matrix per geometry by using data texture
  19179. this._matricesTexture = null;
  19180. this._indirectTexture = null;
  19181. this._colorsTexture = null;
  19182. this._initMatricesTexture();
  19183. this._initIndirectTexture();
  19184. }
  19185. /**
  19186. * The maximum number of individual instances that can be stored in the batch.
  19187. *
  19188. * @type {number}
  19189. * @readonly
  19190. */
  19191. get maxInstanceCount() {
  19192. return this._maxInstanceCount;
  19193. }
  19194. /**
  19195. * The instance count.
  19196. *
  19197. * @type {number}
  19198. * @readonly
  19199. */
  19200. get instanceCount() {
  19201. return this._instanceInfo.length - this._availableInstanceIds.length;
  19202. }
  19203. /**
  19204. * The number of unused vertices.
  19205. *
  19206. * @type {number}
  19207. * @readonly
  19208. */
  19209. get unusedVertexCount() {
  19210. return this._maxVertexCount - this._nextVertexStart;
  19211. }
  19212. /**
  19213. * The number of unused indices.
  19214. *
  19215. * @type {number}
  19216. * @readonly
  19217. */
  19218. get unusedIndexCount() {
  19219. return this._maxIndexCount - this._nextIndexStart;
  19220. }
  19221. _initMatricesTexture() {
  19222. // layout (1 matrix = 4 pixels)
  19223. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19224. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19225. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19226. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19227. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19228. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19229. size = Math.ceil( size / 4 ) * 4;
  19230. size = Math.max( size, 4 );
  19231. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19232. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19233. this._matricesTexture = matricesTexture;
  19234. }
  19235. _initIndirectTexture() {
  19236. let size = Math.sqrt( this._maxInstanceCount );
  19237. size = Math.ceil( size );
  19238. const indirectArray = new Uint32Array( size * size );
  19239. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19240. this._indirectTexture = indirectTexture;
  19241. }
  19242. _initColorsTexture() {
  19243. let size = Math.sqrt( this._maxInstanceCount );
  19244. size = Math.ceil( size );
  19245. // 4 floats per RGBA pixel initialized to white
  19246. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19247. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19248. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19249. this._colorsTexture = colorsTexture;
  19250. }
  19251. _initializeGeometry( reference ) {
  19252. const geometry = this.geometry;
  19253. const maxVertexCount = this._maxVertexCount;
  19254. const maxIndexCount = this._maxIndexCount;
  19255. if ( this._geometryInitialized === false ) {
  19256. for ( const attributeName in reference.attributes ) {
  19257. const srcAttribute = reference.getAttribute( attributeName );
  19258. const { array, itemSize, normalized } = srcAttribute;
  19259. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19260. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19261. geometry.setAttribute( attributeName, dstAttribute );
  19262. }
  19263. if ( reference.getIndex() !== null ) {
  19264. // Reserve last u16 index for primitive restart.
  19265. const indexArray = maxVertexCount > 65535
  19266. ? new Uint32Array( maxIndexCount )
  19267. : new Uint16Array( maxIndexCount );
  19268. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19269. }
  19270. this._geometryInitialized = true;
  19271. }
  19272. }
  19273. // Make sure the geometry is compatible with the existing combined geometry attributes
  19274. _validateGeometry( geometry ) {
  19275. // check to ensure the geometries are using consistent attributes and indices
  19276. const batchGeometry = this.geometry;
  19277. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19278. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19279. }
  19280. for ( const attributeName in batchGeometry.attributes ) {
  19281. if ( ! geometry.hasAttribute( attributeName ) ) {
  19282. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19283. }
  19284. const srcAttribute = geometry.getAttribute( attributeName );
  19285. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19286. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19287. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19288. }
  19289. }
  19290. }
  19291. /**
  19292. * Validates the instance defined by the given ID.
  19293. *
  19294. * @param {number} instanceId - The instance to validate.
  19295. */
  19296. validateInstanceId( instanceId ) {
  19297. const instanceInfo = this._instanceInfo;
  19298. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19299. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19300. }
  19301. }
  19302. /**
  19303. * Validates the geometry defined by the given ID.
  19304. *
  19305. * @param {number} geometryId - The geometry to validate.
  19306. */
  19307. validateGeometryId( geometryId ) {
  19308. const geometryInfoList = this._geometryInfo;
  19309. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19310. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19311. }
  19312. }
  19313. /**
  19314. * Takes a sort a function that is run before render. The function takes a list of instances to
  19315. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19316. *
  19317. * @param {Function} func - The custom sort function.
  19318. * @return {BatchedMesh} A reference to this batched mesh.
  19319. */
  19320. setCustomSort( func ) {
  19321. this.customSort = func;
  19322. return this;
  19323. }
  19324. /**
  19325. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19326. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19327. * otherwise they are `null`.
  19328. */
  19329. computeBoundingBox() {
  19330. if ( this.boundingBox === null ) {
  19331. this.boundingBox = new Box3();
  19332. }
  19333. const boundingBox = this.boundingBox;
  19334. const instanceInfo = this._instanceInfo;
  19335. boundingBox.makeEmpty();
  19336. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19337. if ( instanceInfo[ i ].active === false ) continue;
  19338. const geometryId = instanceInfo[ i ].geometryIndex;
  19339. this.getMatrixAt( i, _matrix$1 );
  19340. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19341. boundingBox.union( _box$1 );
  19342. }
  19343. }
  19344. /**
  19345. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19346. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19347. * otherwise they are `null`.
  19348. */
  19349. computeBoundingSphere() {
  19350. if ( this.boundingSphere === null ) {
  19351. this.boundingSphere = new Sphere();
  19352. }
  19353. const boundingSphere = this.boundingSphere;
  19354. const instanceInfo = this._instanceInfo;
  19355. boundingSphere.makeEmpty();
  19356. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19357. if ( instanceInfo[ i ].active === false ) continue;
  19358. const geometryId = instanceInfo[ i ].geometryIndex;
  19359. this.getMatrixAt( i, _matrix$1 );
  19360. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19361. boundingSphere.union( _sphere$2 );
  19362. }
  19363. }
  19364. /**
  19365. * Adds a new instance to the batch using the geometry of the given ID and returns
  19366. * a new id referring to the new instance to be used by other functions.
  19367. *
  19368. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  19369. * @return {number} The instance ID.
  19370. */
  19371. addInstance( geometryId ) {
  19372. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  19373. // ensure we're not over geometry
  19374. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  19375. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  19376. }
  19377. const instanceInfo = {
  19378. visible: true,
  19379. active: true,
  19380. geometryIndex: geometryId,
  19381. };
  19382. let drawId = null;
  19383. // Prioritize using previously freed instance ids
  19384. if ( this._availableInstanceIds.length > 0 ) {
  19385. this._availableInstanceIds.sort( ascIdSort );
  19386. drawId = this._availableInstanceIds.shift();
  19387. this._instanceInfo[ drawId ] = instanceInfo;
  19388. } else {
  19389. drawId = this._instanceInfo.length;
  19390. this._instanceInfo.push( instanceInfo );
  19391. }
  19392. const matricesTexture = this._matricesTexture;
  19393. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  19394. matricesTexture.needsUpdate = true;
  19395. const colorsTexture = this._colorsTexture;
  19396. if ( colorsTexture ) {
  19397. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  19398. colorsTexture.needsUpdate = true;
  19399. }
  19400. this._visibilityChanged = true;
  19401. return drawId;
  19402. }
  19403. /**
  19404. * Adds the given geometry to the batch and returns the associated
  19405. * geometry id referring to it to be used in other functions.
  19406. *
  19407. * @param {BufferGeometry} geometry - The geometry to add.
  19408. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  19409. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  19410. * to set a new geometry at this index at a later time that is larger than the original geometry.
  19411. * Defaults to the length of the given geometry vertex buffer.
  19412. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  19413. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  19414. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  19415. * the length of the given geometry index buffer.
  19416. * @return {number} The geometry ID.
  19417. */
  19418. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  19419. this._initializeGeometry( geometry );
  19420. this._validateGeometry( geometry );
  19421. const geometryInfo = {
  19422. // geometry information
  19423. vertexStart: -1,
  19424. vertexCount: -1,
  19425. reservedVertexCount: -1,
  19426. indexStart: -1,
  19427. indexCount: -1,
  19428. reservedIndexCount: -1,
  19429. // draw range information
  19430. start: -1,
  19431. count: -1,
  19432. // state
  19433. boundingBox: null,
  19434. boundingSphere: null,
  19435. active: true,
  19436. };
  19437. const geometryInfoList = this._geometryInfo;
  19438. geometryInfo.vertexStart = this._nextVertexStart;
  19439. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  19440. const index = geometry.getIndex();
  19441. const hasIndex = index !== null;
  19442. if ( hasIndex ) {
  19443. geometryInfo.indexStart = this._nextIndexStart;
  19444. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  19445. }
  19446. if (
  19447. geometryInfo.indexStart !== -1 &&
  19448. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  19449. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  19450. ) {
  19451. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19452. }
  19453. // update id
  19454. let geometryId;
  19455. if ( this._availableGeometryIds.length > 0 ) {
  19456. this._availableGeometryIds.sort( ascIdSort );
  19457. geometryId = this._availableGeometryIds.shift();
  19458. geometryInfoList[ geometryId ] = geometryInfo;
  19459. } else {
  19460. geometryId = this._geometryCount;
  19461. this._geometryCount ++;
  19462. geometryInfoList.push( geometryInfo );
  19463. }
  19464. // update the geometry
  19465. this.setGeometryAt( geometryId, geometry );
  19466. // increment the next geometry position
  19467. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  19468. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  19469. return geometryId;
  19470. }
  19471. /**
  19472. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  19473. * is not enough space reserved for geometry. Calling this will change all instances that are
  19474. * rendering that geometry.
  19475. *
  19476. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  19477. * @param {BufferGeometry} geometry - The new geometry.
  19478. * @return {number} The geometry ID.
  19479. */
  19480. setGeometryAt( geometryId, geometry ) {
  19481. if ( geometryId >= this._geometryCount ) {
  19482. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  19483. }
  19484. this._validateGeometry( geometry );
  19485. const batchGeometry = this.geometry;
  19486. const hasIndex = batchGeometry.getIndex() !== null;
  19487. const dstIndex = batchGeometry.getIndex();
  19488. const srcIndex = geometry.getIndex();
  19489. const geometryInfo = this._geometryInfo[ geometryId ];
  19490. if (
  19491. hasIndex &&
  19492. srcIndex.count > geometryInfo.reservedIndexCount ||
  19493. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  19494. ) {
  19495. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  19496. }
  19497. // copy geometry buffer data over
  19498. const vertexStart = geometryInfo.vertexStart;
  19499. const reservedVertexCount = geometryInfo.reservedVertexCount;
  19500. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  19501. for ( const attributeName in batchGeometry.attributes ) {
  19502. // copy attribute data
  19503. const srcAttribute = geometry.getAttribute( attributeName );
  19504. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19505. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19506. // fill the rest in with zeroes
  19507. const itemSize = srcAttribute.itemSize;
  19508. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  19509. const index = vertexStart + i;
  19510. for ( let c = 0; c < itemSize; c ++ ) {
  19511. dstAttribute.setComponent( index, c, 0 );
  19512. }
  19513. }
  19514. dstAttribute.needsUpdate = true;
  19515. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  19516. }
  19517. // copy index
  19518. if ( hasIndex ) {
  19519. const indexStart = geometryInfo.indexStart;
  19520. const reservedIndexCount = geometryInfo.reservedIndexCount;
  19521. geometryInfo.indexCount = geometry.getIndex().count;
  19522. // copy index data over
  19523. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19524. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19525. }
  19526. // fill the rest in with zeroes
  19527. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  19528. dstIndex.setX( indexStart + i, vertexStart );
  19529. }
  19530. dstIndex.needsUpdate = true;
  19531. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  19532. }
  19533. // update the draw range
  19534. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19535. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  19536. // store the bounding boxes
  19537. geometryInfo.boundingBox = null;
  19538. if ( geometry.boundingBox !== null ) {
  19539. geometryInfo.boundingBox = geometry.boundingBox.clone();
  19540. }
  19541. geometryInfo.boundingSphere = null;
  19542. if ( geometry.boundingSphere !== null ) {
  19543. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  19544. }
  19545. this._visibilityChanged = true;
  19546. return geometryId;
  19547. }
  19548. /**
  19549. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  19550. * this geometry will also be removed as a side effect.
  19551. *
  19552. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  19553. * @return {BatchedMesh} A reference to this batched mesh.
  19554. */
  19555. deleteGeometry( geometryId ) {
  19556. const geometryInfoList = this._geometryInfo;
  19557. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19558. return this;
  19559. }
  19560. // delete any instances associated with this geometry
  19561. const instanceInfo = this._instanceInfo;
  19562. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19563. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  19564. this.deleteInstance( i );
  19565. }
  19566. }
  19567. geometryInfoList[ geometryId ].active = false;
  19568. this._availableGeometryIds.push( geometryId );
  19569. this._visibilityChanged = true;
  19570. return this;
  19571. }
  19572. /**
  19573. * Deletes an existing instance from the batch using the given ID.
  19574. *
  19575. * @param {number} instanceId - The ID of the instance to remove from the batch.
  19576. * @return {BatchedMesh} A reference to this batched mesh.
  19577. */
  19578. deleteInstance( instanceId ) {
  19579. this.validateInstanceId( instanceId );
  19580. this._instanceInfo[ instanceId ].active = false;
  19581. this._availableInstanceIds.push( instanceId );
  19582. this._visibilityChanged = true;
  19583. return this;
  19584. }
  19585. /**
  19586. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  19587. * previously deleted geometry, freeing up space to add new geometry.
  19588. *
  19589. * @return {BatchedMesh} A reference to this batched mesh.
  19590. */
  19591. optimize() {
  19592. // track the next indices to copy data to
  19593. let nextVertexStart = 0;
  19594. let nextIndexStart = 0;
  19595. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  19596. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  19597. const geometryInfoList = this._geometryInfo;
  19598. const indices = geometryInfoList
  19599. .map( ( e, i ) => i )
  19600. .sort( ( a, b ) => {
  19601. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  19602. } );
  19603. const geometry = this.geometry;
  19604. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  19605. // if a geometry range is inactive then don't copy anything
  19606. const index = indices[ i ];
  19607. const geometryInfo = geometryInfoList[ index ];
  19608. if ( geometryInfo.active === false ) {
  19609. continue;
  19610. }
  19611. // if a geometry contains an index buffer then shift it, as well
  19612. if ( geometry.index !== null ) {
  19613. if ( geometryInfo.indexStart !== nextIndexStart ) {
  19614. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  19615. const index = geometry.index;
  19616. const array = index.array;
  19617. // shift the index pointers based on how the vertex data will shift
  19618. // adjusting the index must happen first so the original vertex start value is available
  19619. const elementDelta = nextVertexStart - vertexStart;
  19620. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  19621. array[ j ] = array[ j ] + elementDelta;
  19622. }
  19623. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  19624. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  19625. index.needsUpdate = true;
  19626. geometryInfo.indexStart = nextIndexStart;
  19627. }
  19628. nextIndexStart += geometryInfo.reservedIndexCount;
  19629. }
  19630. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  19631. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  19632. const { vertexStart, reservedVertexCount } = geometryInfo;
  19633. const attributes = geometry.attributes;
  19634. for ( const key in attributes ) {
  19635. const attribute = attributes[ key ];
  19636. const { array, itemSize } = attribute;
  19637. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  19638. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  19639. attribute.needsUpdate = true;
  19640. }
  19641. geometryInfo.vertexStart = nextVertexStart;
  19642. }
  19643. nextVertexStart += geometryInfo.reservedVertexCount;
  19644. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19645. }
  19646. this._nextIndexStart = nextIndexStart;
  19647. this._nextVertexStart = nextVertexStart;
  19648. this._visibilityChanged = true;
  19649. return this;
  19650. }
  19651. /**
  19652. * Returns the bounding box for the given geometry.
  19653. *
  19654. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  19655. * @param {Box3} target - The target object that is used to store the method's result.
  19656. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  19657. */
  19658. getBoundingBoxAt( geometryId, target ) {
  19659. if ( geometryId >= this._geometryCount ) {
  19660. return null;
  19661. }
  19662. // compute bounding box
  19663. const geometry = this.geometry;
  19664. const geometryInfo = this._geometryInfo[ geometryId ];
  19665. if ( geometryInfo.boundingBox === null ) {
  19666. const box = new Box3();
  19667. const index = geometry.index;
  19668. const position = geometry.attributes.position;
  19669. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19670. let iv = i;
  19671. if ( index ) {
  19672. iv = index.getX( iv );
  19673. }
  19674. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19675. }
  19676. geometryInfo.boundingBox = box;
  19677. }
  19678. target.copy( geometryInfo.boundingBox );
  19679. return target;
  19680. }
  19681. /**
  19682. * Returns the bounding sphere for the given geometry.
  19683. *
  19684. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  19685. * @param {Sphere} target - The target object that is used to store the method's result.
  19686. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  19687. */
  19688. getBoundingSphereAt( geometryId, target ) {
  19689. if ( geometryId >= this._geometryCount ) {
  19690. return null;
  19691. }
  19692. // compute bounding sphere
  19693. const geometry = this.geometry;
  19694. const geometryInfo = this._geometryInfo[ geometryId ];
  19695. if ( geometryInfo.boundingSphere === null ) {
  19696. const sphere = new Sphere();
  19697. this.getBoundingBoxAt( geometryId, _box$1 );
  19698. _box$1.getCenter( sphere.center );
  19699. const index = geometry.index;
  19700. const position = geometry.attributes.position;
  19701. let maxRadiusSq = 0;
  19702. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19703. let iv = i;
  19704. if ( index ) {
  19705. iv = index.getX( iv );
  19706. }
  19707. _vector$5.fromBufferAttribute( position, iv );
  19708. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19709. }
  19710. sphere.radius = Math.sqrt( maxRadiusSq );
  19711. geometryInfo.boundingSphere = sphere;
  19712. }
  19713. target.copy( geometryInfo.boundingSphere );
  19714. return target;
  19715. }
  19716. /**
  19717. * Sets the given local transformation matrix to the defined instance.
  19718. * Negatively scaled matrices are not supported.
  19719. *
  19720. * @param {number} instanceId - The ID of an instance to set the matrix of.
  19721. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  19722. * @return {BatchedMesh} A reference to this batched mesh.
  19723. */
  19724. setMatrixAt( instanceId, matrix ) {
  19725. this.validateInstanceId( instanceId );
  19726. const matricesTexture = this._matricesTexture;
  19727. const matricesArray = this._matricesTexture.image.data;
  19728. matrix.toArray( matricesArray, instanceId * 16 );
  19729. matricesTexture.needsUpdate = true;
  19730. return this;
  19731. }
  19732. /**
  19733. * Returns the local transformation matrix of the defined instance.
  19734. *
  19735. * @param {number} instanceId - The ID of an instance to get the matrix of.
  19736. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19737. * @return {Matrix4} The instance's local transformation matrix.
  19738. */
  19739. getMatrixAt( instanceId, matrix ) {
  19740. this.validateInstanceId( instanceId );
  19741. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  19742. }
  19743. /**
  19744. * Sets the given color to the defined instance.
  19745. *
  19746. * @param {number} instanceId - The ID of an instance to set the color of.
  19747. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  19748. * @return {BatchedMesh} A reference to this batched mesh.
  19749. */
  19750. setColorAt( instanceId, color ) {
  19751. this.validateInstanceId( instanceId );
  19752. if ( this._colorsTexture === null ) {
  19753. this._initColorsTexture();
  19754. }
  19755. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  19756. this._colorsTexture.needsUpdate = true;
  19757. return this;
  19758. }
  19759. /**
  19760. * Returns the color of the defined instance.
  19761. *
  19762. * @param {number} instanceId - The ID of an instance to get the color of.
  19763. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  19764. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  19765. */
  19766. getColorAt( instanceId, color ) {
  19767. this.validateInstanceId( instanceId );
  19768. if ( this._colorsTexture === null ) {
  19769. if ( color.isVector4 ) {
  19770. return color.set( 1, 1, 1, 1 );
  19771. } else {
  19772. return color.setRGB( 1, 1, 1 );
  19773. }
  19774. } else {
  19775. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  19776. }
  19777. }
  19778. /**
  19779. * Sets the visibility of the instance.
  19780. *
  19781. * @param {number} instanceId - The id of the instance to set the visibility of.
  19782. * @param {boolean} visible - Whether the instance is visible or not.
  19783. * @return {BatchedMesh} A reference to this batched mesh.
  19784. */
  19785. setVisibleAt( instanceId, visible ) {
  19786. this.validateInstanceId( instanceId );
  19787. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  19788. return this;
  19789. }
  19790. this._instanceInfo[ instanceId ].visible = visible;
  19791. this._visibilityChanged = true;
  19792. return this;
  19793. }
  19794. /**
  19795. * Returns the visibility state of the defined instance.
  19796. *
  19797. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  19798. * @return {boolean} Whether the instance is visible or not.
  19799. */
  19800. getVisibleAt( instanceId ) {
  19801. this.validateInstanceId( instanceId );
  19802. return this._instanceInfo[ instanceId ].visible;
  19803. }
  19804. /**
  19805. * Sets the geometry ID of the instance at the given index.
  19806. *
  19807. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  19808. * @param {number} geometryId - The geometry ID to be use by the instance.
  19809. * @return {BatchedMesh} A reference to this batched mesh.
  19810. */
  19811. setGeometryIdAt( instanceId, geometryId ) {
  19812. this.validateInstanceId( instanceId );
  19813. this.validateGeometryId( geometryId );
  19814. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  19815. return this;
  19816. }
  19817. /**
  19818. * Returns the geometry ID of the defined instance.
  19819. *
  19820. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  19821. * @return {number} The instance's geometry ID.
  19822. */
  19823. getGeometryIdAt( instanceId ) {
  19824. this.validateInstanceId( instanceId );
  19825. return this._instanceInfo[ instanceId ].geometryIndex;
  19826. }
  19827. /**
  19828. * Get the range representing the subset of triangles related to the attached geometry,
  19829. * indicating the starting offset and count, or `null` if invalid.
  19830. *
  19831. * @param {number} geometryId - The id of the geometry to get the range of.
  19832. * @param {Object} [target] - The target object that is used to store the method's result.
  19833. * @return {{
  19834. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  19835. * indexStart:number,indexCount:number,reservedIndexCount:number,
  19836. * start:number,count:number
  19837. * }} The result object with range data.
  19838. */
  19839. getGeometryRangeAt( geometryId, target = {} ) {
  19840. this.validateGeometryId( geometryId );
  19841. const geometryInfo = this._geometryInfo[ geometryId ];
  19842. target.vertexStart = geometryInfo.vertexStart;
  19843. target.vertexCount = geometryInfo.vertexCount;
  19844. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  19845. target.indexStart = geometryInfo.indexStart;
  19846. target.indexCount = geometryInfo.indexCount;
  19847. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  19848. target.start = geometryInfo.start;
  19849. target.count = geometryInfo.count;
  19850. return target;
  19851. }
  19852. /**
  19853. * Resizes the necessary buffers to support the provided number of instances.
  19854. * If the provided arguments shrink the number of instances but there are not enough
  19855. * unused Ids at the end of the list then an error is thrown.
  19856. *
  19857. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  19858. */
  19859. setInstanceCount( maxInstanceCount ) {
  19860. // shrink the available instances as much as possible
  19861. const availableInstanceIds = this._availableInstanceIds;
  19862. const instanceInfo = this._instanceInfo;
  19863. availableInstanceIds.sort( ascIdSort );
  19864. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  19865. instanceInfo.pop();
  19866. availableInstanceIds.pop();
  19867. }
  19868. // throw an error if it can't be shrunk to the desired size
  19869. if ( maxInstanceCount < instanceInfo.length ) {
  19870. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  19871. }
  19872. // copy the multi draw counts
  19873. const multiDrawCounts = new Int32Array( maxInstanceCount );
  19874. const multiDrawStarts = new Int32Array( maxInstanceCount );
  19875. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  19876. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  19877. this._multiDrawCounts = multiDrawCounts;
  19878. this._multiDrawStarts = multiDrawStarts;
  19879. this._maxInstanceCount = maxInstanceCount;
  19880. // update texture data for instance sampling
  19881. const indirectTexture = this._indirectTexture;
  19882. const matricesTexture = this._matricesTexture;
  19883. const colorsTexture = this._colorsTexture;
  19884. indirectTexture.dispose();
  19885. this._initIndirectTexture();
  19886. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  19887. matricesTexture.dispose();
  19888. this._initMatricesTexture();
  19889. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  19890. if ( colorsTexture ) {
  19891. colorsTexture.dispose();
  19892. this._initColorsTexture();
  19893. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  19894. }
  19895. }
  19896. /**
  19897. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  19898. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  19899. * end of the geometry attributes then an error is thrown.
  19900. *
  19901. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  19902. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  19903. */
  19904. setGeometrySize( maxVertexCount, maxIndexCount ) {
  19905. // Check if we can shrink to the requested vertex attribute size
  19906. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  19907. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  19908. if ( requiredVertexLength > maxVertexCount ) {
  19909. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  19910. }
  19911. // Check if we can shrink to the requested index attribute size
  19912. if ( this.geometry.index ) {
  19913. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  19914. if ( requiredIndexLength > maxIndexCount ) {
  19915. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  19916. }
  19917. }
  19918. //
  19919. // dispose of the previous geometry
  19920. const oldGeometry = this.geometry;
  19921. oldGeometry.dispose();
  19922. // recreate the geometry needed based on the previous variant
  19923. this._maxVertexCount = maxVertexCount;
  19924. this._maxIndexCount = maxIndexCount;
  19925. if ( this._geometryInitialized ) {
  19926. this._geometryInitialized = false;
  19927. this.geometry = new BufferGeometry();
  19928. this._initializeGeometry( oldGeometry );
  19929. }
  19930. // copy data from the previous geometry
  19931. const geometry = this.geometry;
  19932. if ( oldGeometry.index ) {
  19933. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  19934. }
  19935. for ( const key in oldGeometry.attributes ) {
  19936. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  19937. }
  19938. }
  19939. raycast( raycaster, intersects ) {
  19940. const instanceInfo = this._instanceInfo;
  19941. const geometryInfoList = this._geometryInfo;
  19942. const matrixWorld = this.matrixWorld;
  19943. const batchGeometry = this.geometry;
  19944. // iterate over each geometry
  19945. _mesh.material = this.material;
  19946. _mesh.geometry.index = batchGeometry.index;
  19947. _mesh.geometry.attributes = batchGeometry.attributes;
  19948. if ( _mesh.geometry.boundingBox === null ) {
  19949. _mesh.geometry.boundingBox = new Box3();
  19950. }
  19951. if ( _mesh.geometry.boundingSphere === null ) {
  19952. _mesh.geometry.boundingSphere = new Sphere();
  19953. }
  19954. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19955. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  19956. continue;
  19957. }
  19958. const geometryId = instanceInfo[ i ].geometryIndex;
  19959. const geometryInfo = geometryInfoList[ geometryId ];
  19960. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  19961. // get the intersects
  19962. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  19963. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  19964. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  19965. _mesh.raycast( raycaster, _batchIntersects );
  19966. // add batch id to the intersects
  19967. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  19968. const intersect = _batchIntersects[ j ];
  19969. intersect.object = this;
  19970. intersect.batchId = i;
  19971. intersects.push( intersect );
  19972. }
  19973. _batchIntersects.length = 0;
  19974. }
  19975. _mesh.material = null;
  19976. _mesh.geometry.index = null;
  19977. _mesh.geometry.attributes = {};
  19978. _mesh.geometry.setDrawRange( 0, Infinity );
  19979. }
  19980. copy( source ) {
  19981. super.copy( source );
  19982. this.geometry = source.geometry.clone();
  19983. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  19984. this.sortObjects = source.sortObjects;
  19985. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  19986. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  19987. this._geometryInfo = source._geometryInfo.map( info => ( {
  19988. ...info,
  19989. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  19990. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  19991. } ) );
  19992. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  19993. this._availableInstanceIds = source._availableInstanceIds.slice();
  19994. this._availableGeometryIds = source._availableGeometryIds.slice();
  19995. this._nextIndexStart = source._nextIndexStart;
  19996. this._nextVertexStart = source._nextVertexStart;
  19997. this._geometryCount = source._geometryCount;
  19998. this._maxInstanceCount = source._maxInstanceCount;
  19999. this._maxVertexCount = source._maxVertexCount;
  20000. this._maxIndexCount = source._maxIndexCount;
  20001. this._geometryInitialized = source._geometryInitialized;
  20002. this._multiDrawCounts = source._multiDrawCounts.slice();
  20003. this._multiDrawStarts = source._multiDrawStarts.slice();
  20004. this._indirectTexture = source._indirectTexture.clone();
  20005. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20006. this._matricesTexture = source._matricesTexture.clone();
  20007. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20008. if ( this._colorsTexture !== null ) {
  20009. this._colorsTexture = source._colorsTexture.clone();
  20010. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20011. }
  20012. return this;
  20013. }
  20014. /**
  20015. * Frees the GPU-related resources allocated by this instance. Call this
  20016. * method whenever this instance is no longer used in your app.
  20017. */
  20018. dispose() {
  20019. // Assuming the geometry is not shared with other meshes
  20020. this.geometry.dispose();
  20021. this._matricesTexture.dispose();
  20022. this._matricesTexture = null;
  20023. this._indirectTexture.dispose();
  20024. this._indirectTexture = null;
  20025. if ( this._colorsTexture !== null ) {
  20026. this._colorsTexture.dispose();
  20027. this._colorsTexture = null;
  20028. }
  20029. }
  20030. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20031. // if visibility has not changed and frustum culling and object sorting is not required
  20032. // then skip iterating over all items
  20033. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20034. return;
  20035. }
  20036. // the indexed version of the multi draw function requires specifying the start
  20037. // offset in bytes.
  20038. const index = geometry.getIndex();
  20039. let bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20040. // the "wireframe" attribute implicitly creates a line attribute in the renderer, which is double
  20041. // the vertices to draw (3 lines per triangle) so we multiply the draw counts / starts and make
  20042. // assumptions about the index buffer byte size.
  20043. let multiDrawMultiplier = 1;
  20044. if ( material.wireframe ) {
  20045. multiDrawMultiplier = 2;
  20046. bytesPerElement = geometry.attributes.position.count > 65535 ? 4 : 2;
  20047. }
  20048. const instanceInfo = this._instanceInfo;
  20049. const multiDrawStarts = this._multiDrawStarts;
  20050. const multiDrawCounts = this._multiDrawCounts;
  20051. const geometryInfoList = this._geometryInfo;
  20052. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20053. const indirectTexture = this._indirectTexture;
  20054. const indirectArray = indirectTexture.image.data;
  20055. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20056. // prepare the frustum in the local frame
  20057. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20058. _matrix$1
  20059. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20060. .multiply( this.matrixWorld );
  20061. _frustum.setFromProjectionMatrix(
  20062. _matrix$1,
  20063. camera.coordinateSystem,
  20064. camera.reversedDepth
  20065. );
  20066. }
  20067. let multiDrawCount = 0;
  20068. if ( this.sortObjects ) {
  20069. // get the camera position in the local frame
  20070. _matrix$1.copy( this.matrixWorld ).invert();
  20071. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20072. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20073. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20074. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20075. const geometryId = instanceInfo[ i ].geometryIndex;
  20076. // get the bounds in world space
  20077. this.getMatrixAt( i, _matrix$1 );
  20078. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20079. // determine whether the batched geometry is within the frustum
  20080. let culled = false;
  20081. if ( perObjectFrustumCulled ) {
  20082. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20083. }
  20084. if ( ! culled ) {
  20085. // get the distance from camera used for sorting
  20086. const geometryInfo = geometryInfoList[ geometryId ];
  20087. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20088. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20089. }
  20090. }
  20091. }
  20092. // Sort the draw ranges and prep for rendering
  20093. const list = _renderList.list;
  20094. const customSort = this.customSort;
  20095. if ( customSort === null ) {
  20096. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20097. } else {
  20098. customSort.call( this, list, camera );
  20099. }
  20100. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20101. const item = list[ i ];
  20102. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement * multiDrawMultiplier;
  20103. multiDrawCounts[ multiDrawCount ] = item.count * multiDrawMultiplier;
  20104. indirectArray[ multiDrawCount ] = item.index;
  20105. multiDrawCount ++;
  20106. }
  20107. _renderList.reset();
  20108. } else {
  20109. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20110. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20111. const geometryId = instanceInfo[ i ].geometryIndex;
  20112. // determine whether the batched geometry is within the frustum
  20113. let culled = false;
  20114. if ( perObjectFrustumCulled ) {
  20115. // get the bounds in world space
  20116. this.getMatrixAt( i, _matrix$1 );
  20117. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20118. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20119. }
  20120. if ( ! culled ) {
  20121. const geometryInfo = geometryInfoList[ geometryId ];
  20122. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement * multiDrawMultiplier;
  20123. multiDrawCounts[ multiDrawCount ] = geometryInfo.count * multiDrawMultiplier;
  20124. indirectArray[ multiDrawCount ] = i;
  20125. multiDrawCount ++;
  20126. }
  20127. }
  20128. }
  20129. }
  20130. indirectTexture.needsUpdate = true;
  20131. this._multiDrawCount = multiDrawCount;
  20132. this._visibilityChanged = false;
  20133. }
  20134. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20135. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20136. }
  20137. }
  20138. /**
  20139. * A material for rendering line primitives.
  20140. *
  20141. * Materials define the appearance of renderable 3D objects.
  20142. *
  20143. * ```js
  20144. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20145. * ```
  20146. *
  20147. * @augments Material
  20148. */
  20149. class LineBasicMaterial extends Material {
  20150. /**
  20151. * Constructs a new line basic material.
  20152. *
  20153. * @param {Object} [parameters] - An object with one or more properties
  20154. * defining the material's appearance. Any property of the material
  20155. * (including any property from inherited materials) can be passed
  20156. * in here. Color values can be passed any type of value accepted
  20157. * by {@link Color#set}.
  20158. */
  20159. constructor( parameters ) {
  20160. super();
  20161. /**
  20162. * This flag can be used for type testing.
  20163. *
  20164. * @type {boolean}
  20165. * @readonly
  20166. * @default true
  20167. */
  20168. this.isLineBasicMaterial = true;
  20169. this.type = 'LineBasicMaterial';
  20170. /**
  20171. * Color of the material.
  20172. *
  20173. * @type {Color}
  20174. * @default (1,1,1)
  20175. */
  20176. this.color = new Color( 0xffffff );
  20177. /**
  20178. * Sets the color of the lines using data from a texture. The texture map
  20179. * color is modulated by the diffuse `color`.
  20180. *
  20181. * @type {?Texture}
  20182. * @default null
  20183. */
  20184. this.map = null;
  20185. /**
  20186. * Controls line thickness or lines.
  20187. *
  20188. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20189. * ignore this setting and always render line primitives with a
  20190. * width of one pixel.
  20191. *
  20192. * @type {number}
  20193. * @default 1
  20194. */
  20195. this.linewidth = 1;
  20196. /**
  20197. * Defines appearance of line ends.
  20198. *
  20199. * Can only be used with {@link SVGRenderer}.
  20200. *
  20201. * @type {('butt'|'round'|'square')}
  20202. * @default 'round'
  20203. */
  20204. this.linecap = 'round';
  20205. /**
  20206. * Defines appearance of line joints.
  20207. *
  20208. * Can only be used with {@link SVGRenderer}.
  20209. *
  20210. * @type {('round'|'bevel'|'miter')}
  20211. * @default 'round'
  20212. */
  20213. this.linejoin = 'round';
  20214. /**
  20215. * Whether the material is affected by fog or not.
  20216. *
  20217. * @type {boolean}
  20218. * @default true
  20219. */
  20220. this.fog = true;
  20221. this.setValues( parameters );
  20222. }
  20223. copy( source ) {
  20224. super.copy( source );
  20225. this.color.copy( source.color );
  20226. this.map = source.map;
  20227. this.linewidth = source.linewidth;
  20228. this.linecap = source.linecap;
  20229. this.linejoin = source.linejoin;
  20230. this.fog = source.fog;
  20231. return this;
  20232. }
  20233. }
  20234. const _vStart = /*@__PURE__*/ new Vector3();
  20235. const _vEnd = /*@__PURE__*/ new Vector3();
  20236. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20237. const _ray$1 = /*@__PURE__*/ new Ray();
  20238. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20239. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20240. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20241. /**
  20242. * A continuous line. The line are rendered by connecting consecutive
  20243. * vertices with straight lines.
  20244. *
  20245. * ```js
  20246. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20247. *
  20248. * const points = [];
  20249. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20250. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20251. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20252. *
  20253. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20254. *
  20255. * const line = new THREE.Line( geometry, material );
  20256. * scene.add( line );
  20257. * ```
  20258. *
  20259. * @augments Object3D
  20260. */
  20261. class Line extends Object3D {
  20262. /**
  20263. * Constructs a new line.
  20264. *
  20265. * @param {BufferGeometry} [geometry] - The line geometry.
  20266. * @param {Material|Array<Material>} [material] - The line material.
  20267. */
  20268. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20269. super();
  20270. /**
  20271. * This flag can be used for type testing.
  20272. *
  20273. * @type {boolean}
  20274. * @readonly
  20275. * @default true
  20276. */
  20277. this.isLine = true;
  20278. this.type = 'Line';
  20279. /**
  20280. * The line geometry.
  20281. *
  20282. * @type {BufferGeometry}
  20283. */
  20284. this.geometry = geometry;
  20285. /**
  20286. * The line material.
  20287. *
  20288. * @type {Material|Array<Material>}
  20289. * @default LineBasicMaterial
  20290. */
  20291. this.material = material;
  20292. /**
  20293. * A dictionary representing the morph targets in the geometry. The key is the
  20294. * morph targets name, the value its attribute index. This member is `undefined`
  20295. * by default and only set when morph targets are detected in the geometry.
  20296. *
  20297. * @type {Object<string,number>|undefined}
  20298. * @default undefined
  20299. */
  20300. this.morphTargetDictionary = undefined;
  20301. /**
  20302. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20303. * is applied. This member is `undefined` by default and only set when morph targets are
  20304. * detected in the geometry.
  20305. *
  20306. * @type {Array<number>|undefined}
  20307. * @default undefined
  20308. */
  20309. this.morphTargetInfluences = undefined;
  20310. this.updateMorphTargets();
  20311. }
  20312. copy( source, recursive ) {
  20313. super.copy( source, recursive );
  20314. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20315. this.geometry = source.geometry;
  20316. return this;
  20317. }
  20318. /**
  20319. * Computes an array of distance values which are necessary for rendering dashed lines.
  20320. * For each vertex in the geometry, the method calculates the cumulative length from the
  20321. * current point to the very beginning of the line.
  20322. *
  20323. * @return {Line} A reference to this line.
  20324. */
  20325. computeLineDistances() {
  20326. const geometry = this.geometry;
  20327. // we assume non-indexed geometry
  20328. if ( geometry.index === null ) {
  20329. const positionAttribute = geometry.attributes.position;
  20330. const lineDistances = [ 0 ];
  20331. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20332. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20333. _vEnd.fromBufferAttribute( positionAttribute, i );
  20334. lineDistances[ i ] = lineDistances[ i - 1 ];
  20335. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20336. }
  20337. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20338. } else {
  20339. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20340. }
  20341. return this;
  20342. }
  20343. /**
  20344. * Computes intersection points between a casted ray and this line.
  20345. *
  20346. * @param {Raycaster} raycaster - The raycaster.
  20347. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20348. */
  20349. raycast( raycaster, intersects ) {
  20350. const geometry = this.geometry;
  20351. const matrixWorld = this.matrixWorld;
  20352. const threshold = raycaster.params.Line.threshold;
  20353. const drawRange = geometry.drawRange;
  20354. // Checking boundingSphere distance to ray
  20355. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20356. _sphere$1.copy( geometry.boundingSphere );
  20357. _sphere$1.applyMatrix4( matrixWorld );
  20358. _sphere$1.radius += threshold;
  20359. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20360. //
  20361. _inverseMatrix$1.copy( matrixWorld ).invert();
  20362. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20363. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20364. const localThresholdSq = localThreshold * localThreshold;
  20365. const step = this.isLineSegments ? 2 : 1;
  20366. const index = geometry.index;
  20367. const attributes = geometry.attributes;
  20368. const positionAttribute = attributes.position;
  20369. if ( index !== null ) {
  20370. const start = Math.max( 0, drawRange.start );
  20371. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20372. for ( let i = start, l = end - 1; i < l; i += step ) {
  20373. const a = index.getX( i );
  20374. const b = index.getX( i + 1 );
  20375. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  20376. if ( intersect ) {
  20377. intersects.push( intersect );
  20378. }
  20379. }
  20380. if ( this.isLineLoop ) {
  20381. const a = index.getX( end - 1 );
  20382. const b = index.getX( start );
  20383. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  20384. if ( intersect ) {
  20385. intersects.push( intersect );
  20386. }
  20387. }
  20388. } else {
  20389. const start = Math.max( 0, drawRange.start );
  20390. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20391. for ( let i = start, l = end - 1; i < l; i += step ) {
  20392. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  20393. if ( intersect ) {
  20394. intersects.push( intersect );
  20395. }
  20396. }
  20397. if ( this.isLineLoop ) {
  20398. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  20399. if ( intersect ) {
  20400. intersects.push( intersect );
  20401. }
  20402. }
  20403. }
  20404. }
  20405. /**
  20406. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  20407. * to make sure existing morph targets can influence this 3D object.
  20408. */
  20409. updateMorphTargets() {
  20410. const geometry = this.geometry;
  20411. const morphAttributes = geometry.morphAttributes;
  20412. const keys = Object.keys( morphAttributes );
  20413. if ( keys.length > 0 ) {
  20414. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20415. if ( morphAttribute !== undefined ) {
  20416. this.morphTargetInfluences = [];
  20417. this.morphTargetDictionary = {};
  20418. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20419. const name = morphAttribute[ m ].name || String( m );
  20420. this.morphTargetInfluences.push( 0 );
  20421. this.morphTargetDictionary[ name ] = m;
  20422. }
  20423. }
  20424. }
  20425. }
  20426. }
  20427. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  20428. const positionAttribute = object.geometry.attributes.position;
  20429. _vStart.fromBufferAttribute( positionAttribute, a );
  20430. _vEnd.fromBufferAttribute( positionAttribute, b );
  20431. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20432. if ( distSq > thresholdSq ) return;
  20433. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20434. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20435. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20436. return {
  20437. distance: distance,
  20438. // What do we want? intersection point on the ray or on the segment??
  20439. // point: raycaster.ray.at( distance ),
  20440. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20441. index: i,
  20442. face: null,
  20443. faceIndex: null,
  20444. barycoord: null,
  20445. object: object
  20446. };
  20447. }
  20448. const _start = /*@__PURE__*/ new Vector3();
  20449. const _end = /*@__PURE__*/ new Vector3();
  20450. /**
  20451. * A series of lines drawn between pairs of vertices.
  20452. *
  20453. * @augments Line
  20454. */
  20455. class LineSegments extends Line {
  20456. /**
  20457. * Constructs a new line segments.
  20458. *
  20459. * @param {BufferGeometry} [geometry] - The line geometry.
  20460. * @param {Material|Array<Material>} [material] - The line material.
  20461. */
  20462. constructor( geometry, material ) {
  20463. super( geometry, material );
  20464. /**
  20465. * This flag can be used for type testing.
  20466. *
  20467. * @type {boolean}
  20468. * @readonly
  20469. * @default true
  20470. */
  20471. this.isLineSegments = true;
  20472. this.type = 'LineSegments';
  20473. }
  20474. computeLineDistances() {
  20475. const geometry = this.geometry;
  20476. // we assume non-indexed geometry
  20477. if ( geometry.index === null ) {
  20478. const positionAttribute = geometry.attributes.position;
  20479. const lineDistances = [];
  20480. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20481. _start.fromBufferAttribute( positionAttribute, i );
  20482. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20483. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20484. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20485. }
  20486. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20487. } else {
  20488. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20489. }
  20490. return this;
  20491. }
  20492. }
  20493. /**
  20494. * A continuous line. This is nearly the same as {@link Line} the only difference
  20495. * is that the last vertex is connected with the first vertex in order to close
  20496. * the line to form a loop.
  20497. *
  20498. * @augments Line
  20499. */
  20500. class LineLoop extends Line {
  20501. /**
  20502. * Constructs a new line loop.
  20503. *
  20504. * @param {BufferGeometry} [geometry] - The line geometry.
  20505. * @param {Material|Array<Material>} [material] - The line material.
  20506. */
  20507. constructor( geometry, material ) {
  20508. super( geometry, material );
  20509. /**
  20510. * This flag can be used for type testing.
  20511. *
  20512. * @type {boolean}
  20513. * @readonly
  20514. * @default true
  20515. */
  20516. this.isLineLoop = true;
  20517. this.type = 'LineLoop';
  20518. }
  20519. }
  20520. /**
  20521. * A material for rendering point primitives.
  20522. *
  20523. * Materials define the appearance of renderable 3D objects.
  20524. *
  20525. * ```js
  20526. * const vertices = [];
  20527. *
  20528. * for ( let i = 0; i < 10000; i ++ ) {
  20529. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  20530. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  20531. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  20532. *
  20533. * vertices.push( x, y, z );
  20534. * }
  20535. *
  20536. * const geometry = new THREE.BufferGeometry();
  20537. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  20538. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  20539. * const points = new THREE.Points( geometry, material );
  20540. * scene.add( points );
  20541. * ```
  20542. *
  20543. * @augments Material
  20544. */
  20545. class PointsMaterial extends Material {
  20546. /**
  20547. * Constructs a new points material.
  20548. *
  20549. * @param {Object} [parameters] - An object with one or more properties
  20550. * defining the material's appearance. Any property of the material
  20551. * (including any property from inherited materials) can be passed
  20552. * in here. Color values can be passed any type of value accepted
  20553. * by {@link Color#set}.
  20554. */
  20555. constructor( parameters ) {
  20556. super();
  20557. /**
  20558. * This flag can be used for type testing.
  20559. *
  20560. * @type {boolean}
  20561. * @readonly
  20562. * @default true
  20563. */
  20564. this.isPointsMaterial = true;
  20565. this.type = 'PointsMaterial';
  20566. /**
  20567. * Color of the material.
  20568. *
  20569. * @type {Color}
  20570. * @default (1,1,1)
  20571. */
  20572. this.color = new Color( 0xffffff );
  20573. /**
  20574. * The color map. May optionally include an alpha channel, typically combined
  20575. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  20576. * color is modulated by the diffuse `color`.
  20577. *
  20578. * @type {?Texture}
  20579. * @default null
  20580. */
  20581. this.map = null;
  20582. /**
  20583. * The alpha map is a grayscale texture that controls the opacity across the
  20584. * surface (black: fully transparent; white: fully opaque).
  20585. *
  20586. * Only the color of the texture is used, ignoring the alpha channel if one
  20587. * exists. For RGB and RGBA textures, the renderer will use the green channel
  20588. * when sampling this texture due to the extra bit of precision provided for
  20589. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  20590. * luminance/alpha textures will also still work as expected.
  20591. *
  20592. * @type {?Texture}
  20593. * @default null
  20594. */
  20595. this.alphaMap = null;
  20596. /**
  20597. * Defines the size of the points in pixels.
  20598. *
  20599. * 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).
  20600. *
  20601. * @type {number}
  20602. * @default 1
  20603. */
  20604. this.size = 1;
  20605. /**
  20606. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  20607. *
  20608. * @type {boolean}
  20609. * @default true
  20610. */
  20611. this.sizeAttenuation = true;
  20612. /**
  20613. * Whether the material is affected by fog or not.
  20614. *
  20615. * @type {boolean}
  20616. * @default true
  20617. */
  20618. this.fog = true;
  20619. this.setValues( parameters );
  20620. }
  20621. copy( source ) {
  20622. super.copy( source );
  20623. this.color.copy( source.color );
  20624. this.map = source.map;
  20625. this.alphaMap = source.alphaMap;
  20626. this.size = source.size;
  20627. this.sizeAttenuation = source.sizeAttenuation;
  20628. this.fog = source.fog;
  20629. return this;
  20630. }
  20631. }
  20632. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20633. const _ray = /*@__PURE__*/ new Ray();
  20634. const _sphere = /*@__PURE__*/ new Sphere();
  20635. const _position$3 = /*@__PURE__*/ new Vector3();
  20636. /**
  20637. * A class for displaying points or point clouds.
  20638. *
  20639. * @augments Object3D
  20640. */
  20641. class Points extends Object3D {
  20642. /**
  20643. * Constructs a new point cloud.
  20644. *
  20645. * @param {BufferGeometry} [geometry] - The points geometry.
  20646. * @param {Material|Array<Material>} [material] - The points material.
  20647. */
  20648. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20649. super();
  20650. /**
  20651. * This flag can be used for type testing.
  20652. *
  20653. * @type {boolean}
  20654. * @readonly
  20655. * @default true
  20656. */
  20657. this.isPoints = true;
  20658. this.type = 'Points';
  20659. /**
  20660. * The points geometry.
  20661. *
  20662. * @type {BufferGeometry}
  20663. */
  20664. this.geometry = geometry;
  20665. /**
  20666. * The line material.
  20667. *
  20668. * @type {Material|Array<Material>}
  20669. * @default PointsMaterial
  20670. */
  20671. this.material = material;
  20672. /**
  20673. * A dictionary representing the morph targets in the geometry. The key is the
  20674. * morph targets name, the value its attribute index. This member is `undefined`
  20675. * by default and only set when morph targets are detected in the geometry.
  20676. *
  20677. * @type {Object<string,number>|undefined}
  20678. * @default undefined
  20679. */
  20680. this.morphTargetDictionary = undefined;
  20681. /**
  20682. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20683. * is applied. This member is `undefined` by default and only set when morph targets are
  20684. * detected in the geometry.
  20685. *
  20686. * @type {Array<number>|undefined}
  20687. * @default undefined
  20688. */
  20689. this.morphTargetInfluences = undefined;
  20690. this.updateMorphTargets();
  20691. }
  20692. copy( source, recursive ) {
  20693. super.copy( source, recursive );
  20694. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20695. this.geometry = source.geometry;
  20696. return this;
  20697. }
  20698. /**
  20699. * Computes intersection points between a casted ray and this point cloud.
  20700. *
  20701. * @param {Raycaster} raycaster - The raycaster.
  20702. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20703. */
  20704. raycast( raycaster, intersects ) {
  20705. const geometry = this.geometry;
  20706. const matrixWorld = this.matrixWorld;
  20707. const threshold = raycaster.params.Points.threshold;
  20708. const drawRange = geometry.drawRange;
  20709. // Checking boundingSphere distance to ray
  20710. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20711. _sphere.copy( geometry.boundingSphere );
  20712. _sphere.applyMatrix4( matrixWorld );
  20713. _sphere.radius += threshold;
  20714. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20715. //
  20716. _inverseMatrix.copy( matrixWorld ).invert();
  20717. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20718. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20719. const localThresholdSq = localThreshold * localThreshold;
  20720. const index = geometry.index;
  20721. const attributes = geometry.attributes;
  20722. const positionAttribute = attributes.position;
  20723. if ( index !== null ) {
  20724. const start = Math.max( 0, drawRange.start );
  20725. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20726. for ( let i = start, il = end; i < il; i ++ ) {
  20727. const a = index.getX( i );
  20728. _position$3.fromBufferAttribute( positionAttribute, a );
  20729. testPoint( _position$3, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20730. }
  20731. } else {
  20732. const start = Math.max( 0, drawRange.start );
  20733. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20734. for ( let i = start, l = end; i < l; i ++ ) {
  20735. _position$3.fromBufferAttribute( positionAttribute, i );
  20736. testPoint( _position$3, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20737. }
  20738. }
  20739. }
  20740. /**
  20741. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  20742. * to make sure existing morph targets can influence this 3D object.
  20743. */
  20744. updateMorphTargets() {
  20745. const geometry = this.geometry;
  20746. const morphAttributes = geometry.morphAttributes;
  20747. const keys = Object.keys( morphAttributes );
  20748. if ( keys.length > 0 ) {
  20749. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20750. if ( morphAttribute !== undefined ) {
  20751. this.morphTargetInfluences = [];
  20752. this.morphTargetDictionary = {};
  20753. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20754. const name = morphAttribute[ m ].name || String( m );
  20755. this.morphTargetInfluences.push( 0 );
  20756. this.morphTargetDictionary[ name ] = m;
  20757. }
  20758. }
  20759. }
  20760. }
  20761. }
  20762. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20763. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20764. if ( rayPointDistanceSq < localThresholdSq ) {
  20765. const intersectPoint = new Vector3();
  20766. _ray.closestPointToPoint( point, intersectPoint );
  20767. intersectPoint.applyMatrix4( matrixWorld );
  20768. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20769. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20770. intersects.push( {
  20771. distance: distance,
  20772. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20773. point: intersectPoint,
  20774. index: index,
  20775. face: null,
  20776. faceIndex: null,
  20777. barycoord: null,
  20778. object: object
  20779. } );
  20780. }
  20781. }
  20782. /**
  20783. * A texture for use with a video.
  20784. *
  20785. * ```js
  20786. * // assuming you have created a HTML video element with id="video"
  20787. * const video = document.getElementById( 'video' );
  20788. * const texture = new THREE.VideoTexture( video );
  20789. * ```
  20790. *
  20791. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  20792. * set to THREE.SRGBColorSpace.
  20793. *
  20794. * Note: After the initial use of a texture, its dimensions, format, and type
  20795. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  20796. *
  20797. * @augments Texture
  20798. */
  20799. class VideoTexture extends Texture {
  20800. /**
  20801. * Constructs a new video texture.
  20802. *
  20803. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  20804. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20805. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20806. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20807. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20808. * @param {number} [minFilter=LinearFilter] - The min filter value.
  20809. * @param {number} [format=RGBAFormat] - The texture format.
  20810. * @param {number} [type=UnsignedByteType] - The texture type.
  20811. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20812. */
  20813. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  20814. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20815. /**
  20816. * This flag can be used for type testing.
  20817. *
  20818. * @type {boolean}
  20819. * @readonly
  20820. * @default true
  20821. */
  20822. this.isVideoTexture = true;
  20823. /**
  20824. * Whether to generate mipmaps (if possible) for a texture.
  20825. *
  20826. * Overwritten and set to `false` by default.
  20827. *
  20828. * @type {boolean}
  20829. * @default false
  20830. */
  20831. this.generateMipmaps = false;
  20832. /**
  20833. * The video frame request callback identifier, which is a positive integer.
  20834. *
  20835. * Value of 0 represents no scheduled rVFC.
  20836. *
  20837. * @private
  20838. * @type {number}
  20839. */
  20840. this._requestVideoFrameCallbackId = 0;
  20841. const scope = this;
  20842. function updateVideo() {
  20843. scope.needsUpdate = true;
  20844. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  20845. }
  20846. if ( 'requestVideoFrameCallback' in video ) {
  20847. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  20848. }
  20849. }
  20850. clone() {
  20851. return new this.constructor( this.image ).copy( this );
  20852. }
  20853. /**
  20854. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  20855. * to `true` every time a new frame is available.
  20856. *
  20857. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  20858. */
  20859. update() {
  20860. const video = this.image;
  20861. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20862. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20863. this.needsUpdate = true;
  20864. }
  20865. }
  20866. dispose() {
  20867. if ( this._requestVideoFrameCallbackId !== 0 ) {
  20868. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  20869. this._requestVideoFrameCallbackId = 0;
  20870. }
  20871. super.dispose();
  20872. }
  20873. }
  20874. /**
  20875. * This class can be used as an alternative way to define video data. Instead of using
  20876. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  20877. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  20878. * video frames are decoded with the WebCodecs API.
  20879. *
  20880. * ```js
  20881. * const texture = new THREE.VideoFrameTexture();
  20882. * texture.setFrame( frame );
  20883. * ```
  20884. *
  20885. * @augments VideoTexture
  20886. */
  20887. class VideoFrameTexture extends VideoTexture {
  20888. /**
  20889. * Constructs a new video frame texture.
  20890. *
  20891. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20892. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20893. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20894. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20895. * @param {number} [minFilter=LinearFilter] - The min filter value.
  20896. * @param {number} [format=RGBAFormat] - The texture format.
  20897. * @param {number} [type=UnsignedByteType] - The texture type.
  20898. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20899. */
  20900. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20901. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20902. /**
  20903. * This flag can be used for type testing.
  20904. *
  20905. * @type {boolean}
  20906. * @readonly
  20907. * @default true
  20908. */
  20909. this.isVideoFrameTexture = true;
  20910. }
  20911. /**
  20912. * This method overwritten with an empty implementation since
  20913. * this type of texture is updated via `setFrame()`.
  20914. */
  20915. update() {}
  20916. clone() {
  20917. return new this.constructor().copy( this ); // restoring Texture.clone()
  20918. }
  20919. /**
  20920. * Sets the current frame of the video. This will automatically update the texture
  20921. * so the data can be used for rendering.
  20922. *
  20923. * @param {VideoFrame} frame - The video frame.
  20924. */
  20925. setFrame( frame ) {
  20926. this.image = frame;
  20927. this.needsUpdate = true;
  20928. }
  20929. }
  20930. /**
  20931. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  20932. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  20933. * as a texture for further usage.
  20934. *
  20935. * ```js
  20936. * const pixelRatio = window.devicePixelRatio;
  20937. * const textureSize = 128 * pixelRatio;
  20938. *
  20939. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  20940. *
  20941. * // calculate start position for copying part of the frame data
  20942. * const vector = new Vector2();
  20943. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  20944. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  20945. *
  20946. * renderer.render( scene, camera );
  20947. *
  20948. * // copy part of the rendered frame into the framebuffer texture
  20949. * renderer.copyFramebufferToTexture( frameTexture, vector );
  20950. * ```
  20951. *
  20952. * @augments Texture
  20953. */
  20954. class FramebufferTexture extends Texture {
  20955. /**
  20956. * Constructs a new framebuffer texture.
  20957. *
  20958. * @param {number} [width] - The width of the texture.
  20959. * @param {number} [height] - The height of the texture.
  20960. */
  20961. constructor( width, height ) {
  20962. super( { width, height } );
  20963. /**
  20964. * This flag can be used for type testing.
  20965. *
  20966. * @type {boolean}
  20967. * @readonly
  20968. * @default true
  20969. */
  20970. this.isFramebufferTexture = true;
  20971. /**
  20972. * How the texture is sampled when a texel covers more than one pixel.
  20973. *
  20974. * Overwritten and set to `NearestFilter` by default to disable filtering.
  20975. *
  20976. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  20977. * @default NearestFilter
  20978. */
  20979. this.magFilter = NearestFilter;
  20980. /**
  20981. * How the texture is sampled when a texel covers less than one pixel.
  20982. *
  20983. * Overwritten and set to `NearestFilter` by default to disable filtering.
  20984. *
  20985. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  20986. * @default NearestFilter
  20987. */
  20988. this.minFilter = NearestFilter;
  20989. /**
  20990. * Whether to generate mipmaps (if possible) for a texture.
  20991. *
  20992. * Overwritten and set to `false` by default.
  20993. *
  20994. * @type {boolean}
  20995. * @default false
  20996. */
  20997. this.generateMipmaps = false;
  20998. this.needsUpdate = true;
  20999. }
  21000. }
  21001. /**
  21002. * Creates a texture based on data in compressed form.
  21003. *
  21004. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21005. *
  21006. * @augments Texture
  21007. */
  21008. class CompressedTexture extends Texture {
  21009. /**
  21010. * Constructs a new compressed texture.
  21011. *
  21012. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21013. * the data and dimensions.
  21014. * @param {number} width - The width of the texture.
  21015. * @param {number} height - The height of the texture.
  21016. * @param {number} [format=RGBAFormat] - The texture format.
  21017. * @param {number} [type=UnsignedByteType] - The texture type.
  21018. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21019. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21020. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21021. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21022. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21023. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21024. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21025. */
  21026. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21027. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21028. /**
  21029. * This flag can be used for type testing.
  21030. *
  21031. * @type {boolean}
  21032. * @readonly
  21033. * @default true
  21034. */
  21035. this.isCompressedTexture = true;
  21036. /**
  21037. * The image property of a compressed texture just defines its dimensions.
  21038. *
  21039. * @type {{width:number,height:number}}
  21040. */
  21041. this.image = { width: width, height: height };
  21042. /**
  21043. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21044. *
  21045. * @type {Array<Object>}
  21046. */
  21047. this.mipmaps = mipmaps;
  21048. /**
  21049. * If set to `true`, the texture is flipped along the vertical axis when
  21050. * uploaded to the GPU.
  21051. *
  21052. * Overwritten and set to `false` by default since it is not possible to
  21053. * flip compressed textures.
  21054. *
  21055. * @type {boolean}
  21056. * @default false
  21057. * @readonly
  21058. */
  21059. this.flipY = false;
  21060. /**
  21061. * Whether to generate mipmaps (if possible) for a texture.
  21062. *
  21063. * Overwritten and set to `false` by default since it is not
  21064. * possible to generate mipmaps for compressed data. Mipmaps
  21065. * must be embedded in the compressed texture file.
  21066. *
  21067. * @type {boolean}
  21068. * @default false
  21069. * @readonly
  21070. */
  21071. this.generateMipmaps = false;
  21072. }
  21073. }
  21074. /**
  21075. * Creates a texture 2D array based on data in compressed form.
  21076. *
  21077. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21078. *
  21079. * @augments CompressedTexture
  21080. */
  21081. class CompressedArrayTexture extends CompressedTexture {
  21082. /**
  21083. * Constructs a new compressed array texture.
  21084. *
  21085. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21086. * the data and dimensions.
  21087. * @param {number} width - The width of the texture.
  21088. * @param {number} height - The height of the texture.
  21089. * @param {number} depth - The depth of the texture.
  21090. * @param {number} [format=RGBAFormat] - The min filter value.
  21091. * @param {number} [type=UnsignedByteType] - The min filter value.
  21092. */
  21093. constructor( mipmaps, width, height, depth, format, type ) {
  21094. super( mipmaps, width, height, format, type );
  21095. /**
  21096. * This flag can be used for type testing.
  21097. *
  21098. * @type {boolean}
  21099. * @readonly
  21100. * @default true
  21101. */
  21102. this.isCompressedArrayTexture = true;
  21103. /**
  21104. * The image property of a compressed texture just defines its dimensions.
  21105. *
  21106. * @name CompressedArrayTexture#image
  21107. * @type {{width:number,height:number,depth:number}}
  21108. */
  21109. this.image.depth = depth;
  21110. /**
  21111. * This defines how the texture is wrapped in the depth and corresponds to
  21112. * *W* in UVW mapping.
  21113. *
  21114. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21115. * @default ClampToEdgeWrapping
  21116. */
  21117. this.wrapR = ClampToEdgeWrapping;
  21118. /**
  21119. * A set of all layers which need to be updated in the texture.
  21120. *
  21121. * @type {Set<number>}
  21122. */
  21123. this.layerUpdates = new Set();
  21124. }
  21125. /**
  21126. * Describes that a specific layer of the texture needs to be updated.
  21127. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21128. * entire compressed texture array is sent to the GPU. Marking specific
  21129. * layers will only transmit subsets of all mipmaps associated with a
  21130. * specific depth in the array which is often much more performant.
  21131. *
  21132. * @param {number} layerIndex - The layer index that should be updated.
  21133. */
  21134. addLayerUpdate( layerIndex ) {
  21135. this.layerUpdates.add( layerIndex );
  21136. }
  21137. /**
  21138. * Resets the layer updates registry.
  21139. */
  21140. clearLayerUpdates() {
  21141. this.layerUpdates.clear();
  21142. }
  21143. }
  21144. /**
  21145. * Creates a cube texture based on data in compressed form.
  21146. *
  21147. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21148. *
  21149. * @augments CompressedTexture
  21150. */
  21151. class CompressedCubeTexture extends CompressedTexture {
  21152. /**
  21153. * Constructs a new compressed texture.
  21154. *
  21155. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21156. * @param {number} [format=RGBAFormat] - The texture format.
  21157. * @param {number} [type=UnsignedByteType] - The texture type.
  21158. */
  21159. constructor( images, format, type ) {
  21160. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21161. /**
  21162. * This flag can be used for type testing.
  21163. *
  21164. * @type {boolean}
  21165. * @readonly
  21166. * @default true
  21167. */
  21168. this.isCompressedCubeTexture = true;
  21169. /**
  21170. * This flag can be used for type testing.
  21171. *
  21172. * @type {boolean}
  21173. * @readonly
  21174. * @default true
  21175. */
  21176. this.isCubeTexture = true;
  21177. this.image = images;
  21178. }
  21179. }
  21180. /**
  21181. * Creates a cube texture made up of six images.
  21182. *
  21183. * ```js
  21184. * const loader = new THREE.CubeTextureLoader();
  21185. * loader.setPath( 'textures/cube/pisa/' );
  21186. *
  21187. * const textureCube = loader.load( [
  21188. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  21189. * ] );
  21190. *
  21191. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  21192. * ```
  21193. *
  21194. * @augments Texture
  21195. */
  21196. class CubeTexture extends Texture {
  21197. /**
  21198. * Constructs a new cube texture.
  21199. *
  21200. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  21201. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21202. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21203. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21204. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21205. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21206. * @param {number} [format=RGBAFormat] - The texture format.
  21207. * @param {number} [type=UnsignedByteType] - The texture type.
  21208. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21209. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  21210. */
  21211. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  21212. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21213. /**
  21214. * This flag can be used for type testing.
  21215. *
  21216. * @type {boolean}
  21217. * @readonly
  21218. * @default true
  21219. */
  21220. this.isCubeTexture = true;
  21221. /**
  21222. * If set to `true`, the texture is flipped along the vertical axis when
  21223. * uploaded to the GPU.
  21224. *
  21225. * Overwritten and set to `false` by default.
  21226. *
  21227. * @type {boolean}
  21228. * @default false
  21229. */
  21230. this.flipY = false;
  21231. }
  21232. /**
  21233. * Alias for {@link CubeTexture#image}.
  21234. *
  21235. * @type {Array<Image>}
  21236. */
  21237. get images() {
  21238. return this.image;
  21239. }
  21240. set images( value ) {
  21241. this.image = value;
  21242. }
  21243. }
  21244. /**
  21245. * Creates a texture from a canvas element.
  21246. *
  21247. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21248. * to `true` immediately since a canvas can directly be used for rendering.
  21249. *
  21250. * @augments Texture
  21251. */
  21252. class CanvasTexture extends Texture {
  21253. /**
  21254. * Constructs a new texture.
  21255. *
  21256. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21257. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21258. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21259. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21260. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21261. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21262. * @param {number} [format=RGBAFormat] - The texture format.
  21263. * @param {number} [type=UnsignedByteType] - The texture type.
  21264. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21265. */
  21266. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21267. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21268. /**
  21269. * This flag can be used for type testing.
  21270. *
  21271. * @type {boolean}
  21272. * @readonly
  21273. * @default true
  21274. */
  21275. this.isCanvasTexture = true;
  21276. this.needsUpdate = true;
  21277. }
  21278. }
  21279. /**
  21280. * Creates a texture from an HTML element.
  21281. *
  21282. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21283. * to `true` immediately and listens for the parent canvas's paint events to trigger updates.
  21284. *
  21285. * @augments Texture
  21286. */
  21287. class HTMLTexture extends Texture {
  21288. /**
  21289. * Constructs a new texture.
  21290. *
  21291. * @param {HTMLElement} [element] - The HTML element.
  21292. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21293. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21294. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21295. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21296. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21297. * @param {number} [format=RGBAFormat] - The texture format.
  21298. * @param {number} [type=UnsignedByteType] - The texture type.
  21299. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21300. */
  21301. constructor( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21302. super( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21303. /**
  21304. * This flag can be used for type testing.
  21305. *
  21306. * @type {boolean}
  21307. * @readonly
  21308. * @default true
  21309. */
  21310. this.isHTMLTexture = true;
  21311. this.generateMipmaps = false;
  21312. this.needsUpdate = true;
  21313. const parent = element ? element.parentNode : null;
  21314. if ( parent !== null && 'requestPaint' in parent ) {
  21315. parent.onpaint = () => {
  21316. this.needsUpdate = true;
  21317. };
  21318. parent.requestPaint();
  21319. }
  21320. }
  21321. dispose() {
  21322. const parent = this.image ? this.image.parentNode : null;
  21323. if ( parent !== null && 'onpaint' in parent ) {
  21324. parent.onpaint = null;
  21325. }
  21326. super.dispose();
  21327. }
  21328. }
  21329. /**
  21330. * This class can be used to automatically save the depth information of a
  21331. * rendering into a texture.
  21332. *
  21333. * @augments Texture
  21334. */
  21335. class DepthTexture extends Texture {
  21336. /**
  21337. * Constructs a new depth texture.
  21338. *
  21339. * @param {number} width - The width of the texture.
  21340. * @param {number} height - The height of the texture.
  21341. * @param {number} [type=UnsignedIntType] - The texture type.
  21342. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21343. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21344. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21345. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21346. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21347. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21348. * @param {number} [format=DepthFormat] - The texture format.
  21349. * @param {number} [depth=1] - The depth of the texture.
  21350. */
  21351. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  21352. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21353. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21354. }
  21355. const image = { width: width, height: height, depth: depth };
  21356. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21357. /**
  21358. * This flag can be used for type testing.
  21359. *
  21360. * @type {boolean}
  21361. * @readonly
  21362. * @default true
  21363. */
  21364. this.isDepthTexture = true;
  21365. /**
  21366. * If set to `true`, the texture is flipped along the vertical axis when
  21367. * uploaded to the GPU.
  21368. *
  21369. * Overwritten and set to `false` by default.
  21370. *
  21371. * @type {boolean}
  21372. * @default false
  21373. */
  21374. this.flipY = false;
  21375. /**
  21376. * Whether to generate mipmaps (if possible) for a texture.
  21377. *
  21378. * Overwritten and set to `false` by default.
  21379. *
  21380. * @type {boolean}
  21381. * @default false
  21382. */
  21383. this.generateMipmaps = false;
  21384. /**
  21385. * Code corresponding to the depth compare function.
  21386. *
  21387. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21388. * @default null
  21389. */
  21390. this.compareFunction = null;
  21391. }
  21392. copy( source ) {
  21393. super.copy( source );
  21394. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21395. this.compareFunction = source.compareFunction;
  21396. return this;
  21397. }
  21398. toJSON( meta ) {
  21399. const data = super.toJSON( meta );
  21400. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21401. return data;
  21402. }
  21403. }
  21404. /**
  21405. * This class can be used to automatically save the depth information of a
  21406. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  21407. *
  21408. * @augments DepthTexture
  21409. */
  21410. class CubeDepthTexture extends DepthTexture {
  21411. /**
  21412. * Constructs a new cube depth texture.
  21413. *
  21414. * @param {number} size - The size (width and height) of each cube face.
  21415. * @param {number} [type=UnsignedIntType] - The texture type.
  21416. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21417. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21418. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21419. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  21420. * @param {number} [minFilter=NearestFilter] - The min filter value.
  21421. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21422. * @param {number} [format=DepthFormat] - The texture format.
  21423. */
  21424. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21425. // Create 6 identical image descriptors for the cube faces
  21426. const image = { width: size, height: size, depth: 1 };
  21427. const images = [ image, image, image, image, image, image ];
  21428. // Call DepthTexture constructor with width, height
  21429. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  21430. // Replace the single image with the array of 6 images
  21431. this.image = images;
  21432. /**
  21433. * This flag can be used for type testing.
  21434. *
  21435. * @type {boolean}
  21436. * @readonly
  21437. * @default true
  21438. */
  21439. this.isCubeDepthTexture = true;
  21440. /**
  21441. * Set to true for cube texture handling in WebGLTextures.
  21442. *
  21443. * @type {boolean}
  21444. * @readonly
  21445. * @default true
  21446. */
  21447. this.isCubeTexture = true;
  21448. }
  21449. /**
  21450. * Alias for {@link CubeDepthTexture#image}.
  21451. *
  21452. * @type {Array<Image>}
  21453. */
  21454. get images() {
  21455. return this.image;
  21456. }
  21457. set images( value ) {
  21458. this.image = value;
  21459. }
  21460. }
  21461. /**
  21462. * Represents a texture created externally with the same renderer context.
  21463. *
  21464. * This may be a texture from a protected media stream, device camera feed,
  21465. * or other data feeds like a depth sensor.
  21466. *
  21467. * Note that this class is only supported in {@link WebGLRenderer}, and in
  21468. * the {@link WebGPURenderer} WebGPU backend.
  21469. *
  21470. * @augments Texture
  21471. */
  21472. class ExternalTexture extends Texture {
  21473. /**
  21474. * Creates a new raw texture.
  21475. *
  21476. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  21477. */
  21478. constructor( sourceTexture = null ) {
  21479. super();
  21480. /**
  21481. * The external source texture.
  21482. *
  21483. * @type {?(WebGLTexture|GPUTexture)}
  21484. * @default null
  21485. */
  21486. this.sourceTexture = sourceTexture;
  21487. /**
  21488. * This flag can be used for type testing.
  21489. *
  21490. * @type {boolean}
  21491. * @readonly
  21492. * @default true
  21493. */
  21494. this.isExternalTexture = true;
  21495. }
  21496. copy( source ) {
  21497. super.copy( source );
  21498. this.sourceTexture = source.sourceTexture;
  21499. return this;
  21500. }
  21501. }
  21502. /**
  21503. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  21504. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  21505. * of the axes.
  21506. *
  21507. * ```js
  21508. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  21509. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21510. * const cube = new THREE.Mesh( geometry, material );
  21511. * scene.add( cube );
  21512. * ```
  21513. *
  21514. * @augments BufferGeometry
  21515. * @demo scenes/geometry-browser.html#BoxGeometry
  21516. */
  21517. class BoxGeometry extends BufferGeometry {
  21518. /**
  21519. * Constructs a new box geometry.
  21520. *
  21521. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  21522. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  21523. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  21524. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  21525. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  21526. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  21527. */
  21528. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  21529. super();
  21530. this.type = 'BoxGeometry';
  21531. /**
  21532. * Holds the constructor parameters that have been
  21533. * used to generate the geometry. Any modification
  21534. * after instantiation does not change the geometry.
  21535. *
  21536. * @type {Object}
  21537. */
  21538. this.parameters = {
  21539. width: width,
  21540. height: height,
  21541. depth: depth,
  21542. widthSegments: widthSegments,
  21543. heightSegments: heightSegments,
  21544. depthSegments: depthSegments
  21545. };
  21546. const scope = this;
  21547. // segments
  21548. widthSegments = Math.floor( widthSegments );
  21549. heightSegments = Math.floor( heightSegments );
  21550. depthSegments = Math.floor( depthSegments );
  21551. // buffers
  21552. const indices = [];
  21553. const vertices = [];
  21554. const normals = [];
  21555. const uvs = [];
  21556. // helper variables
  21557. let numberOfVertices = 0;
  21558. let groupStart = 0;
  21559. // build each side of the box geometry
  21560. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  21561. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  21562. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  21563. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  21564. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  21565. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  21566. // build geometry
  21567. this.setIndex( indices );
  21568. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21569. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21570. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21571. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  21572. const segmentWidth = width / gridX;
  21573. const segmentHeight = height / gridY;
  21574. const widthHalf = width / 2;
  21575. const heightHalf = height / 2;
  21576. const depthHalf = depth / 2;
  21577. const gridX1 = gridX + 1;
  21578. const gridY1 = gridY + 1;
  21579. let vertexCounter = 0;
  21580. let groupCount = 0;
  21581. const vector = new Vector3();
  21582. // generate vertices, normals and uvs
  21583. for ( let iy = 0; iy < gridY1; iy ++ ) {
  21584. const y = iy * segmentHeight - heightHalf;
  21585. for ( let ix = 0; ix < gridX1; ix ++ ) {
  21586. const x = ix * segmentWidth - widthHalf;
  21587. // set values to correct vector component
  21588. vector[ u ] = x * udir;
  21589. vector[ v ] = y * vdir;
  21590. vector[ w ] = depthHalf;
  21591. // now apply vector to vertex buffer
  21592. vertices.push( vector.x, vector.y, vector.z );
  21593. // set values to correct vector component
  21594. vector[ u ] = 0;
  21595. vector[ v ] = 0;
  21596. vector[ w ] = depth > 0 ? 1 : -1;
  21597. // now apply vector to normal buffer
  21598. normals.push( vector.x, vector.y, vector.z );
  21599. // uvs
  21600. uvs.push( ix / gridX );
  21601. uvs.push( 1 - ( iy / gridY ) );
  21602. // counters
  21603. vertexCounter += 1;
  21604. }
  21605. }
  21606. // indices
  21607. // 1. you need three indices to draw a single face
  21608. // 2. a single segment consists of two faces
  21609. // 3. so we need to generate six (2*3) indices per segment
  21610. for ( let iy = 0; iy < gridY; iy ++ ) {
  21611. for ( let ix = 0; ix < gridX; ix ++ ) {
  21612. const a = numberOfVertices + ix + gridX1 * iy;
  21613. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  21614. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  21615. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  21616. // faces
  21617. indices.push( a, b, d );
  21618. indices.push( b, c, d );
  21619. // increase counter
  21620. groupCount += 6;
  21621. }
  21622. }
  21623. // add a group to the geometry. this will ensure multi material support
  21624. scope.addGroup( groupStart, groupCount, materialIndex );
  21625. // calculate new start value for groups
  21626. groupStart += groupCount;
  21627. // update total number of vertices
  21628. numberOfVertices += vertexCounter;
  21629. }
  21630. }
  21631. copy( source ) {
  21632. super.copy( source );
  21633. this.parameters = Object.assign( {}, source.parameters );
  21634. return this;
  21635. }
  21636. /**
  21637. * Factory method for creating an instance of this class from the given
  21638. * JSON object.
  21639. *
  21640. * @param {Object} data - A JSON object representing the serialized geometry.
  21641. * @return {BoxGeometry} A new instance.
  21642. */
  21643. static fromJSON( data ) {
  21644. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  21645. }
  21646. }
  21647. /**
  21648. * A geometry class for representing a capsule.
  21649. *
  21650. * ```js
  21651. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  21652. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21653. * const capsule = new THREE.Mesh( geometry, material );
  21654. * scene.add( capsule );
  21655. * ```
  21656. *
  21657. * @augments BufferGeometry
  21658. * @demo scenes/geometry-browser.html#CapsuleGeometry
  21659. */
  21660. class CapsuleGeometry extends BufferGeometry {
  21661. /**
  21662. * Constructs a new capsule geometry.
  21663. *
  21664. * @param {number} [radius=1] - Radius of the capsule.
  21665. * @param {number} [height=1] - Height of the middle section.
  21666. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  21667. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  21668. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  21669. */
  21670. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  21671. super();
  21672. this.type = 'CapsuleGeometry';
  21673. /**
  21674. * Holds the constructor parameters that have been
  21675. * used to generate the geometry. Any modification
  21676. * after instantiation does not change the geometry.
  21677. *
  21678. * @type {Object}
  21679. */
  21680. this.parameters = {
  21681. radius: radius,
  21682. height: height,
  21683. capSegments: capSegments,
  21684. radialSegments: radialSegments,
  21685. heightSegments: heightSegments,
  21686. };
  21687. height = Math.max( 0, height );
  21688. capSegments = Math.max( 1, Math.floor( capSegments ) );
  21689. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  21690. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  21691. // buffers
  21692. const indices = [];
  21693. const vertices = [];
  21694. const normals = [];
  21695. const uvs = [];
  21696. // helper variables
  21697. const halfHeight = height / 2;
  21698. const capArcLength = ( Math.PI / 2 ) * radius;
  21699. const cylinderPartLength = height;
  21700. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  21701. const numVerticalSegments = capSegments * 2 + heightSegments;
  21702. const verticesPerRow = radialSegments + 1;
  21703. const normal = new Vector3();
  21704. const vertex = new Vector3();
  21705. // generate vertices, normals, and uvs
  21706. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  21707. let currentArcLength = 0;
  21708. let profileY = 0;
  21709. let profileRadius = 0;
  21710. let normalYComponent = 0;
  21711. if ( iy <= capSegments ) {
  21712. // bottom cap
  21713. const segmentProgress = iy / capSegments;
  21714. const angle = ( segmentProgress * Math.PI ) / 2;
  21715. profileY = - halfHeight - radius * Math.cos( angle );
  21716. profileRadius = radius * Math.sin( angle );
  21717. normalYComponent = - radius * Math.cos( angle );
  21718. currentArcLength = segmentProgress * capArcLength;
  21719. } else if ( iy <= capSegments + heightSegments ) {
  21720. // middle section
  21721. const segmentProgress = ( iy - capSegments ) / heightSegments;
  21722. profileY = - halfHeight + segmentProgress * height;
  21723. profileRadius = radius;
  21724. normalYComponent = 0;
  21725. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  21726. } else {
  21727. // top cap
  21728. const segmentProgress =
  21729. ( iy - capSegments - heightSegments ) / capSegments;
  21730. const angle = ( segmentProgress * Math.PI ) / 2;
  21731. profileY = halfHeight + radius * Math.sin( angle );
  21732. profileRadius = radius * Math.cos( angle );
  21733. normalYComponent = radius * Math.sin( angle );
  21734. currentArcLength =
  21735. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  21736. }
  21737. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  21738. // special case for the poles
  21739. let uOffset = 0;
  21740. if ( iy === 0 ) {
  21741. uOffset = 0.5 / radialSegments;
  21742. } else if ( iy === numVerticalSegments ) {
  21743. uOffset = -0.5 / radialSegments;
  21744. }
  21745. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  21746. const u = ix / radialSegments;
  21747. const theta = u * Math.PI * 2;
  21748. const sinTheta = Math.sin( theta );
  21749. const cosTheta = Math.cos( theta );
  21750. // vertex
  21751. vertex.x = - profileRadius * cosTheta;
  21752. vertex.y = profileY;
  21753. vertex.z = profileRadius * sinTheta;
  21754. vertices.push( vertex.x, vertex.y, vertex.z );
  21755. // normal
  21756. normal.set(
  21757. - profileRadius * cosTheta,
  21758. normalYComponent,
  21759. profileRadius * sinTheta
  21760. );
  21761. normal.normalize();
  21762. normals.push( normal.x, normal.y, normal.z );
  21763. // uv
  21764. uvs.push( u + uOffset, v );
  21765. }
  21766. if ( iy > 0 ) {
  21767. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  21768. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  21769. const i1 = prevIndexRow + ix;
  21770. const i2 = prevIndexRow + ix + 1;
  21771. const i3 = iy * verticesPerRow + ix;
  21772. const i4 = iy * verticesPerRow + ix + 1;
  21773. indices.push( i1, i2, i3 );
  21774. indices.push( i2, i4, i3 );
  21775. }
  21776. }
  21777. }
  21778. // build geometry
  21779. this.setIndex( indices );
  21780. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21781. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21782. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21783. }
  21784. copy( source ) {
  21785. super.copy( source );
  21786. this.parameters = Object.assign( {}, source.parameters );
  21787. return this;
  21788. }
  21789. /**
  21790. * Factory method for creating an instance of this class from the given
  21791. * JSON object.
  21792. *
  21793. * @param {Object} data - A JSON object representing the serialized geometry.
  21794. * @return {CapsuleGeometry} A new instance.
  21795. */
  21796. static fromJSON( data ) {
  21797. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  21798. }
  21799. }
  21800. /**
  21801. * A simple shape of Euclidean geometry. It is constructed from a
  21802. * number of triangular segments that are oriented around a central point and
  21803. * extend as far out as a given radius. It is built counter-clockwise from a
  21804. * start angle and a given central angle. It can also be used to create
  21805. * regular polygons, where the number of segments determines the number of
  21806. * sides.
  21807. *
  21808. * ```js
  21809. * const geometry = new THREE.CircleGeometry( 5, 32 );
  21810. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21811. * const circle = new THREE.Mesh( geometry, material );
  21812. * scene.add( circle )
  21813. * ```
  21814. *
  21815. * @augments BufferGeometry
  21816. * @demo scenes/geometry-browser.html#CircleGeometry
  21817. */
  21818. class CircleGeometry extends BufferGeometry {
  21819. /**
  21820. * Constructs a new circle geometry.
  21821. *
  21822. * @param {number} [radius=1] - Radius of the circle.
  21823. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  21824. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  21825. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  21826. * of the circular sector in radians. The default value results in a complete circle.
  21827. */
  21828. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21829. super();
  21830. this.type = 'CircleGeometry';
  21831. /**
  21832. * Holds the constructor parameters that have been
  21833. * used to generate the geometry. Any modification
  21834. * after instantiation does not change the geometry.
  21835. *
  21836. * @type {Object}
  21837. */
  21838. this.parameters = {
  21839. radius: radius,
  21840. segments: segments,
  21841. thetaStart: thetaStart,
  21842. thetaLength: thetaLength
  21843. };
  21844. segments = Math.max( 3, segments );
  21845. // buffers
  21846. const indices = [];
  21847. const vertices = [];
  21848. const normals = [];
  21849. const uvs = [];
  21850. // helper variables
  21851. const vertex = new Vector3();
  21852. const uv = new Vector2();
  21853. // center point
  21854. vertices.push( 0, 0, 0 );
  21855. normals.push( 0, 0, 1 );
  21856. uvs.push( 0.5, 0.5 );
  21857. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21858. const segment = thetaStart + s / segments * thetaLength;
  21859. // vertex
  21860. vertex.x = radius * Math.cos( segment );
  21861. vertex.y = radius * Math.sin( segment );
  21862. vertices.push( vertex.x, vertex.y, vertex.z );
  21863. // normal
  21864. normals.push( 0, 0, 1 );
  21865. // uvs
  21866. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21867. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21868. uvs.push( uv.x, uv.y );
  21869. }
  21870. // indices
  21871. for ( let i = 1; i <= segments; i ++ ) {
  21872. indices.push( i, i + 1, 0 );
  21873. }
  21874. // build geometry
  21875. this.setIndex( indices );
  21876. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21877. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21878. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21879. }
  21880. copy( source ) {
  21881. super.copy( source );
  21882. this.parameters = Object.assign( {}, source.parameters );
  21883. return this;
  21884. }
  21885. /**
  21886. * Factory method for creating an instance of this class from the given
  21887. * JSON object.
  21888. *
  21889. * @param {Object} data - A JSON object representing the serialized geometry.
  21890. * @return {CircleGeometry} A new instance.
  21891. */
  21892. static fromJSON( data ) {
  21893. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  21894. }
  21895. }
  21896. /**
  21897. * A geometry class for representing a cylinder.
  21898. *
  21899. * ```js
  21900. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  21901. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21902. * const cylinder = new THREE.Mesh( geometry, material );
  21903. * scene.add( cylinder );
  21904. * ```
  21905. *
  21906. * @augments BufferGeometry
  21907. * @demo scenes/geometry-browser.html#CylinderGeometry
  21908. */
  21909. class CylinderGeometry extends BufferGeometry {
  21910. /**
  21911. * Constructs a new cylinder geometry.
  21912. *
  21913. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  21914. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  21915. * @param {number} [height=1] - Height of the cylinder.
  21916. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  21917. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  21918. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  21919. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  21920. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  21921. * The default value results in a complete cylinder.
  21922. */
  21923. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21924. super();
  21925. this.type = 'CylinderGeometry';
  21926. /**
  21927. * Holds the constructor parameters that have been
  21928. * used to generate the geometry. Any modification
  21929. * after instantiation does not change the geometry.
  21930. *
  21931. * @type {Object}
  21932. */
  21933. this.parameters = {
  21934. radiusTop: radiusTop,
  21935. radiusBottom: radiusBottom,
  21936. height: height,
  21937. radialSegments: radialSegments,
  21938. heightSegments: heightSegments,
  21939. openEnded: openEnded,
  21940. thetaStart: thetaStart,
  21941. thetaLength: thetaLength
  21942. };
  21943. const scope = this;
  21944. radialSegments = Math.floor( radialSegments );
  21945. heightSegments = Math.floor( heightSegments );
  21946. // buffers
  21947. const indices = [];
  21948. const vertices = [];
  21949. const normals = [];
  21950. const uvs = [];
  21951. // helper variables
  21952. let index = 0;
  21953. const indexArray = [];
  21954. const halfHeight = height / 2;
  21955. let groupStart = 0;
  21956. // generate geometry
  21957. generateTorso();
  21958. if ( openEnded === false ) {
  21959. if ( radiusTop > 0 ) generateCap( true );
  21960. if ( radiusBottom > 0 ) generateCap( false );
  21961. }
  21962. // build geometry
  21963. this.setIndex( indices );
  21964. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21965. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21966. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21967. function generateTorso() {
  21968. const normal = new Vector3();
  21969. const vertex = new Vector3();
  21970. let groupCount = 0;
  21971. // this will be used to calculate the normal
  21972. const slope = ( radiusBottom - radiusTop ) / height;
  21973. // generate vertices, normals and uvs
  21974. for ( let y = 0; y <= heightSegments; y ++ ) {
  21975. const indexRow = [];
  21976. const v = y / heightSegments;
  21977. // calculate the radius of the current row
  21978. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21979. for ( let x = 0; x <= radialSegments; x ++ ) {
  21980. const u = x / radialSegments;
  21981. const theta = u * thetaLength + thetaStart;
  21982. const sinTheta = Math.sin( theta );
  21983. const cosTheta = Math.cos( theta );
  21984. // vertex
  21985. vertex.x = radius * sinTheta;
  21986. vertex.y = - v * height + halfHeight;
  21987. vertex.z = radius * cosTheta;
  21988. vertices.push( vertex.x, vertex.y, vertex.z );
  21989. // normal
  21990. normal.set( sinTheta, slope, cosTheta ).normalize();
  21991. normals.push( normal.x, normal.y, normal.z );
  21992. // uv
  21993. uvs.push( u, 1 - v );
  21994. // save index of vertex in respective row
  21995. indexRow.push( index ++ );
  21996. }
  21997. // now save vertices of the row in our index array
  21998. indexArray.push( indexRow );
  21999. }
  22000. // generate indices
  22001. for ( let x = 0; x < radialSegments; x ++ ) {
  22002. for ( let y = 0; y < heightSegments; y ++ ) {
  22003. // we use the index array to access the correct indices
  22004. const a = indexArray[ y ][ x ];
  22005. const b = indexArray[ y + 1 ][ x ];
  22006. const c = indexArray[ y + 1 ][ x + 1 ];
  22007. const d = indexArray[ y ][ x + 1 ];
  22008. // faces
  22009. if ( radiusTop > 0 || y !== 0 ) {
  22010. indices.push( a, b, d );
  22011. groupCount += 3;
  22012. }
  22013. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22014. indices.push( b, c, d );
  22015. groupCount += 3;
  22016. }
  22017. }
  22018. }
  22019. // add a group to the geometry. this will ensure multi material support
  22020. scope.addGroup( groupStart, groupCount, 0 );
  22021. // calculate new start value for groups
  22022. groupStart += groupCount;
  22023. }
  22024. function generateCap( top ) {
  22025. // save the index of the first center vertex
  22026. const centerIndexStart = index;
  22027. const uv = new Vector2();
  22028. const vertex = new Vector3();
  22029. let groupCount = 0;
  22030. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22031. const sign = ( top === true ) ? 1 : -1;
  22032. // first we generate the center vertex data of the cap.
  22033. // because the geometry needs one set of uvs per face,
  22034. // we must generate a center vertex per face/segment
  22035. for ( let x = 1; x <= radialSegments; x ++ ) {
  22036. // vertex
  22037. vertices.push( 0, halfHeight * sign, 0 );
  22038. // normal
  22039. normals.push( 0, sign, 0 );
  22040. // uv
  22041. uvs.push( 0.5, 0.5 );
  22042. // increase index
  22043. index ++;
  22044. }
  22045. // save the index of the last center vertex
  22046. const centerIndexEnd = index;
  22047. // now we generate the surrounding vertices, normals and uvs
  22048. for ( let x = 0; x <= radialSegments; x ++ ) {
  22049. const u = x / radialSegments;
  22050. const theta = u * thetaLength + thetaStart;
  22051. const cosTheta = Math.cos( theta );
  22052. const sinTheta = Math.sin( theta );
  22053. // vertex
  22054. vertex.x = radius * sinTheta;
  22055. vertex.y = halfHeight * sign;
  22056. vertex.z = radius * cosTheta;
  22057. vertices.push( vertex.x, vertex.y, vertex.z );
  22058. // normal
  22059. normals.push( 0, sign, 0 );
  22060. // uv
  22061. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22062. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22063. uvs.push( uv.x, uv.y );
  22064. // increase index
  22065. index ++;
  22066. }
  22067. // generate indices
  22068. for ( let x = 0; x < radialSegments; x ++ ) {
  22069. const c = centerIndexStart + x;
  22070. const i = centerIndexEnd + x;
  22071. if ( top === true ) {
  22072. // face top
  22073. indices.push( i, i + 1, c );
  22074. } else {
  22075. // face bottom
  22076. indices.push( i + 1, i, c );
  22077. }
  22078. groupCount += 3;
  22079. }
  22080. // add a group to the geometry. this will ensure multi material support
  22081. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22082. // calculate new start value for groups
  22083. groupStart += groupCount;
  22084. }
  22085. }
  22086. copy( source ) {
  22087. super.copy( source );
  22088. this.parameters = Object.assign( {}, source.parameters );
  22089. return this;
  22090. }
  22091. /**
  22092. * Factory method for creating an instance of this class from the given
  22093. * JSON object.
  22094. *
  22095. * @param {Object} data - A JSON object representing the serialized geometry.
  22096. * @return {CylinderGeometry} A new instance.
  22097. */
  22098. static fromJSON( data ) {
  22099. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22100. }
  22101. }
  22102. /**
  22103. * A geometry class for representing a cone.
  22104. *
  22105. * ```js
  22106. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22107. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22108. * const cone = new THREE.Mesh(geometry, material );
  22109. * scene.add( cone );
  22110. * ```
  22111. *
  22112. * @augments CylinderGeometry
  22113. * @demo scenes/geometry-browser.html#ConeGeometry
  22114. */
  22115. class ConeGeometry extends CylinderGeometry {
  22116. /**
  22117. * Constructs a new cone geometry.
  22118. *
  22119. * @param {number} [radius=1] - Radius of the cone base.
  22120. * @param {number} [height=1] - Height of the cone.
  22121. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22122. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22123. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22124. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22125. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22126. * The default value results in a complete cone.
  22127. */
  22128. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22129. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22130. this.type = 'ConeGeometry';
  22131. /**
  22132. * Holds the constructor parameters that have been
  22133. * used to generate the geometry. Any modification
  22134. * after instantiation does not change the geometry.
  22135. *
  22136. * @type {Object}
  22137. */
  22138. this.parameters = {
  22139. radius: radius,
  22140. height: height,
  22141. radialSegments: radialSegments,
  22142. heightSegments: heightSegments,
  22143. openEnded: openEnded,
  22144. thetaStart: thetaStart,
  22145. thetaLength: thetaLength
  22146. };
  22147. }
  22148. /**
  22149. * Factory method for creating an instance of this class from the given
  22150. * JSON object.
  22151. *
  22152. * @param {Object} data - A JSON object representing the serialized geometry.
  22153. * @return {ConeGeometry} A new instance.
  22154. */
  22155. static fromJSON( data ) {
  22156. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22157. }
  22158. }
  22159. /**
  22160. * A polyhedron is a solid in three dimensions with flat faces. This class
  22161. * will take an array of vertices, project them onto a sphere, and then
  22162. * divide them up to the desired level of detail.
  22163. *
  22164. * @augments BufferGeometry
  22165. */
  22166. class PolyhedronGeometry extends BufferGeometry {
  22167. /**
  22168. * Constructs a new polyhedron geometry.
  22169. *
  22170. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22171. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22172. * @param {number} [radius=1] - The radius of the shape.
  22173. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22174. */
  22175. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22176. super();
  22177. this.type = 'PolyhedronGeometry';
  22178. /**
  22179. * Holds the constructor parameters that have been
  22180. * used to generate the geometry. Any modification
  22181. * after instantiation does not change the geometry.
  22182. *
  22183. * @type {Object}
  22184. */
  22185. this.parameters = {
  22186. vertices: vertices,
  22187. indices: indices,
  22188. radius: radius,
  22189. detail: detail
  22190. };
  22191. // default buffer data
  22192. const vertexBuffer = [];
  22193. const uvBuffer = [];
  22194. // the subdivision creates the vertex buffer data
  22195. subdivide( detail );
  22196. // all vertices should lie on a conceptual sphere with a given radius
  22197. applyRadius( radius );
  22198. // finally, create the uv data
  22199. generateUVs();
  22200. // build non-indexed geometry
  22201. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22202. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22203. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22204. if ( detail === 0 ) {
  22205. this.computeVertexNormals(); // flat normals
  22206. } else {
  22207. this.normalizeNormals(); // smooth normals
  22208. }
  22209. // helper functions
  22210. function subdivide( detail ) {
  22211. const a = new Vector3();
  22212. const b = new Vector3();
  22213. const c = new Vector3();
  22214. // iterate over all faces and apply a subdivision with the given detail value
  22215. for ( let i = 0; i < indices.length; i += 3 ) {
  22216. // get the vertices of the face
  22217. getVertexByIndex( indices[ i + 0 ], a );
  22218. getVertexByIndex( indices[ i + 1 ], b );
  22219. getVertexByIndex( indices[ i + 2 ], c );
  22220. // perform subdivision
  22221. subdivideFace( a, b, c, detail );
  22222. }
  22223. }
  22224. function subdivideFace( a, b, c, detail ) {
  22225. const cols = detail + 1;
  22226. // we use this multidimensional array as a data structure for creating the subdivision
  22227. const v = [];
  22228. // construct all of the vertices for this subdivision
  22229. for ( let i = 0; i <= cols; i ++ ) {
  22230. v[ i ] = [];
  22231. const aj = a.clone().lerp( c, i / cols );
  22232. const bj = b.clone().lerp( c, i / cols );
  22233. const rows = cols - i;
  22234. for ( let j = 0; j <= rows; j ++ ) {
  22235. if ( j === 0 && i === cols ) {
  22236. v[ i ][ j ] = aj;
  22237. } else {
  22238. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22239. }
  22240. }
  22241. }
  22242. // construct all of the faces
  22243. for ( let i = 0; i < cols; i ++ ) {
  22244. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22245. const k = Math.floor( j / 2 );
  22246. if ( j % 2 === 0 ) {
  22247. pushVertex( v[ i ][ k + 1 ] );
  22248. pushVertex( v[ i + 1 ][ k ] );
  22249. pushVertex( v[ i ][ k ] );
  22250. } else {
  22251. pushVertex( v[ i ][ k + 1 ] );
  22252. pushVertex( v[ i + 1 ][ k + 1 ] );
  22253. pushVertex( v[ i + 1 ][ k ] );
  22254. }
  22255. }
  22256. }
  22257. }
  22258. function applyRadius( radius ) {
  22259. const vertex = new Vector3();
  22260. // iterate over the entire buffer and apply the radius to each vertex
  22261. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22262. vertex.x = vertexBuffer[ i + 0 ];
  22263. vertex.y = vertexBuffer[ i + 1 ];
  22264. vertex.z = vertexBuffer[ i + 2 ];
  22265. vertex.normalize().multiplyScalar( radius );
  22266. vertexBuffer[ i + 0 ] = vertex.x;
  22267. vertexBuffer[ i + 1 ] = vertex.y;
  22268. vertexBuffer[ i + 2 ] = vertex.z;
  22269. }
  22270. }
  22271. function generateUVs() {
  22272. const vertex = new Vector3();
  22273. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22274. vertex.x = vertexBuffer[ i + 0 ];
  22275. vertex.y = vertexBuffer[ i + 1 ];
  22276. vertex.z = vertexBuffer[ i + 2 ];
  22277. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22278. const v = inclination( vertex ) / Math.PI + 0.5;
  22279. uvBuffer.push( u, 1 - v );
  22280. }
  22281. correctUVs();
  22282. correctSeam();
  22283. }
  22284. function correctSeam() {
  22285. // handle case when face straddles the seam, see #3269
  22286. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22287. // uv data of a single face
  22288. const x0 = uvBuffer[ i + 0 ];
  22289. const x1 = uvBuffer[ i + 2 ];
  22290. const x2 = uvBuffer[ i + 4 ];
  22291. const max = Math.max( x0, x1, x2 );
  22292. const min = Math.min( x0, x1, x2 );
  22293. // 0.9 is somewhat arbitrary
  22294. if ( max > 0.9 && min < 0.1 ) {
  22295. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22296. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22297. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22298. }
  22299. }
  22300. }
  22301. function pushVertex( vertex ) {
  22302. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22303. }
  22304. function getVertexByIndex( index, vertex ) {
  22305. const stride = index * 3;
  22306. vertex.x = vertices[ stride + 0 ];
  22307. vertex.y = vertices[ stride + 1 ];
  22308. vertex.z = vertices[ stride + 2 ];
  22309. }
  22310. function correctUVs() {
  22311. const a = new Vector3();
  22312. const b = new Vector3();
  22313. const c = new Vector3();
  22314. const centroid = new Vector3();
  22315. const uvA = new Vector2();
  22316. const uvB = new Vector2();
  22317. const uvC = new Vector2();
  22318. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22319. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22320. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22321. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22322. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22323. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22324. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22325. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22326. const azi = azimuth( centroid );
  22327. correctUV( uvA, j + 0, a, azi );
  22328. correctUV( uvB, j + 2, b, azi );
  22329. correctUV( uvC, j + 4, c, azi );
  22330. }
  22331. }
  22332. function correctUV( uv, stride, vector, azimuth ) {
  22333. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22334. uvBuffer[ stride ] = uv.x - 1;
  22335. }
  22336. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22337. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22338. }
  22339. }
  22340. // Angle around the Y axis, counter-clockwise when looking from above.
  22341. function azimuth( vector ) {
  22342. return Math.atan2( vector.z, - vector.x );
  22343. }
  22344. // Angle above the XZ plane.
  22345. function inclination( vector ) {
  22346. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22347. }
  22348. }
  22349. copy( source ) {
  22350. super.copy( source );
  22351. this.parameters = Object.assign( {}, source.parameters );
  22352. return this;
  22353. }
  22354. /**
  22355. * Factory method for creating an instance of this class from the given
  22356. * JSON object.
  22357. *
  22358. * @param {Object} data - A JSON object representing the serialized geometry.
  22359. * @return {PolyhedronGeometry} A new instance.
  22360. */
  22361. static fromJSON( data ) {
  22362. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  22363. }
  22364. }
  22365. /**
  22366. * A geometry class for representing a dodecahedron.
  22367. *
  22368. * ```js
  22369. * const geometry = new THREE.DodecahedronGeometry();
  22370. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22371. * const dodecahedron = new THREE.Mesh( geometry, material );
  22372. * scene.add( dodecahedron );
  22373. * ```
  22374. *
  22375. * @augments PolyhedronGeometry
  22376. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  22377. */
  22378. class DodecahedronGeometry extends PolyhedronGeometry {
  22379. /**
  22380. * Constructs a new dodecahedron geometry.
  22381. *
  22382. * @param {number} [radius=1] - Radius of the dodecahedron.
  22383. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22384. */
  22385. constructor( radius = 1, detail = 0 ) {
  22386. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22387. const r = 1 / t;
  22388. const vertices = [
  22389. // (±1, ±1, ±1)
  22390. -1, -1, -1, -1, -1, 1,
  22391. -1, 1, -1, -1, 1, 1,
  22392. 1, -1, -1, 1, -1, 1,
  22393. 1, 1, -1, 1, 1, 1,
  22394. // (0, ±1/φ, ±φ)
  22395. 0, - r, - t, 0, - r, t,
  22396. 0, r, - t, 0, r, t,
  22397. // (±1/φ, ±φ, 0)
  22398. - r, - t, 0, - r, t, 0,
  22399. r, - t, 0, r, t, 0,
  22400. // (±φ, 0, ±1/φ)
  22401. - t, 0, - r, t, 0, - r,
  22402. - t, 0, r, t, 0, r
  22403. ];
  22404. const indices = [
  22405. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22406. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22407. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22408. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22409. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22410. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22411. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22412. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22413. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22414. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22415. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22416. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22417. ];
  22418. super( vertices, indices, radius, detail );
  22419. this.type = 'DodecahedronGeometry';
  22420. /**
  22421. * Holds the constructor parameters that have been
  22422. * used to generate the geometry. Any modification
  22423. * after instantiation does not change the geometry.
  22424. *
  22425. * @type {Object}
  22426. */
  22427. this.parameters = {
  22428. radius: radius,
  22429. detail: detail
  22430. };
  22431. }
  22432. /**
  22433. * Factory method for creating an instance of this class from the given
  22434. * JSON object.
  22435. *
  22436. * @param {Object} data - A JSON object representing the serialized geometry.
  22437. * @return {DodecahedronGeometry} A new instance.
  22438. */
  22439. static fromJSON( data ) {
  22440. return new DodecahedronGeometry( data.radius, data.detail );
  22441. }
  22442. }
  22443. const _v0 = /*@__PURE__*/ new Vector3();
  22444. const _v1$1 = /*@__PURE__*/ new Vector3();
  22445. const _normal = /*@__PURE__*/ new Vector3();
  22446. const _triangle = /*@__PURE__*/ new Triangle();
  22447. /**
  22448. * Can be used as a helper object to view the edges of a geometry.
  22449. *
  22450. * ```js
  22451. * const geometry = new THREE.BoxGeometry();
  22452. * const edges = new THREE.EdgesGeometry( geometry );
  22453. * const line = new THREE.LineSegments( edges );
  22454. * scene.add( line );
  22455. * ```
  22456. *
  22457. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22458. *
  22459. * @augments BufferGeometry
  22460. */
  22461. class EdgesGeometry extends BufferGeometry {
  22462. /**
  22463. * Constructs a new edges geometry.
  22464. *
  22465. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22466. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22467. * between the face normals of the adjoining faces exceeds this value.
  22468. */
  22469. constructor( geometry = null, thresholdAngle = 1 ) {
  22470. super();
  22471. this.type = 'EdgesGeometry';
  22472. /**
  22473. * Holds the constructor parameters that have been
  22474. * used to generate the geometry. Any modification
  22475. * after instantiation does not change the geometry.
  22476. *
  22477. * @type {Object}
  22478. */
  22479. this.parameters = {
  22480. geometry: geometry,
  22481. thresholdAngle: thresholdAngle
  22482. };
  22483. if ( geometry !== null ) {
  22484. const precisionPoints = 4;
  22485. const precision = Math.pow( 10, precisionPoints );
  22486. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22487. const indexAttr = geometry.getIndex();
  22488. const positionAttr = geometry.getAttribute( 'position' );
  22489. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22490. const indexArr = [ 0, 0, 0 ];
  22491. const vertKeys = [ 'a', 'b', 'c' ];
  22492. const hashes = new Array( 3 );
  22493. const edgeData = {};
  22494. const vertices = [];
  22495. for ( let i = 0; i < indexCount; i += 3 ) {
  22496. if ( indexAttr ) {
  22497. indexArr[ 0 ] = indexAttr.getX( i );
  22498. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22499. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22500. } else {
  22501. indexArr[ 0 ] = i;
  22502. indexArr[ 1 ] = i + 1;
  22503. indexArr[ 2 ] = i + 2;
  22504. }
  22505. const { a, b, c } = _triangle;
  22506. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22507. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22508. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22509. _triangle.getNormal( _normal );
  22510. // create hashes for the edge from the vertices
  22511. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22512. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22513. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22514. // skip degenerate triangles
  22515. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22516. continue;
  22517. }
  22518. // iterate over every edge
  22519. for ( let j = 0; j < 3; j ++ ) {
  22520. // get the first and next vertex making up the edge
  22521. const jNext = ( j + 1 ) % 3;
  22522. const vecHash0 = hashes[ j ];
  22523. const vecHash1 = hashes[ jNext ];
  22524. const v0 = _triangle[ vertKeys[ j ] ];
  22525. const v1 = _triangle[ vertKeys[ jNext ] ];
  22526. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22527. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22528. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22529. // if we found a sibling edge add it into the vertex array if
  22530. // it meets the angle threshold and delete the edge from the map.
  22531. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22532. vertices.push( v0.x, v0.y, v0.z );
  22533. vertices.push( v1.x, v1.y, v1.z );
  22534. }
  22535. edgeData[ reverseHash ] = null;
  22536. } else if ( ! ( hash in edgeData ) ) {
  22537. // if we've already got an edge here then skip adding a new one
  22538. edgeData[ hash ] = {
  22539. index0: indexArr[ j ],
  22540. index1: indexArr[ jNext ],
  22541. normal: _normal.clone(),
  22542. };
  22543. }
  22544. }
  22545. }
  22546. // iterate over all remaining, unmatched edges and add them to the vertex array
  22547. for ( const key in edgeData ) {
  22548. if ( edgeData[ key ] ) {
  22549. const { index0, index1 } = edgeData[ key ];
  22550. _v0.fromBufferAttribute( positionAttr, index0 );
  22551. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22552. vertices.push( _v0.x, _v0.y, _v0.z );
  22553. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22554. }
  22555. }
  22556. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22557. }
  22558. }
  22559. copy( source ) {
  22560. super.copy( source );
  22561. this.parameters = Object.assign( {}, source.parameters );
  22562. return this;
  22563. }
  22564. }
  22565. /**
  22566. * An abstract base class for creating an analytic curve object that contains methods
  22567. * for interpolation.
  22568. *
  22569. * @abstract
  22570. */
  22571. class Curve {
  22572. /**
  22573. * Constructs a new curve.
  22574. */
  22575. constructor() {
  22576. /**
  22577. * The type property is used for detecting the object type
  22578. * in context of serialization/deserialization.
  22579. *
  22580. * @type {string}
  22581. * @readonly
  22582. */
  22583. this.type = 'Curve';
  22584. /**
  22585. * This value determines the amount of divisions when calculating the
  22586. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  22587. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  22588. * recommended to increase the value of this property if the curve is very large.
  22589. *
  22590. * @type {number}
  22591. * @default 200
  22592. */
  22593. this.arcLengthDivisions = 200;
  22594. /**
  22595. * Must be set to `true` if the curve parameters have changed.
  22596. *
  22597. * @type {boolean}
  22598. * @default false
  22599. */
  22600. this.needsUpdate = false;
  22601. /**
  22602. * An internal cache that holds precomputed curve length values.
  22603. *
  22604. * @private
  22605. * @type {?Array<number>}
  22606. * @default null
  22607. */
  22608. this.cacheArcLengths = null;
  22609. }
  22610. /**
  22611. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22612. * for the given interpolation factor.
  22613. *
  22614. * @abstract
  22615. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22616. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22617. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22618. */
  22619. getPoint( /* t, optionalTarget */ ) {
  22620. warn( 'Curve: .getPoint() not implemented.' );
  22621. }
  22622. /**
  22623. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22624. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  22625. * of the curve which equidistant samples.
  22626. *
  22627. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22628. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22629. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22630. */
  22631. getPointAt( u, optionalTarget ) {
  22632. const t = this.getUtoTmapping( u );
  22633. return this.getPoint( t, optionalTarget );
  22634. }
  22635. /**
  22636. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  22637. * the curve shape.
  22638. *
  22639. * @param {number} [divisions=5] - The number of divisions.
  22640. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22641. */
  22642. getPoints( divisions = 5 ) {
  22643. const points = [];
  22644. for ( let d = 0; d <= divisions; d ++ ) {
  22645. points.push( this.getPoint( d / divisions ) );
  22646. }
  22647. return points;
  22648. }
  22649. // Get sequence of points using getPointAt( u )
  22650. /**
  22651. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  22652. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  22653. * curve.
  22654. *
  22655. * @param {number} [divisions=5] - The number of divisions.
  22656. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22657. */
  22658. getSpacedPoints( divisions = 5 ) {
  22659. const points = [];
  22660. for ( let d = 0; d <= divisions; d ++ ) {
  22661. points.push( this.getPointAt( d / divisions ) );
  22662. }
  22663. return points;
  22664. }
  22665. /**
  22666. * Returns the total arc length of the curve.
  22667. *
  22668. * @return {number} The length of the curve.
  22669. */
  22670. getLength() {
  22671. const lengths = this.getLengths();
  22672. return lengths[ lengths.length - 1 ];
  22673. }
  22674. /**
  22675. * Returns an array of cumulative segment lengths of the curve.
  22676. *
  22677. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  22678. * @return {Array<number>} An array holding the cumulative segment lengths.
  22679. */
  22680. getLengths( divisions = this.arcLengthDivisions ) {
  22681. if ( this.cacheArcLengths &&
  22682. ( this.cacheArcLengths.length === divisions + 1 ) &&
  22683. ! this.needsUpdate ) {
  22684. return this.cacheArcLengths;
  22685. }
  22686. this.needsUpdate = false;
  22687. const cache = [];
  22688. let current, last = this.getPoint( 0 );
  22689. let sum = 0;
  22690. cache.push( 0 );
  22691. for ( let p = 1; p <= divisions; p ++ ) {
  22692. current = this.getPoint( p / divisions );
  22693. sum += current.distanceTo( last );
  22694. cache.push( sum );
  22695. last = current;
  22696. }
  22697. this.cacheArcLengths = cache;
  22698. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22699. }
  22700. /**
  22701. * Update the cumulative segment distance cache. The method must be called
  22702. * every time curve parameters are changed. If an updated curve is part of a
  22703. * composed curve like {@link CurvePath}, this method must be called on the
  22704. * composed curve, too.
  22705. */
  22706. updateArcLengths() {
  22707. this.needsUpdate = true;
  22708. this.getLengths();
  22709. }
  22710. /**
  22711. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  22712. * interpolation factor in the same range that can be ued to sample equidistant points
  22713. * from a curve.
  22714. *
  22715. * @param {number} u - The interpolation factor.
  22716. * @param {?number} distance - An optional distance on the curve.
  22717. * @return {number} The updated interpolation factor.
  22718. */
  22719. getUtoTmapping( u, distance = null ) {
  22720. const arcLengths = this.getLengths();
  22721. let i = 0;
  22722. const il = arcLengths.length;
  22723. let targetArcLength; // The targeted u distance value to get
  22724. if ( distance ) {
  22725. targetArcLength = distance;
  22726. } else {
  22727. targetArcLength = u * arcLengths[ il - 1 ];
  22728. }
  22729. // binary search for the index with largest value smaller than target u distance
  22730. let low = 0, high = il - 1, comparison;
  22731. while ( low <= high ) {
  22732. 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
  22733. comparison = arcLengths[ i ] - targetArcLength;
  22734. if ( comparison < 0 ) {
  22735. low = i + 1;
  22736. } else if ( comparison > 0 ) {
  22737. high = i - 1;
  22738. } else {
  22739. high = i;
  22740. break;
  22741. // DONE
  22742. }
  22743. }
  22744. i = high;
  22745. if ( arcLengths[ i ] === targetArcLength ) {
  22746. return i / ( il - 1 );
  22747. }
  22748. // we could get finer grain at lengths, or use simple interpolation between two points
  22749. const lengthBefore = arcLengths[ i ];
  22750. const lengthAfter = arcLengths[ i + 1 ];
  22751. const segmentLength = lengthAfter - lengthBefore;
  22752. // determine where we are between the 'before' and 'after' points
  22753. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  22754. // add that fractional amount to t
  22755. const t = ( i + segmentFraction ) / ( il - 1 );
  22756. return t;
  22757. }
  22758. /**
  22759. * Returns a unit vector tangent for the given interpolation factor.
  22760. * If the derived curve does not implement its tangent derivation,
  22761. * two points a small delta apart will be used to find its gradient
  22762. * which seems to give a reasonable approximation.
  22763. *
  22764. * @param {number} t - The interpolation factor.
  22765. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22766. * @return {(Vector2|Vector3)} The tangent vector.
  22767. */
  22768. getTangent( t, optionalTarget ) {
  22769. const delta = 0.0001;
  22770. let t1 = t - delta;
  22771. let t2 = t + delta;
  22772. // Capping in case of danger
  22773. if ( t1 < 0 ) t1 = 0;
  22774. if ( t2 > 1 ) t2 = 1;
  22775. const pt1 = this.getPoint( t1 );
  22776. const pt2 = this.getPoint( t2 );
  22777. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  22778. tangent.copy( pt2 ).sub( pt1 ).normalize();
  22779. return tangent;
  22780. }
  22781. /**
  22782. * Same as {@link Curve#getTangent} but with equidistant samples.
  22783. *
  22784. * @param {number} u - The interpolation factor.
  22785. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22786. * @return {(Vector2|Vector3)} The tangent vector.
  22787. * @see {@link Curve#getPointAt}
  22788. */
  22789. getTangentAt( u, optionalTarget ) {
  22790. const t = this.getUtoTmapping( u );
  22791. return this.getTangent( t, optionalTarget );
  22792. }
  22793. /**
  22794. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  22795. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  22796. *
  22797. * @param {number} segments - The number of segments.
  22798. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  22799. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  22800. */
  22801. computeFrenetFrames( segments, closed = false ) {
  22802. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22803. const normal = new Vector3();
  22804. const tangents = [];
  22805. const normals = [];
  22806. const binormals = [];
  22807. const vec = new Vector3();
  22808. const mat = new Matrix4();
  22809. // compute the tangent vectors for each segment on the curve
  22810. for ( let i = 0; i <= segments; i ++ ) {
  22811. const u = i / segments;
  22812. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  22813. }
  22814. // select an initial normal vector perpendicular to the first tangent vector,
  22815. // and in the direction of the minimum tangent xyz component
  22816. normals[ 0 ] = new Vector3();
  22817. binormals[ 0 ] = new Vector3();
  22818. let min = Number.MAX_VALUE;
  22819. const tx = Math.abs( tangents[ 0 ].x );
  22820. const ty = Math.abs( tangents[ 0 ].y );
  22821. const tz = Math.abs( tangents[ 0 ].z );
  22822. if ( tx <= min ) {
  22823. min = tx;
  22824. normal.set( 1, 0, 0 );
  22825. }
  22826. if ( ty <= min ) {
  22827. min = ty;
  22828. normal.set( 0, 1, 0 );
  22829. }
  22830. if ( tz <= min ) {
  22831. normal.set( 0, 0, 1 );
  22832. }
  22833. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22834. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22835. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22836. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22837. for ( let i = 1; i <= segments; i ++ ) {
  22838. normals[ i ] = normals[ i - 1 ].clone();
  22839. binormals[ i ] = binormals[ i - 1 ].clone();
  22840. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22841. if ( vec.length() > Number.EPSILON ) {
  22842. vec.normalize();
  22843. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  22844. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22845. }
  22846. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22847. }
  22848. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22849. if ( closed === true ) {
  22850. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  22851. theta /= segments;
  22852. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  22853. theta = - theta;
  22854. }
  22855. for ( let i = 1; i <= segments; i ++ ) {
  22856. // twist a little...
  22857. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22858. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22859. }
  22860. }
  22861. return {
  22862. tangents: tangents,
  22863. normals: normals,
  22864. binormals: binormals
  22865. };
  22866. }
  22867. /**
  22868. * Returns a new curve with copied values from this instance.
  22869. *
  22870. * @return {Curve} A clone of this instance.
  22871. */
  22872. clone() {
  22873. return new this.constructor().copy( this );
  22874. }
  22875. /**
  22876. * Copies the values of the given curve to this instance.
  22877. *
  22878. * @param {Curve} source - The curve to copy.
  22879. * @return {Curve} A reference to this curve.
  22880. */
  22881. copy( source ) {
  22882. this.arcLengthDivisions = source.arcLengthDivisions;
  22883. return this;
  22884. }
  22885. /**
  22886. * Serializes the curve into JSON.
  22887. *
  22888. * @return {Object} A JSON object representing the serialized curve.
  22889. * @see {@link ObjectLoader#parse}
  22890. */
  22891. toJSON() {
  22892. const data = {
  22893. metadata: {
  22894. version: 4.7,
  22895. type: 'Curve',
  22896. generator: 'Curve.toJSON'
  22897. }
  22898. };
  22899. data.arcLengthDivisions = this.arcLengthDivisions;
  22900. data.type = this.type;
  22901. return data;
  22902. }
  22903. /**
  22904. * Deserializes the curve from the given JSON.
  22905. *
  22906. * @param {Object} json - The JSON holding the serialized curve.
  22907. * @return {Curve} A reference to this curve.
  22908. */
  22909. fromJSON( json ) {
  22910. this.arcLengthDivisions = json.arcLengthDivisions;
  22911. return this;
  22912. }
  22913. }
  22914. /**
  22915. * A curve representing an ellipse.
  22916. *
  22917. * ```js
  22918. * const curve = new THREE.EllipseCurve(
  22919. * 0, 0,
  22920. * 10, 10,
  22921. * 0, 2 * Math.PI,
  22922. * false,
  22923. * 0
  22924. * );
  22925. *
  22926. * const points = curve.getPoints( 50 );
  22927. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22928. *
  22929. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22930. *
  22931. * // Create the final object to add to the scene
  22932. * const ellipse = new THREE.Line( geometry, material );
  22933. * ```
  22934. *
  22935. * @augments Curve
  22936. */
  22937. class EllipseCurve extends Curve {
  22938. /**
  22939. * Constructs a new ellipse curve.
  22940. *
  22941. * @param {number} [aX=0] - The X center of the ellipse.
  22942. * @param {number} [aY=0] - The Y center of the ellipse.
  22943. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  22944. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  22945. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22946. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22947. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22948. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22949. */
  22950. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  22951. super();
  22952. /**
  22953. * This flag can be used for type testing.
  22954. *
  22955. * @type {boolean}
  22956. * @readonly
  22957. * @default true
  22958. */
  22959. this.isEllipseCurve = true;
  22960. this.type = 'EllipseCurve';
  22961. /**
  22962. * The X center of the ellipse.
  22963. *
  22964. * @type {number}
  22965. * @default 0
  22966. */
  22967. this.aX = aX;
  22968. /**
  22969. * The Y center of the ellipse.
  22970. *
  22971. * @type {number}
  22972. * @default 0
  22973. */
  22974. this.aY = aY;
  22975. /**
  22976. * The radius of the ellipse in the x direction.
  22977. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  22978. *
  22979. * @type {number}
  22980. * @default 1
  22981. */
  22982. this.xRadius = xRadius;
  22983. /**
  22984. * The radius of the ellipse in the y direction.
  22985. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  22986. *
  22987. * @type {number}
  22988. * @default 1
  22989. */
  22990. this.yRadius = yRadius;
  22991. /**
  22992. * The start angle of the curve in radians starting from the positive X axis.
  22993. *
  22994. * @type {number}
  22995. * @default 0
  22996. */
  22997. this.aStartAngle = aStartAngle;
  22998. /**
  22999. * The end angle of the curve in radians starting from the positive X axis.
  23000. *
  23001. * @type {number}
  23002. * @default Math.PI*2
  23003. */
  23004. this.aEndAngle = aEndAngle;
  23005. /**
  23006. * Whether the ellipse is drawn clockwise or not.
  23007. *
  23008. * @type {boolean}
  23009. * @default false
  23010. */
  23011. this.aClockwise = aClockwise;
  23012. /**
  23013. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23014. *
  23015. * @type {number}
  23016. * @default 0
  23017. */
  23018. this.aRotation = aRotation;
  23019. }
  23020. /**
  23021. * Returns a point on the curve.
  23022. *
  23023. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23024. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23025. * @return {Vector2} The position on the curve.
  23026. */
  23027. getPoint( t, optionalTarget = new Vector2() ) {
  23028. const point = optionalTarget;
  23029. const twoPi = Math.PI * 2;
  23030. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23031. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23032. // ensures that deltaAngle is 0 .. 2 PI
  23033. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23034. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23035. if ( deltaAngle < Number.EPSILON ) {
  23036. if ( samePoints ) {
  23037. deltaAngle = 0;
  23038. } else {
  23039. deltaAngle = twoPi;
  23040. }
  23041. }
  23042. if ( this.aClockwise === true && ! samePoints ) {
  23043. if ( deltaAngle === twoPi ) {
  23044. deltaAngle = - twoPi;
  23045. } else {
  23046. deltaAngle = deltaAngle - twoPi;
  23047. }
  23048. }
  23049. const angle = this.aStartAngle + t * deltaAngle;
  23050. let x = this.aX + this.xRadius * Math.cos( angle );
  23051. let y = this.aY + this.yRadius * Math.sin( angle );
  23052. if ( this.aRotation !== 0 ) {
  23053. const cos = Math.cos( this.aRotation );
  23054. const sin = Math.sin( this.aRotation );
  23055. const tx = x - this.aX;
  23056. const ty = y - this.aY;
  23057. // Rotate the point about the center of the ellipse.
  23058. x = tx * cos - ty * sin + this.aX;
  23059. y = tx * sin + ty * cos + this.aY;
  23060. }
  23061. return point.set( x, y );
  23062. }
  23063. copy( source ) {
  23064. super.copy( source );
  23065. this.aX = source.aX;
  23066. this.aY = source.aY;
  23067. this.xRadius = source.xRadius;
  23068. this.yRadius = source.yRadius;
  23069. this.aStartAngle = source.aStartAngle;
  23070. this.aEndAngle = source.aEndAngle;
  23071. this.aClockwise = source.aClockwise;
  23072. this.aRotation = source.aRotation;
  23073. return this;
  23074. }
  23075. toJSON() {
  23076. const data = super.toJSON();
  23077. data.aX = this.aX;
  23078. data.aY = this.aY;
  23079. data.xRadius = this.xRadius;
  23080. data.yRadius = this.yRadius;
  23081. data.aStartAngle = this.aStartAngle;
  23082. data.aEndAngle = this.aEndAngle;
  23083. data.aClockwise = this.aClockwise;
  23084. data.aRotation = this.aRotation;
  23085. return data;
  23086. }
  23087. fromJSON( json ) {
  23088. super.fromJSON( json );
  23089. this.aX = json.aX;
  23090. this.aY = json.aY;
  23091. this.xRadius = json.xRadius;
  23092. this.yRadius = json.yRadius;
  23093. this.aStartAngle = json.aStartAngle;
  23094. this.aEndAngle = json.aEndAngle;
  23095. this.aClockwise = json.aClockwise;
  23096. this.aRotation = json.aRotation;
  23097. return this;
  23098. }
  23099. }
  23100. /**
  23101. * A curve representing an arc.
  23102. *
  23103. * @augments EllipseCurve
  23104. */
  23105. class ArcCurve extends EllipseCurve {
  23106. /**
  23107. * Constructs a new arc curve.
  23108. *
  23109. * @param {number} [aX=0] - The X center of the ellipse.
  23110. * @param {number} [aY=0] - The Y center of the ellipse.
  23111. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23112. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23113. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23114. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23115. */
  23116. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23117. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23118. /**
  23119. * This flag can be used for type testing.
  23120. *
  23121. * @type {boolean}
  23122. * @readonly
  23123. * @default true
  23124. */
  23125. this.isArcCurve = true;
  23126. this.type = 'ArcCurve';
  23127. }
  23128. }
  23129. function CubicPoly() {
  23130. /**
  23131. * Centripetal CatmullRom Curve - which is useful for avoiding
  23132. * cusps and self-intersections in non-uniform catmull rom curves.
  23133. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23134. *
  23135. * curve.type accepts centripetal(default), chordal and catmullrom
  23136. * curve.tension is used for catmullrom which defaults to 0.5
  23137. */
  23138. /*
  23139. Based on an optimized c++ solution in
  23140. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23141. - http://ideone.com/NoEbVM
  23142. This CubicPoly class could be used for reusing some variables and calculations,
  23143. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23144. which can be placed in CurveUtils.
  23145. */
  23146. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23147. /*
  23148. * Compute coefficients for a cubic polynomial
  23149. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23150. * such that
  23151. * p(0) = x0, p(1) = x1
  23152. * and
  23153. * p'(0) = t0, p'(1) = t1.
  23154. */
  23155. function init( x0, x1, t0, t1 ) {
  23156. c0 = x0;
  23157. c1 = t0;
  23158. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23159. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23160. }
  23161. return {
  23162. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23163. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23164. },
  23165. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23166. // compute tangents when parameterized in [t1,t2]
  23167. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23168. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23169. // rescale tangents for parametrization in [0,1]
  23170. t1 *= dt1;
  23171. t2 *= dt1;
  23172. init( x1, x2, t1, t2 );
  23173. },
  23174. calc: function ( t ) {
  23175. const t2 = t * t;
  23176. const t3 = t2 * t;
  23177. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23178. }
  23179. };
  23180. }
  23181. //
  23182. const tmp = /*@__PURE__*/ new Vector3();
  23183. const tmp2 = /*@__PURE__*/ new Vector3();
  23184. const px = /*@__PURE__*/ new CubicPoly();
  23185. const py = /*@__PURE__*/ new CubicPoly();
  23186. const pz = /*@__PURE__*/ new CubicPoly();
  23187. /**
  23188. * A curve representing a Catmull-Rom spline.
  23189. *
  23190. * ```js
  23191. * //Create a closed wavey loop
  23192. * const curve = new THREE.CatmullRomCurve3( [
  23193. * new THREE.Vector3( -10, 0, 10 ),
  23194. * new THREE.Vector3( -5, 5, 5 ),
  23195. * new THREE.Vector3( 0, 0, 0 ),
  23196. * new THREE.Vector3( 5, -5, 5 ),
  23197. * new THREE.Vector3( 10, 0, 10 )
  23198. * ] );
  23199. *
  23200. * const points = curve.getPoints( 50 );
  23201. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23202. *
  23203. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23204. *
  23205. * // Create the final object to add to the scene
  23206. * const curveObject = new THREE.Line( geometry, material );
  23207. * ```
  23208. *
  23209. * @augments Curve
  23210. */
  23211. class CatmullRomCurve3 extends Curve {
  23212. /**
  23213. * Constructs a new Catmull-Rom curve.
  23214. *
  23215. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23216. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23217. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23218. * @param {number} [tension=0.5] - Tension of the curve.
  23219. */
  23220. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23221. super();
  23222. /**
  23223. * This flag can be used for type testing.
  23224. *
  23225. * @type {boolean}
  23226. * @readonly
  23227. * @default true
  23228. */
  23229. this.isCatmullRomCurve3 = true;
  23230. this.type = 'CatmullRomCurve3';
  23231. /**
  23232. * An array of 3D points defining the curve.
  23233. *
  23234. * @type {Array<Vector3>}
  23235. */
  23236. this.points = points;
  23237. /**
  23238. * Whether the curve is closed or not.
  23239. *
  23240. * @type {boolean}
  23241. * @default false
  23242. */
  23243. this.closed = closed;
  23244. /**
  23245. * The curve type.
  23246. *
  23247. * @type {('centripetal'|'chordal'|'catmullrom')}
  23248. * @default 'centripetal'
  23249. */
  23250. this.curveType = curveType;
  23251. /**
  23252. * Tension of the curve.
  23253. *
  23254. * @type {number}
  23255. * @default 0.5
  23256. */
  23257. this.tension = tension;
  23258. }
  23259. /**
  23260. * Returns a point on the curve.
  23261. *
  23262. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23263. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23264. * @return {Vector3} The position on the curve.
  23265. */
  23266. getPoint( t, optionalTarget = new Vector3() ) {
  23267. const point = optionalTarget;
  23268. const points = this.points;
  23269. const l = points.length;
  23270. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23271. let intPoint = Math.floor( p );
  23272. let weight = p - intPoint;
  23273. if ( this.closed ) {
  23274. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23275. } else if ( weight === 0 && intPoint === l - 1 ) {
  23276. intPoint = l - 2;
  23277. weight = 1;
  23278. }
  23279. let p0, p3; // 4 points (p1 & p2 defined below)
  23280. if ( this.closed || intPoint > 0 ) {
  23281. p0 = points[ ( intPoint - 1 ) % l ];
  23282. } else {
  23283. // extrapolate first point
  23284. tmp2.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23285. p0 = tmp2;
  23286. }
  23287. const p1 = points[ intPoint % l ];
  23288. const p2 = points[ ( intPoint + 1 ) % l ];
  23289. if ( this.closed || intPoint + 2 < l ) {
  23290. p3 = points[ ( intPoint + 2 ) % l ];
  23291. } else {
  23292. // extrapolate last point
  23293. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23294. p3 = tmp;
  23295. }
  23296. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23297. // init Centripetal / Chordal Catmull-Rom
  23298. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23299. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23300. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23301. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23302. // safety check for repeated points
  23303. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23304. if ( dt0 < 1e-4 ) dt0 = dt1;
  23305. if ( dt2 < 1e-4 ) dt2 = dt1;
  23306. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23307. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23308. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23309. } else if ( this.curveType === 'catmullrom' ) {
  23310. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23311. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23312. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23313. }
  23314. point.set(
  23315. px.calc( weight ),
  23316. py.calc( weight ),
  23317. pz.calc( weight )
  23318. );
  23319. return point;
  23320. }
  23321. copy( source ) {
  23322. super.copy( source );
  23323. this.points = [];
  23324. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23325. const point = source.points[ i ];
  23326. this.points.push( point.clone() );
  23327. }
  23328. this.closed = source.closed;
  23329. this.curveType = source.curveType;
  23330. this.tension = source.tension;
  23331. return this;
  23332. }
  23333. toJSON() {
  23334. const data = super.toJSON();
  23335. data.points = [];
  23336. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23337. const point = this.points[ i ];
  23338. data.points.push( point.toArray() );
  23339. }
  23340. data.closed = this.closed;
  23341. data.curveType = this.curveType;
  23342. data.tension = this.tension;
  23343. return data;
  23344. }
  23345. fromJSON( json ) {
  23346. super.fromJSON( json );
  23347. this.points = [];
  23348. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23349. const point = json.points[ i ];
  23350. this.points.push( new Vector3().fromArray( point ) );
  23351. }
  23352. this.closed = json.closed;
  23353. this.curveType = json.curveType;
  23354. this.tension = json.tension;
  23355. return this;
  23356. }
  23357. }
  23358. /**
  23359. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  23360. *
  23361. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23362. *
  23363. * @module Interpolations
  23364. */
  23365. /**
  23366. * Computes a point on a Catmull-Rom spline.
  23367. *
  23368. * @param {number} t - The interpolation factor.
  23369. * @param {number} p0 - The first control point.
  23370. * @param {number} p1 - The second control point.
  23371. * @param {number} p2 - The third control point.
  23372. * @param {number} p3 - The fourth control point.
  23373. * @return {number} The calculated point on a Catmull-Rom spline.
  23374. */
  23375. function CatmullRom( t, p0, p1, p2, p3 ) {
  23376. const v0 = ( p2 - p0 ) * 0.5;
  23377. const v1 = ( p3 - p1 ) * 0.5;
  23378. const t2 = t * t;
  23379. const t3 = t * t2;
  23380. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23381. }
  23382. //
  23383. function QuadraticBezierP0( t, p ) {
  23384. const k = 1 - t;
  23385. return k * k * p;
  23386. }
  23387. function QuadraticBezierP1( t, p ) {
  23388. return 2 * ( 1 - t ) * t * p;
  23389. }
  23390. function QuadraticBezierP2( t, p ) {
  23391. return t * t * p;
  23392. }
  23393. /**
  23394. * Computes a point on a Quadratic Bezier curve.
  23395. *
  23396. * @param {number} t - The interpolation factor.
  23397. * @param {number} p0 - The first control point.
  23398. * @param {number} p1 - The second control point.
  23399. * @param {number} p2 - The third control point.
  23400. * @return {number} The calculated point on a Quadratic Bezier curve.
  23401. */
  23402. function QuadraticBezier( t, p0, p1, p2 ) {
  23403. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23404. QuadraticBezierP2( t, p2 );
  23405. }
  23406. //
  23407. function CubicBezierP0( t, p ) {
  23408. const k = 1 - t;
  23409. return k * k * k * p;
  23410. }
  23411. function CubicBezierP1( t, p ) {
  23412. const k = 1 - t;
  23413. return 3 * k * k * t * p;
  23414. }
  23415. function CubicBezierP2( t, p ) {
  23416. return 3 * ( 1 - t ) * t * t * p;
  23417. }
  23418. function CubicBezierP3( t, p ) {
  23419. return t * t * t * p;
  23420. }
  23421. /**
  23422. * Computes a point on a Cubic Bezier curve.
  23423. *
  23424. * @param {number} t - The interpolation factor.
  23425. * @param {number} p0 - The first control point.
  23426. * @param {number} p1 - The second control point.
  23427. * @param {number} p2 - The third control point.
  23428. * @param {number} p3 - The fourth control point.
  23429. * @return {number} The calculated point on a Cubic Bezier curve.
  23430. */
  23431. function CubicBezier( t, p0, p1, p2, p3 ) {
  23432. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23433. CubicBezierP3( t, p3 );
  23434. }
  23435. /**
  23436. * A curve representing a 2D Cubic Bezier curve.
  23437. *
  23438. * ```js
  23439. * const curve = new THREE.CubicBezierCurve(
  23440. * new THREE.Vector2( - 0, 0 ),
  23441. * new THREE.Vector2( - 5, 15 ),
  23442. * new THREE.Vector2( 20, 15 ),
  23443. * new THREE.Vector2( 10, 0 )
  23444. * );
  23445. *
  23446. * const points = curve.getPoints( 50 );
  23447. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23448. *
  23449. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23450. *
  23451. * // Create the final object to add to the scene
  23452. * const curveObject = new THREE.Line( geometry, material );
  23453. * ```
  23454. *
  23455. * @augments Curve
  23456. */
  23457. class CubicBezierCurve extends Curve {
  23458. /**
  23459. * Constructs a new Cubic Bezier curve.
  23460. *
  23461. * @param {Vector2} [v0] - The start point.
  23462. * @param {Vector2} [v1] - The first control point.
  23463. * @param {Vector2} [v2] - The second control point.
  23464. * @param {Vector2} [v3] - The end point.
  23465. */
  23466. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23467. super();
  23468. /**
  23469. * This flag can be used for type testing.
  23470. *
  23471. * @type {boolean}
  23472. * @readonly
  23473. * @default true
  23474. */
  23475. this.isCubicBezierCurve = true;
  23476. this.type = 'CubicBezierCurve';
  23477. /**
  23478. * The start point.
  23479. *
  23480. * @type {Vector2}
  23481. */
  23482. this.v0 = v0;
  23483. /**
  23484. * The first control point.
  23485. *
  23486. * @type {Vector2}
  23487. */
  23488. this.v1 = v1;
  23489. /**
  23490. * The second control point.
  23491. *
  23492. * @type {Vector2}
  23493. */
  23494. this.v2 = v2;
  23495. /**
  23496. * The end point.
  23497. *
  23498. * @type {Vector2}
  23499. */
  23500. this.v3 = v3;
  23501. }
  23502. /**
  23503. * Returns a point on the curve.
  23504. *
  23505. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23506. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23507. * @return {Vector2} The position on the curve.
  23508. */
  23509. getPoint( t, optionalTarget = new Vector2() ) {
  23510. const point = optionalTarget;
  23511. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23512. point.set(
  23513. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23514. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23515. );
  23516. return point;
  23517. }
  23518. copy( source ) {
  23519. super.copy( source );
  23520. this.v0.copy( source.v0 );
  23521. this.v1.copy( source.v1 );
  23522. this.v2.copy( source.v2 );
  23523. this.v3.copy( source.v3 );
  23524. return this;
  23525. }
  23526. toJSON() {
  23527. const data = super.toJSON();
  23528. data.v0 = this.v0.toArray();
  23529. data.v1 = this.v1.toArray();
  23530. data.v2 = this.v2.toArray();
  23531. data.v3 = this.v3.toArray();
  23532. return data;
  23533. }
  23534. fromJSON( json ) {
  23535. super.fromJSON( json );
  23536. this.v0.fromArray( json.v0 );
  23537. this.v1.fromArray( json.v1 );
  23538. this.v2.fromArray( json.v2 );
  23539. this.v3.fromArray( json.v3 );
  23540. return this;
  23541. }
  23542. }
  23543. /**
  23544. * A curve representing a 3D Cubic Bezier curve.
  23545. *
  23546. * @augments Curve
  23547. */
  23548. class CubicBezierCurve3 extends Curve {
  23549. /**
  23550. * Constructs a new Cubic Bezier curve.
  23551. *
  23552. * @param {Vector3} [v0] - The start point.
  23553. * @param {Vector3} [v1] - The first control point.
  23554. * @param {Vector3} [v2] - The second control point.
  23555. * @param {Vector3} [v3] - The end point.
  23556. */
  23557. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23558. super();
  23559. /**
  23560. * This flag can be used for type testing.
  23561. *
  23562. * @type {boolean}
  23563. * @readonly
  23564. * @default true
  23565. */
  23566. this.isCubicBezierCurve3 = true;
  23567. this.type = 'CubicBezierCurve3';
  23568. /**
  23569. * The start point.
  23570. *
  23571. * @type {Vector3}
  23572. */
  23573. this.v0 = v0;
  23574. /**
  23575. * The first control point.
  23576. *
  23577. * @type {Vector3}
  23578. */
  23579. this.v1 = v1;
  23580. /**
  23581. * The second control point.
  23582. *
  23583. * @type {Vector3}
  23584. */
  23585. this.v2 = v2;
  23586. /**
  23587. * The end point.
  23588. *
  23589. * @type {Vector3}
  23590. */
  23591. this.v3 = v3;
  23592. }
  23593. /**
  23594. * Returns a point on the curve.
  23595. *
  23596. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23597. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23598. * @return {Vector3} The position on the curve.
  23599. */
  23600. getPoint( t, optionalTarget = new Vector3() ) {
  23601. const point = optionalTarget;
  23602. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23603. point.set(
  23604. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23605. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23606. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23607. );
  23608. return point;
  23609. }
  23610. copy( source ) {
  23611. super.copy( source );
  23612. this.v0.copy( source.v0 );
  23613. this.v1.copy( source.v1 );
  23614. this.v2.copy( source.v2 );
  23615. this.v3.copy( source.v3 );
  23616. return this;
  23617. }
  23618. toJSON() {
  23619. const data = super.toJSON();
  23620. data.v0 = this.v0.toArray();
  23621. data.v1 = this.v1.toArray();
  23622. data.v2 = this.v2.toArray();
  23623. data.v3 = this.v3.toArray();
  23624. return data;
  23625. }
  23626. fromJSON( json ) {
  23627. super.fromJSON( json );
  23628. this.v0.fromArray( json.v0 );
  23629. this.v1.fromArray( json.v1 );
  23630. this.v2.fromArray( json.v2 );
  23631. this.v3.fromArray( json.v3 );
  23632. return this;
  23633. }
  23634. }
  23635. /**
  23636. * A curve representing a 2D line segment.
  23637. *
  23638. * @augments Curve
  23639. */
  23640. class LineCurve extends Curve {
  23641. /**
  23642. * Constructs a new line curve.
  23643. *
  23644. * @param {Vector2} [v1] - The start point.
  23645. * @param {Vector2} [v2] - The end point.
  23646. */
  23647. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  23648. super();
  23649. /**
  23650. * This flag can be used for type testing.
  23651. *
  23652. * @type {boolean}
  23653. * @readonly
  23654. * @default true
  23655. */
  23656. this.isLineCurve = true;
  23657. this.type = 'LineCurve';
  23658. /**
  23659. * The start point.
  23660. *
  23661. * @type {Vector2}
  23662. */
  23663. this.v1 = v1;
  23664. /**
  23665. * The end point.
  23666. *
  23667. * @type {Vector2}
  23668. */
  23669. this.v2 = v2;
  23670. }
  23671. /**
  23672. * Returns a point on the line.
  23673. *
  23674. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23675. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23676. * @return {Vector2} The position on the line.
  23677. */
  23678. getPoint( t, optionalTarget = new Vector2() ) {
  23679. const point = optionalTarget;
  23680. if ( t === 1 ) {
  23681. point.copy( this.v2 );
  23682. } else {
  23683. point.copy( this.v2 ).sub( this.v1 );
  23684. point.multiplyScalar( t ).add( this.v1 );
  23685. }
  23686. return point;
  23687. }
  23688. // Line curve is linear, so we can overwrite default getPointAt
  23689. getPointAt( u, optionalTarget ) {
  23690. return this.getPoint( u, optionalTarget );
  23691. }
  23692. getTangent( t, optionalTarget = new Vector2() ) {
  23693. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23694. }
  23695. getTangentAt( u, optionalTarget ) {
  23696. return this.getTangent( u, optionalTarget );
  23697. }
  23698. copy( source ) {
  23699. super.copy( source );
  23700. this.v1.copy( source.v1 );
  23701. this.v2.copy( source.v2 );
  23702. return this;
  23703. }
  23704. toJSON() {
  23705. const data = super.toJSON();
  23706. data.v1 = this.v1.toArray();
  23707. data.v2 = this.v2.toArray();
  23708. return data;
  23709. }
  23710. fromJSON( json ) {
  23711. super.fromJSON( json );
  23712. this.v1.fromArray( json.v1 );
  23713. this.v2.fromArray( json.v2 );
  23714. return this;
  23715. }
  23716. }
  23717. /**
  23718. * A curve representing a 3D line segment.
  23719. *
  23720. * @augments Curve
  23721. */
  23722. class LineCurve3 extends Curve {
  23723. /**
  23724. * Constructs a new line curve.
  23725. *
  23726. * @param {Vector3} [v1] - The start point.
  23727. * @param {Vector3} [v2] - The end point.
  23728. */
  23729. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  23730. super();
  23731. /**
  23732. * This flag can be used for type testing.
  23733. *
  23734. * @type {boolean}
  23735. * @readonly
  23736. * @default true
  23737. */
  23738. this.isLineCurve3 = true;
  23739. this.type = 'LineCurve3';
  23740. /**
  23741. * The start point.
  23742. *
  23743. * @type {Vector3}
  23744. */
  23745. this.v1 = v1;
  23746. /**
  23747. * The end point.
  23748. *
  23749. * @type {Vector2}
  23750. */
  23751. this.v2 = v2;
  23752. }
  23753. /**
  23754. * Returns a point on the line.
  23755. *
  23756. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23757. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23758. * @return {Vector3} The position on the line.
  23759. */
  23760. getPoint( t, optionalTarget = new Vector3() ) {
  23761. const point = optionalTarget;
  23762. if ( t === 1 ) {
  23763. point.copy( this.v2 );
  23764. } else {
  23765. point.copy( this.v2 ).sub( this.v1 );
  23766. point.multiplyScalar( t ).add( this.v1 );
  23767. }
  23768. return point;
  23769. }
  23770. // Line curve is linear, so we can overwrite default getPointAt
  23771. getPointAt( u, optionalTarget ) {
  23772. return this.getPoint( u, optionalTarget );
  23773. }
  23774. getTangent( t, optionalTarget = new Vector3() ) {
  23775. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23776. }
  23777. getTangentAt( u, optionalTarget ) {
  23778. return this.getTangent( u, optionalTarget );
  23779. }
  23780. copy( source ) {
  23781. super.copy( source );
  23782. this.v1.copy( source.v1 );
  23783. this.v2.copy( source.v2 );
  23784. return this;
  23785. }
  23786. toJSON() {
  23787. const data = super.toJSON();
  23788. data.v1 = this.v1.toArray();
  23789. data.v2 = this.v2.toArray();
  23790. return data;
  23791. }
  23792. fromJSON( json ) {
  23793. super.fromJSON( json );
  23794. this.v1.fromArray( json.v1 );
  23795. this.v2.fromArray( json.v2 );
  23796. return this;
  23797. }
  23798. }
  23799. /**
  23800. * A curve representing a 2D Quadratic Bezier curve.
  23801. *
  23802. * ```js
  23803. * const curve = new THREE.QuadraticBezierCurve(
  23804. * new THREE.Vector2( - 10, 0 ),
  23805. * new THREE.Vector2( 20, 15 ),
  23806. * new THREE.Vector2( 10, 0 )
  23807. * )
  23808. *
  23809. * const points = curve.getPoints( 50 );
  23810. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23811. *
  23812. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23813. *
  23814. * // Create the final object to add to the scene
  23815. * const curveObject = new THREE.Line( geometry, material );
  23816. * ```
  23817. *
  23818. * @augments Curve
  23819. */
  23820. class QuadraticBezierCurve extends Curve {
  23821. /**
  23822. * Constructs a new Quadratic Bezier curve.
  23823. *
  23824. * @param {Vector2} [v0] - The start point.
  23825. * @param {Vector2} [v1] - The control point.
  23826. * @param {Vector2} [v2] - The end point.
  23827. */
  23828. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  23829. super();
  23830. /**
  23831. * This flag can be used for type testing.
  23832. *
  23833. * @type {boolean}
  23834. * @readonly
  23835. * @default true
  23836. */
  23837. this.isQuadraticBezierCurve = true;
  23838. this.type = 'QuadraticBezierCurve';
  23839. /**
  23840. * The start point.
  23841. *
  23842. * @type {Vector2}
  23843. */
  23844. this.v0 = v0;
  23845. /**
  23846. * The control point.
  23847. *
  23848. * @type {Vector2}
  23849. */
  23850. this.v1 = v1;
  23851. /**
  23852. * The end point.
  23853. *
  23854. * @type {Vector2}
  23855. */
  23856. this.v2 = v2;
  23857. }
  23858. /**
  23859. * Returns a point on the curve.
  23860. *
  23861. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23862. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23863. * @return {Vector2} The position on the curve.
  23864. */
  23865. getPoint( t, optionalTarget = new Vector2() ) {
  23866. const point = optionalTarget;
  23867. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23868. point.set(
  23869. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23870. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23871. );
  23872. return point;
  23873. }
  23874. copy( source ) {
  23875. super.copy( source );
  23876. this.v0.copy( source.v0 );
  23877. this.v1.copy( source.v1 );
  23878. this.v2.copy( source.v2 );
  23879. return this;
  23880. }
  23881. toJSON() {
  23882. const data = super.toJSON();
  23883. data.v0 = this.v0.toArray();
  23884. data.v1 = this.v1.toArray();
  23885. data.v2 = this.v2.toArray();
  23886. return data;
  23887. }
  23888. fromJSON( json ) {
  23889. super.fromJSON( json );
  23890. this.v0.fromArray( json.v0 );
  23891. this.v1.fromArray( json.v1 );
  23892. this.v2.fromArray( json.v2 );
  23893. return this;
  23894. }
  23895. }
  23896. /**
  23897. * A curve representing a 3D Quadratic Bezier curve.
  23898. *
  23899. * @augments Curve
  23900. */
  23901. class QuadraticBezierCurve3 extends Curve {
  23902. /**
  23903. * Constructs a new Quadratic Bezier curve.
  23904. *
  23905. * @param {Vector3} [v0] - The start point.
  23906. * @param {Vector3} [v1] - The control point.
  23907. * @param {Vector3} [v2] - The end point.
  23908. */
  23909. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  23910. super();
  23911. /**
  23912. * This flag can be used for type testing.
  23913. *
  23914. * @type {boolean}
  23915. * @readonly
  23916. * @default true
  23917. */
  23918. this.isQuadraticBezierCurve3 = true;
  23919. this.type = 'QuadraticBezierCurve3';
  23920. /**
  23921. * The start point.
  23922. *
  23923. * @type {Vector3}
  23924. */
  23925. this.v0 = v0;
  23926. /**
  23927. * The control point.
  23928. *
  23929. * @type {Vector3}
  23930. */
  23931. this.v1 = v1;
  23932. /**
  23933. * The end point.
  23934. *
  23935. * @type {Vector3}
  23936. */
  23937. this.v2 = v2;
  23938. }
  23939. /**
  23940. * Returns a point on the curve.
  23941. *
  23942. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23943. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23944. * @return {Vector3} The position on the curve.
  23945. */
  23946. getPoint( t, optionalTarget = new Vector3() ) {
  23947. const point = optionalTarget;
  23948. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23949. point.set(
  23950. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23951. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23952. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23953. );
  23954. return point;
  23955. }
  23956. copy( source ) {
  23957. super.copy( source );
  23958. this.v0.copy( source.v0 );
  23959. this.v1.copy( source.v1 );
  23960. this.v2.copy( source.v2 );
  23961. return this;
  23962. }
  23963. toJSON() {
  23964. const data = super.toJSON();
  23965. data.v0 = this.v0.toArray();
  23966. data.v1 = this.v1.toArray();
  23967. data.v2 = this.v2.toArray();
  23968. return data;
  23969. }
  23970. fromJSON( json ) {
  23971. super.fromJSON( json );
  23972. this.v0.fromArray( json.v0 );
  23973. this.v1.fromArray( json.v1 );
  23974. this.v2.fromArray( json.v2 );
  23975. return this;
  23976. }
  23977. }
  23978. /**
  23979. * A curve representing a 2D spline curve.
  23980. *
  23981. * ```js
  23982. * // Create a sine-like wave
  23983. * const curve = new THREE.SplineCurve( [
  23984. * new THREE.Vector2( -10, 0 ),
  23985. * new THREE.Vector2( -5, 5 ),
  23986. * new THREE.Vector2( 0, 0 ),
  23987. * new THREE.Vector2( 5, -5 ),
  23988. * new THREE.Vector2( 10, 0 )
  23989. * ] );
  23990. *
  23991. * const points = curve.getPoints( 50 );
  23992. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23993. *
  23994. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23995. *
  23996. * // Create the final object to add to the scene
  23997. * const splineObject = new THREE.Line( geometry, material );
  23998. * ```
  23999. *
  24000. * @augments Curve
  24001. */
  24002. class SplineCurve extends Curve {
  24003. /**
  24004. * Constructs a new 2D spline curve.
  24005. *
  24006. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24007. */
  24008. constructor( points = [] ) {
  24009. super();
  24010. /**
  24011. * This flag can be used for type testing.
  24012. *
  24013. * @type {boolean}
  24014. * @readonly
  24015. * @default true
  24016. */
  24017. this.isSplineCurve = true;
  24018. this.type = 'SplineCurve';
  24019. /**
  24020. * An array of 2D points defining the curve.
  24021. *
  24022. * @type {Array<Vector2>}
  24023. */
  24024. this.points = points;
  24025. }
  24026. /**
  24027. * Returns a point on the curve.
  24028. *
  24029. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24030. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24031. * @return {Vector2} The position on the curve.
  24032. */
  24033. getPoint( t, optionalTarget = new Vector2() ) {
  24034. const point = optionalTarget;
  24035. const points = this.points;
  24036. const p = ( points.length - 1 ) * t;
  24037. const intPoint = Math.floor( p );
  24038. const weight = p - intPoint;
  24039. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24040. const p1 = points[ intPoint ];
  24041. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24042. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24043. point.set(
  24044. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24045. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24046. );
  24047. return point;
  24048. }
  24049. copy( source ) {
  24050. super.copy( source );
  24051. this.points = [];
  24052. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24053. const point = source.points[ i ];
  24054. this.points.push( point.clone() );
  24055. }
  24056. return this;
  24057. }
  24058. toJSON() {
  24059. const data = super.toJSON();
  24060. data.points = [];
  24061. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24062. const point = this.points[ i ];
  24063. data.points.push( point.toArray() );
  24064. }
  24065. return data;
  24066. }
  24067. fromJSON( json ) {
  24068. super.fromJSON( json );
  24069. this.points = [];
  24070. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24071. const point = json.points[ i ];
  24072. this.points.push( new Vector2().fromArray( point ) );
  24073. }
  24074. return this;
  24075. }
  24076. }
  24077. var Curves = /*#__PURE__*/Object.freeze({
  24078. __proto__: null,
  24079. ArcCurve: ArcCurve,
  24080. CatmullRomCurve3: CatmullRomCurve3,
  24081. CubicBezierCurve: CubicBezierCurve,
  24082. CubicBezierCurve3: CubicBezierCurve3,
  24083. EllipseCurve: EllipseCurve,
  24084. LineCurve: LineCurve,
  24085. LineCurve3: LineCurve3,
  24086. QuadraticBezierCurve: QuadraticBezierCurve,
  24087. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24088. SplineCurve: SplineCurve
  24089. });
  24090. /**
  24091. * A base class extending {@link Curve}. `CurvePath` is simply an
  24092. * array of connected curves, but retains the API of a curve.
  24093. *
  24094. * @augments Curve
  24095. */
  24096. class CurvePath extends Curve {
  24097. /**
  24098. * Constructs a new curve path.
  24099. */
  24100. constructor() {
  24101. super();
  24102. this.type = 'CurvePath';
  24103. /**
  24104. * An array of curves defining the
  24105. * path.
  24106. *
  24107. * @type {Array<Curve>}
  24108. */
  24109. this.curves = [];
  24110. /**
  24111. * Whether the path should automatically be closed
  24112. * by a line curve.
  24113. *
  24114. * @type {boolean}
  24115. * @default false
  24116. */
  24117. this.autoClose = false;
  24118. }
  24119. /**
  24120. * Adds a curve to this curve path.
  24121. *
  24122. * @param {Curve} curve - The curve to add.
  24123. */
  24124. add( curve ) {
  24125. this.curves.push( curve );
  24126. }
  24127. /**
  24128. * Adds a line curve to close the path.
  24129. *
  24130. * @return {CurvePath} A reference to this curve path.
  24131. */
  24132. closePath() {
  24133. // Add a line curve if start and end of lines are not connected
  24134. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24135. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24136. if ( ! startPoint.equals( endPoint ) ) {
  24137. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24138. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24139. }
  24140. return this;
  24141. }
  24142. /**
  24143. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24144. * for the given interpolation factor.
  24145. *
  24146. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24147. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24148. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24149. */
  24150. getPoint( t, optionalTarget ) {
  24151. // To get accurate point with reference to
  24152. // entire path distance at time t,
  24153. // following has to be done:
  24154. // 1. Length of each sub path have to be known
  24155. // 2. Locate and identify type of curve
  24156. // 3. Get t for the curve
  24157. // 4. Return curve.getPointAt(t')
  24158. const d = t * this.getLength();
  24159. const curveLengths = this.getCurveLengths();
  24160. let i = 0;
  24161. // To think about boundaries points.
  24162. while ( i < curveLengths.length ) {
  24163. if ( curveLengths[ i ] >= d ) {
  24164. const diff = curveLengths[ i ] - d;
  24165. const curve = this.curves[ i ];
  24166. const segmentLength = curve.getLength();
  24167. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24168. return curve.getPointAt( u, optionalTarget );
  24169. }
  24170. i ++;
  24171. }
  24172. return null;
  24173. // loop where sum != 0, sum > d , sum+1 <d
  24174. }
  24175. getLength() {
  24176. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24177. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24178. // getPoint() depends on getLength
  24179. const lens = this.getCurveLengths();
  24180. return lens[ lens.length - 1 ];
  24181. }
  24182. updateArcLengths() {
  24183. // cacheLengths must be recalculated.
  24184. this.needsUpdate = true;
  24185. this.cacheLengths = null;
  24186. this.getCurveLengths();
  24187. }
  24188. /**
  24189. * Returns list of cumulative curve lengths of the defined curves.
  24190. *
  24191. * @return {Array<number>} The curve lengths.
  24192. */
  24193. getCurveLengths() {
  24194. // Compute lengths and cache them
  24195. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24196. // We use cache values if curves and cache array are same length
  24197. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24198. return this.cacheLengths;
  24199. }
  24200. // Get length of sub-curve
  24201. // Push sums into cached array
  24202. const lengths = [];
  24203. let sums = 0;
  24204. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24205. sums += this.curves[ i ].getLength();
  24206. lengths.push( sums );
  24207. }
  24208. this.cacheLengths = lengths;
  24209. return lengths;
  24210. }
  24211. getSpacedPoints( divisions = 40 ) {
  24212. const points = [];
  24213. for ( let i = 0; i <= divisions; i ++ ) {
  24214. points.push( this.getPoint( i / divisions ) );
  24215. }
  24216. if ( this.autoClose ) {
  24217. points.push( points[ 0 ] );
  24218. }
  24219. return points;
  24220. }
  24221. getPoints( divisions = 12 ) {
  24222. const points = [];
  24223. let last;
  24224. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24225. const curve = curves[ i ];
  24226. const resolution = curve.isEllipseCurve ? divisions * 2
  24227. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24228. : curve.isSplineCurve ? divisions * curve.points.length
  24229. : divisions;
  24230. const pts = curve.getPoints( resolution );
  24231. for ( let j = 0; j < pts.length; j ++ ) {
  24232. const point = pts[ j ];
  24233. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24234. points.push( point );
  24235. last = point;
  24236. }
  24237. }
  24238. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24239. points.push( points[ 0 ] );
  24240. }
  24241. return points;
  24242. }
  24243. copy( source ) {
  24244. super.copy( source );
  24245. this.curves = [];
  24246. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24247. const curve = source.curves[ i ];
  24248. this.curves.push( curve.clone() );
  24249. }
  24250. this.autoClose = source.autoClose;
  24251. return this;
  24252. }
  24253. toJSON() {
  24254. const data = super.toJSON();
  24255. data.autoClose = this.autoClose;
  24256. data.curves = [];
  24257. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24258. const curve = this.curves[ i ];
  24259. data.curves.push( curve.toJSON() );
  24260. }
  24261. return data;
  24262. }
  24263. fromJSON( json ) {
  24264. super.fromJSON( json );
  24265. this.autoClose = json.autoClose;
  24266. this.curves = [];
  24267. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24268. const curve = json.curves[ i ];
  24269. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24270. }
  24271. return this;
  24272. }
  24273. }
  24274. /**
  24275. * A 2D path representation. The class provides methods for creating paths
  24276. * and contours of 2D shapes similar to the 2D Canvas API.
  24277. *
  24278. * ```js
  24279. * const path = new THREE.Path();
  24280. *
  24281. * path.lineTo( 0, 0.8 );
  24282. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24283. * path.lineTo( 1, 1 );
  24284. *
  24285. * const points = path.getPoints();
  24286. *
  24287. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24288. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24289. *
  24290. * const line = new THREE.Line( geometry, material );
  24291. * scene.add( line );
  24292. * ```
  24293. *
  24294. * @augments CurvePath
  24295. */
  24296. class Path extends CurvePath {
  24297. /**
  24298. * Constructs a new path.
  24299. *
  24300. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24301. */
  24302. constructor( points ) {
  24303. super();
  24304. this.type = 'Path';
  24305. /**
  24306. * The current offset of the path. Any new curve added will start here.
  24307. *
  24308. * @type {Vector2}
  24309. */
  24310. this.currentPoint = new Vector2();
  24311. if ( points ) {
  24312. this.setFromPoints( points );
  24313. }
  24314. }
  24315. /**
  24316. * Creates a path from the given list of points. The points are added
  24317. * to the path as instances of {@link LineCurve}.
  24318. *
  24319. * @param {Array<Vector2>} points - An array of 2D points.
  24320. * @return {Path} A reference to this path.
  24321. */
  24322. setFromPoints( points ) {
  24323. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24324. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24325. this.lineTo( points[ i ].x, points[ i ].y );
  24326. }
  24327. return this;
  24328. }
  24329. /**
  24330. * Moves {@link Path#currentPoint} to the given point.
  24331. *
  24332. * @param {number} x - The x coordinate.
  24333. * @param {number} y - The y coordinate.
  24334. * @return {Path} A reference to this path.
  24335. */
  24336. moveTo( x, y ) {
  24337. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24338. return this;
  24339. }
  24340. /**
  24341. * Adds an instance of {@link LineCurve} to the path by connecting
  24342. * the current point with the given one.
  24343. *
  24344. * @param {number} x - The x coordinate of the end point.
  24345. * @param {number} y - The y coordinate of the end point.
  24346. * @return {Path} A reference to this path.
  24347. */
  24348. lineTo( x, y ) {
  24349. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24350. this.curves.push( curve );
  24351. this.currentPoint.set( x, y );
  24352. return this;
  24353. }
  24354. /**
  24355. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24356. * the current point with the given one.
  24357. *
  24358. * @param {number} aCPx - The x coordinate of the control point.
  24359. * @param {number} aCPy - The y coordinate of the control point.
  24360. * @param {number} aX - The x coordinate of the end point.
  24361. * @param {number} aY - The y coordinate of the end point.
  24362. * @return {Path} A reference to this path.
  24363. */
  24364. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24365. const curve = new QuadraticBezierCurve(
  24366. this.currentPoint.clone(),
  24367. new Vector2( aCPx, aCPy ),
  24368. new Vector2( aX, aY )
  24369. );
  24370. this.curves.push( curve );
  24371. this.currentPoint.set( aX, aY );
  24372. return this;
  24373. }
  24374. /**
  24375. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24376. * the current point with the given one.
  24377. *
  24378. * @param {number} aCP1x - The x coordinate of the first control point.
  24379. * @param {number} aCP1y - The y coordinate of the first control point.
  24380. * @param {number} aCP2x - The x coordinate of the second control point.
  24381. * @param {number} aCP2y - The y coordinate of the second control point.
  24382. * @param {number} aX - The x coordinate of the end point.
  24383. * @param {number} aY - The y coordinate of the end point.
  24384. * @return {Path} A reference to this path.
  24385. */
  24386. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24387. const curve = new CubicBezierCurve(
  24388. this.currentPoint.clone(),
  24389. new Vector2( aCP1x, aCP1y ),
  24390. new Vector2( aCP2x, aCP2y ),
  24391. new Vector2( aX, aY )
  24392. );
  24393. this.curves.push( curve );
  24394. this.currentPoint.set( aX, aY );
  24395. return this;
  24396. }
  24397. /**
  24398. * Adds an instance of {@link SplineCurve} to the path by connecting
  24399. * the current point with the given list of points.
  24400. *
  24401. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24402. * @return {Path} A reference to this path.
  24403. */
  24404. splineThru( pts ) {
  24405. const npts = [ this.currentPoint.clone() ].concat( pts );
  24406. const curve = new SplineCurve( npts );
  24407. this.curves.push( curve );
  24408. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24409. return this;
  24410. }
  24411. /**
  24412. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24413. * to the current point.
  24414. *
  24415. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24416. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24417. * @param {number} [aRadius=1] - The radius of the arc.
  24418. * @param {number} [aStartAngle=0] - The start angle in radians.
  24419. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24420. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24421. * @return {Path} A reference to this path.
  24422. */
  24423. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24424. const x0 = this.currentPoint.x;
  24425. const y0 = this.currentPoint.y;
  24426. this.absarc( aX + x0, aY + y0, aRadius,
  24427. aStartAngle, aEndAngle, aClockwise );
  24428. return this;
  24429. }
  24430. /**
  24431. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24432. *
  24433. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24434. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24435. * @param {number} [aRadius=1] - The radius of the arc.
  24436. * @param {number} [aStartAngle=0] - The start angle in radians.
  24437. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24438. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24439. * @return {Path} A reference to this path.
  24440. */
  24441. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24442. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24443. return this;
  24444. }
  24445. /**
  24446. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24447. * to the current point
  24448. *
  24449. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24450. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24451. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24452. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24453. * @param {number} [aStartAngle=0] - The start angle in radians.
  24454. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24455. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24456. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24457. * @return {Path} A reference to this path.
  24458. */
  24459. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24460. const x0 = this.currentPoint.x;
  24461. const y0 = this.currentPoint.y;
  24462. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24463. return this;
  24464. }
  24465. /**
  24466. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24467. *
  24468. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24469. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24470. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24471. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24472. * @param {number} [aStartAngle=0] - The start angle in radians.
  24473. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24474. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24475. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24476. * @return {Path} A reference to this path.
  24477. */
  24478. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24479. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24480. if ( this.curves.length > 0 ) {
  24481. // if a previous curve is present, attempt to join
  24482. const firstPoint = curve.getPoint( 0 );
  24483. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24484. this.lineTo( firstPoint.x, firstPoint.y );
  24485. }
  24486. }
  24487. this.curves.push( curve );
  24488. const lastPoint = curve.getPoint( 1 );
  24489. this.currentPoint.copy( lastPoint );
  24490. return this;
  24491. }
  24492. copy( source ) {
  24493. super.copy( source );
  24494. this.currentPoint.copy( source.currentPoint );
  24495. return this;
  24496. }
  24497. toJSON() {
  24498. const data = super.toJSON();
  24499. data.currentPoint = this.currentPoint.toArray();
  24500. return data;
  24501. }
  24502. fromJSON( json ) {
  24503. super.fromJSON( json );
  24504. this.currentPoint.fromArray( json.currentPoint );
  24505. return this;
  24506. }
  24507. }
  24508. /**
  24509. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24510. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24511. * points, or to get triangulated faces.
  24512. *
  24513. * ```js
  24514. * const heartShape = new THREE.Shape();
  24515. *
  24516. * heartShape.moveTo( 25, 25 );
  24517. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24518. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24519. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24520. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24521. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24522. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24523. *
  24524. * const extrudeSettings = {
  24525. * depth: 8,
  24526. * bevelEnabled: true,
  24527. * bevelSegments: 2,
  24528. * steps: 2,
  24529. * bevelSize: 1,
  24530. * bevelThickness: 1
  24531. * };
  24532. *
  24533. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24534. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24535. * ```
  24536. *
  24537. * @augments Path
  24538. */
  24539. class Shape extends Path {
  24540. /**
  24541. * Constructs a new shape.
  24542. *
  24543. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24544. */
  24545. constructor( points ) {
  24546. super( points );
  24547. /**
  24548. * The UUID of the shape.
  24549. *
  24550. * @type {string}
  24551. * @readonly
  24552. */
  24553. this.uuid = generateUUID();
  24554. this.type = 'Shape';
  24555. /**
  24556. * Defines the holes in the shape. Hole definitions must use the
  24557. * opposite winding order (CW/CCW) than the outer shape.
  24558. *
  24559. * @type {Array<Path>}
  24560. * @readonly
  24561. */
  24562. this.holes = [];
  24563. }
  24564. /**
  24565. * Returns an array representing each contour of the holes
  24566. * as a list of 2D points.
  24567. *
  24568. * @param {number} divisions - The fineness of the result.
  24569. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24570. */
  24571. getPointsHoles( divisions ) {
  24572. const holesPts = [];
  24573. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24574. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24575. }
  24576. return holesPts;
  24577. }
  24578. // get points of shape and holes (keypoints based on segments parameter)
  24579. /**
  24580. * Returns an object that holds contour data for the shape and its holes as
  24581. * arrays of 2D points.
  24582. *
  24583. * @param {number} divisions - The fineness of the result.
  24584. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24585. */
  24586. extractPoints( divisions ) {
  24587. return {
  24588. shape: this.getPoints( divisions ),
  24589. holes: this.getPointsHoles( divisions )
  24590. };
  24591. }
  24592. copy( source ) {
  24593. super.copy( source );
  24594. this.holes = [];
  24595. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24596. const hole = source.holes[ i ];
  24597. this.holes.push( hole.clone() );
  24598. }
  24599. return this;
  24600. }
  24601. toJSON() {
  24602. const data = super.toJSON();
  24603. data.uuid = this.uuid;
  24604. data.holes = [];
  24605. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24606. const hole = this.holes[ i ];
  24607. data.holes.push( hole.toJSON() );
  24608. }
  24609. return data;
  24610. }
  24611. fromJSON( json ) {
  24612. super.fromJSON( json );
  24613. this.uuid = json.uuid;
  24614. this.holes = [];
  24615. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24616. const hole = json.holes[ i ];
  24617. this.holes.push( new Path().fromJSON( hole ) );
  24618. }
  24619. return this;
  24620. }
  24621. }
  24622. /* eslint-disable */
  24623. // copy of mapbox/earcut version 3.0.2
  24624. // https://github.com/mapbox/earcut/tree/v3.0.2
  24625. function earcut(data, holeIndices, dim = 2) {
  24626. const hasHoles = holeIndices && holeIndices.length;
  24627. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24628. let outerNode = linkedList(data, 0, outerLen, dim, true);
  24629. const triangles = [];
  24630. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24631. let minX, minY, invSize;
  24632. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  24633. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24634. if (data.length > 80 * dim) {
  24635. minX = data[0];
  24636. minY = data[1];
  24637. let maxX = minX;
  24638. let maxY = minY;
  24639. for (let i = dim; i < outerLen; i += dim) {
  24640. const x = data[i];
  24641. const y = data[i + 1];
  24642. if (x < minX) minX = x;
  24643. if (y < minY) minY = y;
  24644. if (x > maxX) maxX = x;
  24645. if (y > maxY) maxY = y;
  24646. }
  24647. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24648. invSize = Math.max(maxX - minX, maxY - minY);
  24649. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24650. }
  24651. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  24652. return triangles;
  24653. }
  24654. // create a circular doubly linked list from polygon points in the specified winding order
  24655. function linkedList(data, start, end, dim, clockwise) {
  24656. let last;
  24657. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  24658. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24659. } else {
  24660. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24661. }
  24662. if (last && equals(last, last.next)) {
  24663. removeNode(last);
  24664. last = last.next;
  24665. }
  24666. return last;
  24667. }
  24668. // eliminate colinear or duplicate points
  24669. function filterPoints(start, end) {
  24670. if (!start) return start;
  24671. if (!end) end = start;
  24672. let p = start,
  24673. again;
  24674. do {
  24675. again = false;
  24676. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24677. removeNode(p);
  24678. p = end = p.prev;
  24679. if (p === p.next) break;
  24680. again = true;
  24681. } else {
  24682. p = p.next;
  24683. }
  24684. } while (again || p !== end);
  24685. return end;
  24686. }
  24687. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24688. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  24689. if (!ear) return;
  24690. // interlink polygon nodes in z-order
  24691. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  24692. let stop = ear;
  24693. // iterate through ears, slicing them one by one
  24694. while (ear.prev !== ear.next) {
  24695. const prev = ear.prev;
  24696. const next = ear.next;
  24697. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  24698. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  24699. removeNode(ear);
  24700. // skipping the next vertex leads to less sliver triangles
  24701. ear = next.next;
  24702. stop = next.next;
  24703. continue;
  24704. }
  24705. ear = next;
  24706. // if we looped through the whole remaining polygon and can't find any more ears
  24707. if (ear === stop) {
  24708. // try filtering points and slicing again
  24709. if (!pass) {
  24710. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  24711. // if this didn't work, try curing all small self-intersections locally
  24712. } else if (pass === 1) {
  24713. ear = cureLocalIntersections(filterPoints(ear), triangles);
  24714. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  24715. // as a last resort, try splitting the remaining polygon into two
  24716. } else if (pass === 2) {
  24717. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  24718. }
  24719. break;
  24720. }
  24721. }
  24722. }
  24723. // check whether a polygon node forms a valid ear with adjacent nodes
  24724. function isEar(ear) {
  24725. const a = ear.prev,
  24726. b = ear,
  24727. c = ear.next;
  24728. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24729. // now make sure we don't have other points inside the potential ear
  24730. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24731. // triangle bbox
  24732. const x0 = Math.min(ax, bx, cx),
  24733. y0 = Math.min(ay, by, cy),
  24734. x1 = Math.max(ax, bx, cx),
  24735. y1 = Math.max(ay, by, cy);
  24736. let p = c.next;
  24737. while (p !== a) {
  24738. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  24739. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  24740. area(p.prev, p, p.next) >= 0) return false;
  24741. p = p.next;
  24742. }
  24743. return true;
  24744. }
  24745. function isEarHashed(ear, minX, minY, invSize) {
  24746. const a = ear.prev,
  24747. b = ear,
  24748. c = ear.next;
  24749. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24750. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24751. // triangle bbox
  24752. const x0 = Math.min(ax, bx, cx),
  24753. y0 = Math.min(ay, by, cy),
  24754. x1 = Math.max(ax, bx, cx),
  24755. y1 = Math.max(ay, by, cy);
  24756. // z-order range for the current triangle bbox;
  24757. const minZ = zOrder(x0, y0, minX, minY, invSize),
  24758. maxZ = zOrder(x1, y1, minX, minY, invSize);
  24759. let p = ear.prevZ,
  24760. n = ear.nextZ;
  24761. // look for points inside the triangle in both directions
  24762. while (p && p.z >= minZ && n && n.z <= maxZ) {
  24763. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24764. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24765. p = p.prevZ;
  24766. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24767. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24768. n = n.nextZ;
  24769. }
  24770. // look for remaining points in decreasing z-order
  24771. while (p && p.z >= minZ) {
  24772. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24773. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24774. p = p.prevZ;
  24775. }
  24776. // look for remaining points in increasing z-order
  24777. while (n && n.z <= maxZ) {
  24778. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24779. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24780. n = n.nextZ;
  24781. }
  24782. return true;
  24783. }
  24784. // go through all polygon nodes and cure small local self-intersections
  24785. function cureLocalIntersections(start, triangles) {
  24786. let p = start;
  24787. do {
  24788. const a = p.prev,
  24789. b = p.next.next;
  24790. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  24791. triangles.push(a.i, p.i, b.i);
  24792. // remove two nodes involved
  24793. removeNode(p);
  24794. removeNode(p.next);
  24795. p = start = b;
  24796. }
  24797. p = p.next;
  24798. } while (p !== start);
  24799. return filterPoints(p);
  24800. }
  24801. // try splitting polygon into two and triangulate them independently
  24802. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  24803. // look for a valid diagonal that divides the polygon into two
  24804. let a = start;
  24805. do {
  24806. let b = a.next.next;
  24807. while (b !== a.prev) {
  24808. if (a.i !== b.i && isValidDiagonal(a, b)) {
  24809. // split the polygon in two by the diagonal
  24810. let c = splitPolygon(a, b);
  24811. // filter colinear points around the cuts
  24812. a = filterPoints(a, a.next);
  24813. c = filterPoints(c, c.next);
  24814. // run earcut on each half
  24815. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  24816. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  24817. return;
  24818. }
  24819. b = b.next;
  24820. }
  24821. a = a.next;
  24822. } while (a !== start);
  24823. }
  24824. // link every hole into the outer loop, producing a single-ring polygon without holes
  24825. function eliminateHoles(data, holeIndices, outerNode, dim) {
  24826. const queue = [];
  24827. for (let i = 0, len = holeIndices.length; i < len; i++) {
  24828. const start = holeIndices[i] * dim;
  24829. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  24830. const list = linkedList(data, start, end, dim, false);
  24831. if (list === list.next) list.steiner = true;
  24832. queue.push(getLeftmost(list));
  24833. }
  24834. queue.sort(compareXYSlope);
  24835. // process holes from left to right
  24836. for (let i = 0; i < queue.length; i++) {
  24837. outerNode = eliminateHole(queue[i], outerNode);
  24838. }
  24839. return outerNode;
  24840. }
  24841. function compareXYSlope(a, b) {
  24842. let result = a.x - b.x;
  24843. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  24844. // the bridge to the outer shell is always the point that they meet at.
  24845. if (result === 0) {
  24846. result = a.y - b.y;
  24847. if (result === 0) {
  24848. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  24849. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  24850. result = aSlope - bSlope;
  24851. }
  24852. }
  24853. return result;
  24854. }
  24855. // find a bridge between vertices that connects hole with an outer ring and link it
  24856. function eliminateHole(hole, outerNode) {
  24857. const bridge = findHoleBridge(hole, outerNode);
  24858. if (!bridge) {
  24859. return outerNode;
  24860. }
  24861. const bridgeReverse = splitPolygon(bridge, hole);
  24862. // filter collinear points around the cuts
  24863. filterPoints(bridgeReverse, bridgeReverse.next);
  24864. return filterPoints(bridge, bridge.next);
  24865. }
  24866. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  24867. function findHoleBridge(hole, outerNode) {
  24868. let p = outerNode;
  24869. const hx = hole.x;
  24870. const hy = hole.y;
  24871. let qx = -Infinity;
  24872. let m;
  24873. // find a segment intersected by a ray from the hole's leftmost point to the left;
  24874. // segment's endpoint with lesser x will be potential connection point
  24875. // unless they intersect at a vertex, then choose the vertex
  24876. if (equals(hole, p)) return p;
  24877. do {
  24878. if (equals(hole, p.next)) return p.next;
  24879. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  24880. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  24881. if (x <= hx && x > qx) {
  24882. qx = x;
  24883. m = p.x < p.next.x ? p : p.next;
  24884. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  24885. }
  24886. }
  24887. p = p.next;
  24888. } while (p !== outerNode);
  24889. if (!m) return null;
  24890. // look for points inside the triangle of hole point, segment intersection and endpoint;
  24891. // if there are no points found, we have a valid connection;
  24892. // otherwise choose the point of the minimum angle with the ray as connection point
  24893. const stop = m;
  24894. const mx = m.x;
  24895. const my = m.y;
  24896. let tanMin = Infinity;
  24897. p = m;
  24898. do {
  24899. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  24900. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  24901. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  24902. if (locallyInside(p, hole) &&
  24903. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  24904. m = p;
  24905. tanMin = tan;
  24906. }
  24907. }
  24908. p = p.next;
  24909. } while (p !== stop);
  24910. return m;
  24911. }
  24912. // whether sector in vertex m contains sector in vertex p in the same coordinates
  24913. function sectorContainsSector(m, p) {
  24914. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  24915. }
  24916. // interlink polygon nodes in z-order
  24917. function indexCurve(start, minX, minY, invSize) {
  24918. let p = start;
  24919. do {
  24920. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  24921. p.prevZ = p.prev;
  24922. p.nextZ = p.next;
  24923. p = p.next;
  24924. } while (p !== start);
  24925. p.prevZ.nextZ = null;
  24926. p.prevZ = null;
  24927. sortLinked(p);
  24928. }
  24929. // Simon Tatham's linked list merge sort algorithm
  24930. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  24931. function sortLinked(list) {
  24932. let numMerges;
  24933. let inSize = 1;
  24934. do {
  24935. let p = list;
  24936. let e;
  24937. list = null;
  24938. let tail = null;
  24939. numMerges = 0;
  24940. while (p) {
  24941. numMerges++;
  24942. let q = p;
  24943. let pSize = 0;
  24944. for (let i = 0; i < inSize; i++) {
  24945. pSize++;
  24946. q = q.nextZ;
  24947. if (!q) break;
  24948. }
  24949. let qSize = inSize;
  24950. while (pSize > 0 || (qSize > 0 && q)) {
  24951. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  24952. e = p;
  24953. p = p.nextZ;
  24954. pSize--;
  24955. } else {
  24956. e = q;
  24957. q = q.nextZ;
  24958. qSize--;
  24959. }
  24960. if (tail) tail.nextZ = e;
  24961. else list = e;
  24962. e.prevZ = tail;
  24963. tail = e;
  24964. }
  24965. p = q;
  24966. }
  24967. tail.nextZ = null;
  24968. inSize *= 2;
  24969. } while (numMerges > 1);
  24970. return list;
  24971. }
  24972. // z-order of a point given coords and inverse of the longer side of data bbox
  24973. function zOrder(x, y, minX, minY, invSize) {
  24974. // coords are transformed into non-negative 15-bit integer range
  24975. x = (x - minX) * invSize | 0;
  24976. y = (y - minY) * invSize | 0;
  24977. x = (x | (x << 8)) & 0x00FF00FF;
  24978. x = (x | (x << 4)) & 0x0F0F0F0F;
  24979. x = (x | (x << 2)) & 0x33333333;
  24980. x = (x | (x << 1)) & 0x55555555;
  24981. y = (y | (y << 8)) & 0x00FF00FF;
  24982. y = (y | (y << 4)) & 0x0F0F0F0F;
  24983. y = (y | (y << 2)) & 0x33333333;
  24984. y = (y | (y << 1)) & 0x55555555;
  24985. return x | (y << 1);
  24986. }
  24987. // find the leftmost node of a polygon ring
  24988. function getLeftmost(start) {
  24989. let p = start,
  24990. leftmost = start;
  24991. do {
  24992. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  24993. p = p.next;
  24994. } while (p !== start);
  24995. return leftmost;
  24996. }
  24997. // check if a point lies within a convex triangle
  24998. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  24999. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25000. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25001. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25002. }
  25003. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25004. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25005. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25006. }
  25007. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25008. function isValidDiagonal(a, b) {
  25009. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25010. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25011. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25012. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25013. }
  25014. // signed area of a triangle
  25015. function area(p, q, r) {
  25016. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25017. }
  25018. // check if two points are equal
  25019. function equals(p1, p2) {
  25020. return p1.x === p2.x && p1.y === p2.y;
  25021. }
  25022. // check if two segments intersect
  25023. function intersects(p1, q1, p2, q2) {
  25024. const o1 = sign(area(p1, q1, p2));
  25025. const o2 = sign(area(p1, q1, q2));
  25026. const o3 = sign(area(p2, q2, p1));
  25027. const o4 = sign(area(p2, q2, q1));
  25028. if (o1 !== o2 && o3 !== o4) return true; // general case
  25029. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25030. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25031. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25032. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25033. return false;
  25034. }
  25035. // for collinear points p, q, r, check if point q lies on segment pr
  25036. function onSegment(p, q, r) {
  25037. 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);
  25038. }
  25039. function sign(num) {
  25040. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25041. }
  25042. // check if a polygon diagonal intersects any polygon segments
  25043. function intersectsPolygon(a, b) {
  25044. let p = a;
  25045. do {
  25046. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25047. intersects(p, p.next, a, b)) return true;
  25048. p = p.next;
  25049. } while (p !== a);
  25050. return false;
  25051. }
  25052. // check if a polygon diagonal is locally inside the polygon
  25053. function locallyInside(a, b) {
  25054. return area(a.prev, a, a.next) < 0 ?
  25055. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25056. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25057. }
  25058. // check if the middle point of a polygon diagonal is inside the polygon
  25059. function middleInside(a, b) {
  25060. let p = a;
  25061. let inside = false;
  25062. const px = (a.x + b.x) / 2;
  25063. const py = (a.y + b.y) / 2;
  25064. do {
  25065. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25066. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25067. inside = !inside;
  25068. p = p.next;
  25069. } while (p !== a);
  25070. return inside;
  25071. }
  25072. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25073. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25074. function splitPolygon(a, b) {
  25075. const a2 = createNode(a.i, a.x, a.y),
  25076. b2 = createNode(b.i, b.x, b.y),
  25077. an = a.next,
  25078. bp = b.prev;
  25079. a.next = b;
  25080. b.prev = a;
  25081. a2.next = an;
  25082. an.prev = a2;
  25083. b2.next = a2;
  25084. a2.prev = b2;
  25085. bp.next = b2;
  25086. b2.prev = bp;
  25087. return b2;
  25088. }
  25089. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25090. function insertNode(i, x, y, last) {
  25091. const p = createNode(i, x, y);
  25092. if (!last) {
  25093. p.prev = p;
  25094. p.next = p;
  25095. } else {
  25096. p.next = last.next;
  25097. p.prev = last;
  25098. last.next.prev = p;
  25099. last.next = p;
  25100. }
  25101. return p;
  25102. }
  25103. function removeNode(p) {
  25104. p.next.prev = p.prev;
  25105. p.prev.next = p.next;
  25106. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25107. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25108. }
  25109. function createNode(i, x, y) {
  25110. return {
  25111. i, // vertex index in coordinates array
  25112. x, y, // vertex coordinates
  25113. prev: null, // previous and next vertex nodes in a polygon ring
  25114. next: null,
  25115. z: 0, // z-order curve value
  25116. prevZ: null, // previous and next nodes in z-order
  25117. nextZ: null,
  25118. steiner: false // indicates whether this is a steiner point
  25119. };
  25120. }
  25121. function signedArea(data, start, end, dim) {
  25122. let sum = 0;
  25123. for (let i = start, j = end - dim; i < end; i += dim) {
  25124. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25125. j = i;
  25126. }
  25127. return sum;
  25128. }
  25129. /**
  25130. * An implementation of the earcut polygon triangulation algorithm.
  25131. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25132. *
  25133. * @see https://github.com/mapbox/earcut
  25134. */
  25135. class Earcut {
  25136. /**
  25137. * Triangulates the given shape definition by returning an array of triangles.
  25138. *
  25139. * @param {Array<number>} data - An array with 2D points.
  25140. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25141. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25142. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25143. * representing vertex indices.
  25144. */
  25145. static triangulate( data, holeIndices, dim = 2 ) {
  25146. return earcut( data, holeIndices, dim );
  25147. }
  25148. }
  25149. /**
  25150. * A class containing utility functions for shapes.
  25151. *
  25152. * @hideconstructor
  25153. */
  25154. class ShapeUtils {
  25155. /**
  25156. * Calculate area of a ( 2D ) contour polygon.
  25157. *
  25158. * @param {Array<Vector2>} contour - An array of 2D points.
  25159. * @return {number} The area.
  25160. */
  25161. static area( contour ) {
  25162. const n = contour.length;
  25163. let a = 0.0;
  25164. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25165. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25166. }
  25167. return a * 0.5;
  25168. }
  25169. /**
  25170. * Returns `true` if the given contour uses a clockwise winding order.
  25171. *
  25172. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25173. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25174. */
  25175. static isClockWise( pts ) {
  25176. return ShapeUtils.area( pts ) < 0;
  25177. }
  25178. /**
  25179. * Triangulates the given shape definition.
  25180. *
  25181. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25182. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25183. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25184. */
  25185. static triangulateShape( contour, holes ) {
  25186. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25187. const holeIndices = []; // array of hole indices
  25188. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25189. removeDupEndPts( contour );
  25190. addContour( vertices, contour );
  25191. //
  25192. let holeIndex = contour.length;
  25193. holes.forEach( removeDupEndPts );
  25194. for ( let i = 0; i < holes.length; i ++ ) {
  25195. holeIndices.push( holeIndex );
  25196. holeIndex += holes[ i ].length;
  25197. addContour( vertices, holes[ i ] );
  25198. }
  25199. //
  25200. const triangles = Earcut.triangulate( vertices, holeIndices );
  25201. //
  25202. for ( let i = 0; i < triangles.length; i += 3 ) {
  25203. faces.push( triangles.slice( i, i + 3 ) );
  25204. }
  25205. return faces;
  25206. }
  25207. }
  25208. function removeDupEndPts( points ) {
  25209. const l = points.length;
  25210. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25211. points.pop();
  25212. }
  25213. }
  25214. function addContour( vertices, contour ) {
  25215. for ( let i = 0; i < contour.length; i ++ ) {
  25216. vertices.push( contour[ i ].x );
  25217. vertices.push( contour[ i ].y );
  25218. }
  25219. }
  25220. /**
  25221. * Creates extruded geometry from a path shape.
  25222. *
  25223. * ```js
  25224. * const length = 12, width = 8;
  25225. *
  25226. * const shape = new THREE.Shape();
  25227. * shape.moveTo( 0,0 );
  25228. * shape.lineTo( 0, width );
  25229. * shape.lineTo( length, width );
  25230. * shape.lineTo( length, 0 );
  25231. * shape.lineTo( 0, 0 );
  25232. *
  25233. * const geometry = new THREE.ExtrudeGeometry( shape );
  25234. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25235. * const mesh = new THREE.Mesh( geometry, material ) ;
  25236. * scene.add( mesh );
  25237. * ```
  25238. *
  25239. * @augments BufferGeometry
  25240. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25241. */
  25242. class ExtrudeGeometry extends BufferGeometry {
  25243. /**
  25244. * Constructs a new extrude geometry.
  25245. *
  25246. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25247. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25248. */
  25249. 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 = {} ) {
  25250. super();
  25251. this.type = 'ExtrudeGeometry';
  25252. /**
  25253. * Holds the constructor parameters that have been
  25254. * used to generate the geometry. Any modification
  25255. * after instantiation does not change the geometry.
  25256. *
  25257. * @type {Object}
  25258. */
  25259. this.parameters = {
  25260. shapes: shapes,
  25261. options: options
  25262. };
  25263. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25264. const scope = this;
  25265. const verticesArray = [];
  25266. const uvArray = [];
  25267. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25268. const shape = shapes[ i ];
  25269. addShape( shape );
  25270. }
  25271. // build geometry
  25272. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25273. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25274. this.computeVertexNormals();
  25275. // functions
  25276. function addShape( shape ) {
  25277. const placeholder = [];
  25278. // options
  25279. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25280. const steps = options.steps !== undefined ? options.steps : 1;
  25281. const depth = options.depth !== undefined ? options.depth : 1;
  25282. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25283. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25284. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25285. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25286. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25287. const extrudePath = options.extrudePath;
  25288. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25289. //
  25290. let extrudePts, extrudeByPath = false;
  25291. let splineTube, binormal, normal, position2;
  25292. if ( extrudePath ) {
  25293. extrudePts = extrudePath.getSpacedPoints( steps );
  25294. extrudeByPath = true;
  25295. bevelEnabled = false; // bevels not supported for path extrusion
  25296. // SETUP TNB variables
  25297. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  25298. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  25299. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25300. binormal = new Vector3();
  25301. normal = new Vector3();
  25302. position2 = new Vector3();
  25303. }
  25304. // Safeguards if bevels are not enabled
  25305. if ( ! bevelEnabled ) {
  25306. bevelSegments = 0;
  25307. bevelThickness = 0;
  25308. bevelSize = 0;
  25309. bevelOffset = 0;
  25310. }
  25311. // Variables initialization
  25312. const shapePoints = shape.extractPoints( curveSegments );
  25313. let vertices = shapePoints.shape;
  25314. const holes = shapePoints.holes;
  25315. const reverse = ! ShapeUtils.isClockWise( vertices );
  25316. if ( reverse ) {
  25317. vertices = vertices.reverse();
  25318. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25319. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25320. const ahole = holes[ h ];
  25321. if ( ShapeUtils.isClockWise( ahole ) ) {
  25322. holes[ h ] = ahole.reverse();
  25323. }
  25324. }
  25325. }
  25326. /**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.
  25327. * @param {Array<Vector2>} points
  25328. */
  25329. function mergeOverlappingPoints( points ) {
  25330. const THRESHOLD = 1e-10;
  25331. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25332. let prevPos = points[ 0 ];
  25333. for ( let i = 1; i <= points.length; i ++ ) {
  25334. const currentIndex = i % points.length;
  25335. const currentPos = points[ currentIndex ];
  25336. const dx = currentPos.x - prevPos.x;
  25337. const dy = currentPos.y - prevPos.y;
  25338. const distSq = dx * dx + dy * dy;
  25339. const scalingFactorSqrt = Math.max(
  25340. Math.abs( currentPos.x ),
  25341. Math.abs( currentPos.y ),
  25342. Math.abs( prevPos.x ),
  25343. Math.abs( prevPos.y )
  25344. );
  25345. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25346. if ( distSq <= thresholdSqScaled ) {
  25347. points.splice( currentIndex, 1 );
  25348. i --;
  25349. continue;
  25350. }
  25351. prevPos = currentPos;
  25352. }
  25353. }
  25354. mergeOverlappingPoints( vertices );
  25355. holes.forEach( mergeOverlappingPoints );
  25356. const numHoles = holes.length;
  25357. /* Vertices */
  25358. const contour = vertices; // vertices has all points but contour has only points of circumference
  25359. for ( let h = 0; h < numHoles; h ++ ) {
  25360. const ahole = holes[ h ];
  25361. vertices = vertices.concat( ahole );
  25362. }
  25363. function scalePt2( pt, vec, size ) {
  25364. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  25365. return pt.clone().addScaledVector( vec, size );
  25366. }
  25367. const vlen = vertices.length;
  25368. // Find directions for point movement
  25369. function getBevelVec( inPt, inPrev, inNext ) {
  25370. // computes for inPt the corresponding point inPt' on a new contour
  25371. // shifted by 1 unit (length of normalized vector) to the left
  25372. // if we walk along contour clockwise, this new contour is outside the old one
  25373. //
  25374. // inPt' is the intersection of the two lines parallel to the two
  25375. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25376. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25377. // good reading for geometry algorithms (here: line-line intersection)
  25378. // http://geomalgorithms.com/a05-_intersect-1.html
  25379. const v_prev_x = inPt.x - inPrev.x,
  25380. v_prev_y = inPt.y - inPrev.y;
  25381. const v_next_x = inNext.x - inPt.x,
  25382. v_next_y = inNext.y - inPt.y;
  25383. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25384. // check for collinear edges
  25385. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25386. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25387. // not collinear
  25388. // length of vectors for normalizing
  25389. const v_prev_len = Math.sqrt( v_prev_lensq );
  25390. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25391. // shift adjacent points by unit vectors to the left
  25392. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25393. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25394. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25395. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25396. // scaling factor for v_prev to intersection point
  25397. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25398. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25399. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25400. // vector from inPt to intersection point
  25401. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25402. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25403. // Don't normalize!, otherwise sharp corners become ugly
  25404. // but prevent crazy spikes
  25405. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25406. if ( v_trans_lensq <= 2 ) {
  25407. return new Vector2( v_trans_x, v_trans_y );
  25408. } else {
  25409. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25410. }
  25411. } else {
  25412. // handle special case of collinear edges
  25413. let direction_eq = false; // assumes: opposite
  25414. if ( v_prev_x > Number.EPSILON ) {
  25415. if ( v_next_x > Number.EPSILON ) {
  25416. direction_eq = true;
  25417. }
  25418. } else {
  25419. if ( v_prev_x < - Number.EPSILON ) {
  25420. if ( v_next_x < - Number.EPSILON ) {
  25421. direction_eq = true;
  25422. }
  25423. } else {
  25424. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25425. direction_eq = true;
  25426. }
  25427. }
  25428. }
  25429. if ( direction_eq ) {
  25430. // log("Warning: lines are a straight sequence");
  25431. v_trans_x = - v_prev_y;
  25432. v_trans_y = v_prev_x;
  25433. shrink_by = Math.sqrt( v_prev_lensq );
  25434. } else {
  25435. // log("Warning: lines are a straight spike");
  25436. v_trans_x = v_prev_x;
  25437. v_trans_y = v_prev_y;
  25438. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25439. }
  25440. }
  25441. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25442. }
  25443. const contourMovements = [];
  25444. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25445. if ( j === il ) j = 0;
  25446. if ( k === il ) k = 0;
  25447. // (j)---(i)---(k)
  25448. // log('i,j,k', i, j , k)
  25449. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25450. }
  25451. const holesMovements = [];
  25452. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25453. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25454. const ahole = holes[ h ];
  25455. oneHoleMovements = [];
  25456. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25457. if ( j === il ) j = 0;
  25458. if ( k === il ) k = 0;
  25459. // (j)---(i)---(k)
  25460. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25461. }
  25462. holesMovements.push( oneHoleMovements );
  25463. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25464. }
  25465. let faces;
  25466. if ( bevelSegments === 0 ) {
  25467. faces = ShapeUtils.triangulateShape( contour, holes );
  25468. } else {
  25469. const contractedContourVertices = [];
  25470. const expandedHoleVertices = [];
  25471. // Loop bevelSegments, 1 for the front, 1 for the back
  25472. for ( let b = 0; b < bevelSegments; b ++ ) {
  25473. //for ( b = bevelSegments; b > 0; b -- ) {
  25474. const t = b / bevelSegments;
  25475. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25476. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25477. // contract shape
  25478. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25479. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25480. v( vert.x, vert.y, - z );
  25481. if ( t === 0 ) contractedContourVertices.push( vert );
  25482. }
  25483. // expand holes
  25484. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25485. const ahole = holes[ h ];
  25486. oneHoleMovements = holesMovements[ h ];
  25487. const oneHoleVertices = [];
  25488. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25489. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25490. v( vert.x, vert.y, - z );
  25491. if ( t === 0 ) oneHoleVertices.push( vert );
  25492. }
  25493. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25494. }
  25495. }
  25496. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25497. }
  25498. const flen = faces.length;
  25499. const bs = bevelSize + bevelOffset;
  25500. // Back facing vertices
  25501. for ( let i = 0; i < vlen; i ++ ) {
  25502. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25503. if ( ! extrudeByPath ) {
  25504. v( vert.x, vert.y, 0 );
  25505. } else {
  25506. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25507. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25508. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25509. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25510. v( position2.x, position2.y, position2.z );
  25511. }
  25512. }
  25513. // Add stepped vertices...
  25514. // Including front facing vertices
  25515. for ( let s = 1; s <= steps; s ++ ) {
  25516. for ( let i = 0; i < vlen; i ++ ) {
  25517. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25518. if ( ! extrudeByPath ) {
  25519. v( vert.x, vert.y, depth / steps * s );
  25520. } else {
  25521. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25522. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25523. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25524. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25525. v( position2.x, position2.y, position2.z );
  25526. }
  25527. }
  25528. }
  25529. // Add bevel segments planes
  25530. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25531. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25532. const t = b / bevelSegments;
  25533. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25534. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25535. // contract shape
  25536. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25537. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25538. v( vert.x, vert.y, depth + z );
  25539. }
  25540. // expand holes
  25541. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25542. const ahole = holes[ h ];
  25543. oneHoleMovements = holesMovements[ h ];
  25544. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25545. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25546. if ( ! extrudeByPath ) {
  25547. v( vert.x, vert.y, depth + z );
  25548. } else {
  25549. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25550. }
  25551. }
  25552. }
  25553. }
  25554. /* Faces */
  25555. // Top and bottom faces
  25556. buildLidFaces();
  25557. // Sides faces
  25558. buildSideFaces();
  25559. ///// Internal functions
  25560. function buildLidFaces() {
  25561. const start = verticesArray.length / 3;
  25562. if ( bevelEnabled ) {
  25563. let layer = 0; // steps + 1
  25564. let offset = vlen * layer;
  25565. // Bottom faces
  25566. for ( let i = 0; i < flen; i ++ ) {
  25567. const face = faces[ i ];
  25568. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25569. }
  25570. layer = steps + bevelSegments * 2;
  25571. offset = vlen * layer;
  25572. // Top faces
  25573. for ( let i = 0; i < flen; i ++ ) {
  25574. const face = faces[ i ];
  25575. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25576. }
  25577. } else {
  25578. // Bottom faces
  25579. for ( let i = 0; i < flen; i ++ ) {
  25580. const face = faces[ i ];
  25581. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25582. }
  25583. // Top faces
  25584. for ( let i = 0; i < flen; i ++ ) {
  25585. const face = faces[ i ];
  25586. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25587. }
  25588. }
  25589. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25590. }
  25591. // Create faces for the z-sides of the shape
  25592. function buildSideFaces() {
  25593. const start = verticesArray.length / 3;
  25594. let layeroffset = 0;
  25595. sidewalls( contour, layeroffset );
  25596. layeroffset += contour.length;
  25597. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25598. const ahole = holes[ h ];
  25599. sidewalls( ahole, layeroffset );
  25600. //, true
  25601. layeroffset += ahole.length;
  25602. }
  25603. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25604. }
  25605. function sidewalls( contour, layeroffset ) {
  25606. let i = contour.length;
  25607. while ( -- i >= 0 ) {
  25608. const j = i;
  25609. let k = i - 1;
  25610. if ( k < 0 ) k = contour.length - 1;
  25611. //log('b', i,j, i-1, k,vertices.length);
  25612. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25613. const slen1 = vlen * s;
  25614. const slen2 = vlen * ( s + 1 );
  25615. const a = layeroffset + j + slen1,
  25616. b = layeroffset + k + slen1,
  25617. c = layeroffset + k + slen2,
  25618. d = layeroffset + j + slen2;
  25619. f4( a, b, c, d );
  25620. }
  25621. }
  25622. }
  25623. function v( x, y, z ) {
  25624. placeholder.push( x );
  25625. placeholder.push( y );
  25626. placeholder.push( z );
  25627. }
  25628. function f3( a, b, c ) {
  25629. addVertex( a );
  25630. addVertex( b );
  25631. addVertex( c );
  25632. const nextIndex = verticesArray.length / 3;
  25633. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25634. addUV( uvs[ 0 ] );
  25635. addUV( uvs[ 1 ] );
  25636. addUV( uvs[ 2 ] );
  25637. }
  25638. function f4( a, b, c, d ) {
  25639. addVertex( a );
  25640. addVertex( b );
  25641. addVertex( d );
  25642. addVertex( b );
  25643. addVertex( c );
  25644. addVertex( d );
  25645. const nextIndex = verticesArray.length / 3;
  25646. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25647. addUV( uvs[ 0 ] );
  25648. addUV( uvs[ 1 ] );
  25649. addUV( uvs[ 3 ] );
  25650. addUV( uvs[ 1 ] );
  25651. addUV( uvs[ 2 ] );
  25652. addUV( uvs[ 3 ] );
  25653. }
  25654. function addVertex( index ) {
  25655. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25656. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25657. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25658. }
  25659. function addUV( vector2 ) {
  25660. uvArray.push( vector2.x );
  25661. uvArray.push( vector2.y );
  25662. }
  25663. }
  25664. }
  25665. copy( source ) {
  25666. super.copy( source );
  25667. this.parameters = Object.assign( {}, source.parameters );
  25668. return this;
  25669. }
  25670. toJSON() {
  25671. const data = super.toJSON();
  25672. const shapes = this.parameters.shapes;
  25673. const options = this.parameters.options;
  25674. return toJSON$1( shapes, options, data );
  25675. }
  25676. /**
  25677. * Factory method for creating an instance of this class from the given
  25678. * JSON object.
  25679. *
  25680. * @param {Object} data - A JSON object representing the serialized geometry.
  25681. * @param {Array<Shape>} shapes - An array of shapes.
  25682. * @return {ExtrudeGeometry} A new instance.
  25683. */
  25684. static fromJSON( data, shapes ) {
  25685. const geometryShapes = [];
  25686. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25687. const shape = shapes[ data.shapes[ j ] ];
  25688. geometryShapes.push( shape );
  25689. }
  25690. const extrudePath = data.options.extrudePath;
  25691. if ( extrudePath !== undefined ) {
  25692. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25693. }
  25694. return new ExtrudeGeometry( geometryShapes, data.options );
  25695. }
  25696. }
  25697. const WorldUVGenerator = {
  25698. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  25699. const a_x = vertices[ indexA * 3 ];
  25700. const a_y = vertices[ indexA * 3 + 1 ];
  25701. const b_x = vertices[ indexB * 3 ];
  25702. const b_y = vertices[ indexB * 3 + 1 ];
  25703. const c_x = vertices[ indexC * 3 ];
  25704. const c_y = vertices[ indexC * 3 + 1 ];
  25705. return [
  25706. new Vector2( a_x, a_y ),
  25707. new Vector2( b_x, b_y ),
  25708. new Vector2( c_x, c_y )
  25709. ];
  25710. },
  25711. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  25712. const a_x = vertices[ indexA * 3 ];
  25713. const a_y = vertices[ indexA * 3 + 1 ];
  25714. const a_z = vertices[ indexA * 3 + 2 ];
  25715. const b_x = vertices[ indexB * 3 ];
  25716. const b_y = vertices[ indexB * 3 + 1 ];
  25717. const b_z = vertices[ indexB * 3 + 2 ];
  25718. const c_x = vertices[ indexC * 3 ];
  25719. const c_y = vertices[ indexC * 3 + 1 ];
  25720. const c_z = vertices[ indexC * 3 + 2 ];
  25721. const d_x = vertices[ indexD * 3 ];
  25722. const d_y = vertices[ indexD * 3 + 1 ];
  25723. const d_z = vertices[ indexD * 3 + 2 ];
  25724. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  25725. return [
  25726. new Vector2( a_x, 1 - a_z ),
  25727. new Vector2( b_x, 1 - b_z ),
  25728. new Vector2( c_x, 1 - c_z ),
  25729. new Vector2( d_x, 1 - d_z )
  25730. ];
  25731. } else {
  25732. return [
  25733. new Vector2( a_y, 1 - a_z ),
  25734. new Vector2( b_y, 1 - b_z ),
  25735. new Vector2( c_y, 1 - c_z ),
  25736. new Vector2( d_y, 1 - d_z )
  25737. ];
  25738. }
  25739. }
  25740. };
  25741. function toJSON$1( shapes, options, data ) {
  25742. data.shapes = [];
  25743. if ( Array.isArray( shapes ) ) {
  25744. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25745. const shape = shapes[ i ];
  25746. data.shapes.push( shape.uuid );
  25747. }
  25748. } else {
  25749. data.shapes.push( shapes.uuid );
  25750. }
  25751. data.options = Object.assign( {}, options );
  25752. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  25753. return data;
  25754. }
  25755. /**
  25756. * A geometry class for representing an icosahedron.
  25757. *
  25758. * ```js
  25759. * const geometry = new THREE.IcosahedronGeometry();
  25760. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25761. * const icosahedron = new THREE.Mesh( geometry, material );
  25762. * scene.add( icosahedron );
  25763. * ```
  25764. *
  25765. * @augments PolyhedronGeometry
  25766. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  25767. */
  25768. class IcosahedronGeometry extends PolyhedronGeometry {
  25769. /**
  25770. * Constructs a new icosahedron geometry.
  25771. *
  25772. * @param {number} [radius=1] - Radius of the icosahedron.
  25773. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  25774. */
  25775. constructor( radius = 1, detail = 0 ) {
  25776. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  25777. const vertices = [
  25778. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  25779. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  25780. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  25781. ];
  25782. const indices = [
  25783. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  25784. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  25785. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  25786. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  25787. ];
  25788. super( vertices, indices, radius, detail );
  25789. this.type = 'IcosahedronGeometry';
  25790. /**
  25791. * Holds the constructor parameters that have been
  25792. * used to generate the geometry. Any modification
  25793. * after instantiation does not change the geometry.
  25794. *
  25795. * @type {Object}
  25796. */
  25797. this.parameters = {
  25798. radius: radius,
  25799. detail: detail
  25800. };
  25801. }
  25802. /**
  25803. * Factory method for creating an instance of this class from the given
  25804. * JSON object.
  25805. *
  25806. * @param {Object} data - A JSON object representing the serialized geometry.
  25807. * @return {IcosahedronGeometry} A new instance.
  25808. */
  25809. static fromJSON( data ) {
  25810. return new IcosahedronGeometry( data.radius, data.detail );
  25811. }
  25812. }
  25813. /**
  25814. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  25815. *
  25816. * ```js
  25817. * const points = [];
  25818. * for ( let i = 0; i < 10; i ++ ) {
  25819. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  25820. * }
  25821. * const geometry = new THREE.LatheGeometry( points );
  25822. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25823. * const lathe = new THREE.Mesh( geometry, material );
  25824. * scene.add( lathe );
  25825. * ```
  25826. *
  25827. * @augments BufferGeometry
  25828. * @demo scenes/geometry-browser.html#LatheGeometry
  25829. */
  25830. class LatheGeometry extends BufferGeometry {
  25831. /**
  25832. * Constructs a new lathe geometry.
  25833. *
  25834. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  25835. * must be greater than zero.
  25836. * @param {number} [segments=12] - The number of circumference segments to generate.
  25837. * @param {number} [phiStart=0] - The starting angle in radians.
  25838. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  25839. * closed lathe, less than 2PI is a portion.
  25840. */
  25841. 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 ) {
  25842. super();
  25843. this.type = 'LatheGeometry';
  25844. /**
  25845. * Holds the constructor parameters that have been
  25846. * used to generate the geometry. Any modification
  25847. * after instantiation does not change the geometry.
  25848. *
  25849. * @type {Object}
  25850. */
  25851. this.parameters = {
  25852. points: points,
  25853. segments: segments,
  25854. phiStart: phiStart,
  25855. phiLength: phiLength
  25856. };
  25857. segments = Math.floor( segments );
  25858. // clamp phiLength so it's in range of [ 0, 2PI ]
  25859. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  25860. // buffers
  25861. const indices = [];
  25862. const vertices = [];
  25863. const uvs = [];
  25864. const initNormals = [];
  25865. const normals = [];
  25866. // helper variables
  25867. const inverseSegments = 1.0 / segments;
  25868. const vertex = new Vector3();
  25869. const uv = new Vector2();
  25870. const normal = new Vector3();
  25871. const curNormal = new Vector3();
  25872. const prevNormal = new Vector3();
  25873. let dx = 0;
  25874. let dy = 0;
  25875. // pre-compute normals for initial "meridian"
  25876. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  25877. switch ( j ) {
  25878. case 0: // special handling for 1st vertex on path
  25879. dx = points[ j + 1 ].x - points[ j ].x;
  25880. dy = points[ j + 1 ].y - points[ j ].y;
  25881. normal.x = dy * 1.0;
  25882. normal.y = - dx;
  25883. normal.z = dy * 0.0;
  25884. prevNormal.copy( normal );
  25885. normal.normalize();
  25886. initNormals.push( normal.x, normal.y, normal.z );
  25887. break;
  25888. case ( points.length - 1 ): // special handling for last Vertex on path
  25889. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  25890. break;
  25891. default: // default handling for all vertices in between
  25892. dx = points[ j + 1 ].x - points[ j ].x;
  25893. dy = points[ j + 1 ].y - points[ j ].y;
  25894. normal.x = dy * 1.0;
  25895. normal.y = - dx;
  25896. normal.z = dy * 0.0;
  25897. curNormal.copy( normal );
  25898. normal.x += prevNormal.x;
  25899. normal.y += prevNormal.y;
  25900. normal.z += prevNormal.z;
  25901. normal.normalize();
  25902. initNormals.push( normal.x, normal.y, normal.z );
  25903. prevNormal.copy( curNormal );
  25904. }
  25905. }
  25906. // generate vertices, uvs and normals
  25907. for ( let i = 0; i <= segments; i ++ ) {
  25908. const phi = phiStart + i * inverseSegments * phiLength;
  25909. const sin = Math.sin( phi );
  25910. const cos = Math.cos( phi );
  25911. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  25912. // vertex
  25913. vertex.x = points[ j ].x * sin;
  25914. vertex.y = points[ j ].y;
  25915. vertex.z = points[ j ].x * cos;
  25916. vertices.push( vertex.x, vertex.y, vertex.z );
  25917. // uv
  25918. uv.x = i / segments;
  25919. uv.y = j / ( points.length - 1 );
  25920. uvs.push( uv.x, uv.y );
  25921. // normal
  25922. const x = initNormals[ 3 * j + 0 ] * sin;
  25923. const y = initNormals[ 3 * j + 1 ];
  25924. const z = initNormals[ 3 * j + 0 ] * cos;
  25925. normals.push( x, y, z );
  25926. }
  25927. }
  25928. // indices
  25929. for ( let i = 0; i < segments; i ++ ) {
  25930. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  25931. const base = j + i * points.length;
  25932. const a = base;
  25933. const b = base + points.length;
  25934. const c = base + points.length + 1;
  25935. const d = base + 1;
  25936. // faces
  25937. indices.push( a, b, d );
  25938. indices.push( c, d, b );
  25939. }
  25940. }
  25941. // build geometry
  25942. this.setIndex( indices );
  25943. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25944. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25945. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25946. }
  25947. copy( source ) {
  25948. super.copy( source );
  25949. this.parameters = Object.assign( {}, source.parameters );
  25950. return this;
  25951. }
  25952. /**
  25953. * Factory method for creating an instance of this class from the given
  25954. * JSON object.
  25955. *
  25956. * @param {Object} data - A JSON object representing the serialized geometry.
  25957. * @return {LatheGeometry} A new instance.
  25958. */
  25959. static fromJSON( data ) {
  25960. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  25961. }
  25962. }
  25963. /**
  25964. * A geometry class for representing an octahedron.
  25965. *
  25966. * ```js
  25967. * const geometry = new THREE.OctahedronGeometry();
  25968. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25969. * const octahedron = new THREE.Mesh( geometry, material );
  25970. * scene.add( octahedron );
  25971. * ```
  25972. *
  25973. * @augments PolyhedronGeometry
  25974. * @demo scenes/geometry-browser.html#OctahedronGeometry
  25975. */
  25976. class OctahedronGeometry extends PolyhedronGeometry {
  25977. /**
  25978. * Constructs a new octahedron geometry.
  25979. *
  25980. * @param {number} [radius=1] - Radius of the octahedron.
  25981. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  25982. */
  25983. constructor( radius = 1, detail = 0 ) {
  25984. const vertices = [
  25985. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  25986. 0, -1, 0, 0, 0, 1, 0, 0, -1
  25987. ];
  25988. const indices = [
  25989. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  25990. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  25991. 1, 3, 4, 1, 4, 2
  25992. ];
  25993. super( vertices, indices, radius, detail );
  25994. this.type = 'OctahedronGeometry';
  25995. /**
  25996. * Holds the constructor parameters that have been
  25997. * used to generate the geometry. Any modification
  25998. * after instantiation does not change the geometry.
  25999. *
  26000. * @type {Object}
  26001. */
  26002. this.parameters = {
  26003. radius: radius,
  26004. detail: detail
  26005. };
  26006. }
  26007. /**
  26008. * Factory method for creating an instance of this class from the given
  26009. * JSON object.
  26010. *
  26011. * @param {Object} data - A JSON object representing the serialized geometry.
  26012. * @return {OctahedronGeometry} A new instance.
  26013. */
  26014. static fromJSON( data ) {
  26015. return new OctahedronGeometry( data.radius, data.detail );
  26016. }
  26017. }
  26018. /**
  26019. * A geometry class for representing a plane.
  26020. *
  26021. * ```js
  26022. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26023. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26024. * const plane = new THREE.Mesh( geometry, material );
  26025. * scene.add( plane );
  26026. * ```
  26027. *
  26028. * @augments BufferGeometry
  26029. * @demo scenes/geometry-browser.html#PlaneGeometry
  26030. */
  26031. class PlaneGeometry extends BufferGeometry {
  26032. /**
  26033. * Constructs a new plane geometry.
  26034. *
  26035. * @param {number} [width=1] - The width along the X axis.
  26036. * @param {number} [height=1] - The height along the Y axis
  26037. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26038. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26039. */
  26040. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26041. super();
  26042. this.type = 'PlaneGeometry';
  26043. /**
  26044. * Holds the constructor parameters that have been
  26045. * used to generate the geometry. Any modification
  26046. * after instantiation does not change the geometry.
  26047. *
  26048. * @type {Object}
  26049. */
  26050. this.parameters = {
  26051. width: width,
  26052. height: height,
  26053. widthSegments: widthSegments,
  26054. heightSegments: heightSegments
  26055. };
  26056. const width_half = width / 2;
  26057. const height_half = height / 2;
  26058. const gridX = Math.floor( widthSegments );
  26059. const gridY = Math.floor( heightSegments );
  26060. const gridX1 = gridX + 1;
  26061. const gridY1 = gridY + 1;
  26062. const segment_width = width / gridX;
  26063. const segment_height = height / gridY;
  26064. //
  26065. const indices = [];
  26066. const vertices = [];
  26067. const normals = [];
  26068. const uvs = [];
  26069. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26070. const y = iy * segment_height - height_half;
  26071. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26072. const x = ix * segment_width - width_half;
  26073. vertices.push( x, - y, 0 );
  26074. normals.push( 0, 0, 1 );
  26075. uvs.push( ix / gridX );
  26076. uvs.push( 1 - ( iy / gridY ) );
  26077. }
  26078. }
  26079. for ( let iy = 0; iy < gridY; iy ++ ) {
  26080. for ( let ix = 0; ix < gridX; ix ++ ) {
  26081. const a = ix + gridX1 * iy;
  26082. const b = ix + gridX1 * ( iy + 1 );
  26083. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26084. const d = ( ix + 1 ) + gridX1 * iy;
  26085. indices.push( a, b, d );
  26086. indices.push( b, c, d );
  26087. }
  26088. }
  26089. this.setIndex( indices );
  26090. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26091. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26092. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26093. }
  26094. copy( source ) {
  26095. super.copy( source );
  26096. this.parameters = Object.assign( {}, source.parameters );
  26097. return this;
  26098. }
  26099. /**
  26100. * Factory method for creating an instance of this class from the given
  26101. * JSON object.
  26102. *
  26103. * @param {Object} data - A JSON object representing the serialized geometry.
  26104. * @return {PlaneGeometry} A new instance.
  26105. */
  26106. static fromJSON( data ) {
  26107. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26108. }
  26109. }
  26110. /**
  26111. * A class for generating a two-dimensional ring geometry.
  26112. *
  26113. * ```js
  26114. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26115. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26116. * const mesh = new THREE.Mesh( geometry, material );
  26117. * scene.add( mesh );
  26118. * ```
  26119. *
  26120. * @augments BufferGeometry
  26121. * @demo scenes/geometry-browser.html#RingGeometry
  26122. */
  26123. class RingGeometry extends BufferGeometry {
  26124. /**
  26125. * Constructs a new ring geometry.
  26126. *
  26127. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26128. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26129. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26130. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26131. * @param {number} [thetaStart=0] - Starting angle in radians.
  26132. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26133. */
  26134. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26135. super();
  26136. this.type = 'RingGeometry';
  26137. /**
  26138. * Holds the constructor parameters that have been
  26139. * used to generate the geometry. Any modification
  26140. * after instantiation does not change the geometry.
  26141. *
  26142. * @type {Object}
  26143. */
  26144. this.parameters = {
  26145. innerRadius: innerRadius,
  26146. outerRadius: outerRadius,
  26147. thetaSegments: thetaSegments,
  26148. phiSegments: phiSegments,
  26149. thetaStart: thetaStart,
  26150. thetaLength: thetaLength
  26151. };
  26152. thetaSegments = Math.max( 3, thetaSegments );
  26153. phiSegments = Math.max( 1, phiSegments );
  26154. // buffers
  26155. const indices = [];
  26156. const vertices = [];
  26157. const normals = [];
  26158. const uvs = [];
  26159. // some helper variables
  26160. let radius = innerRadius;
  26161. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26162. const vertex = new Vector3();
  26163. const uv = new Vector2();
  26164. // generate vertices, normals and uvs
  26165. for ( let j = 0; j <= phiSegments; j ++ ) {
  26166. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26167. // values are generate from the inside of the ring to the outside
  26168. const segment = thetaStart + i / thetaSegments * thetaLength;
  26169. // vertex
  26170. vertex.x = radius * Math.cos( segment );
  26171. vertex.y = radius * Math.sin( segment );
  26172. vertices.push( vertex.x, vertex.y, vertex.z );
  26173. // normal
  26174. normals.push( 0, 0, 1 );
  26175. // uv
  26176. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26177. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26178. uvs.push( uv.x, uv.y );
  26179. }
  26180. // increase the radius for next row of vertices
  26181. radius += radiusStep;
  26182. }
  26183. // indices
  26184. for ( let j = 0; j < phiSegments; j ++ ) {
  26185. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26186. for ( let i = 0; i < thetaSegments; i ++ ) {
  26187. const segment = i + thetaSegmentLevel;
  26188. const a = segment;
  26189. const b = segment + thetaSegments + 1;
  26190. const c = segment + thetaSegments + 2;
  26191. const d = segment + 1;
  26192. // faces
  26193. indices.push( a, b, d );
  26194. indices.push( b, c, d );
  26195. }
  26196. }
  26197. // build geometry
  26198. this.setIndex( indices );
  26199. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26200. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26201. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26202. }
  26203. copy( source ) {
  26204. super.copy( source );
  26205. this.parameters = Object.assign( {}, source.parameters );
  26206. return this;
  26207. }
  26208. /**
  26209. * Factory method for creating an instance of this class from the given
  26210. * JSON object.
  26211. *
  26212. * @param {Object} data - A JSON object representing the serialized geometry.
  26213. * @return {RingGeometry} A new instance.
  26214. */
  26215. static fromJSON( data ) {
  26216. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26217. }
  26218. }
  26219. /**
  26220. * Creates an one-sided polygonal geometry from one or more path shapes.
  26221. *
  26222. * ```js
  26223. * const arcShape = new THREE.Shape()
  26224. * .moveTo( 5, 1 )
  26225. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26226. *
  26227. * const geometry = new THREE.ShapeGeometry( arcShape );
  26228. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26229. * const mesh = new THREE.Mesh( geometry, material ) ;
  26230. * scene.add( mesh );
  26231. * ```
  26232. *
  26233. * @augments BufferGeometry
  26234. * @demo scenes/geometry-browser.html#ShapeGeometry
  26235. */
  26236. class ShapeGeometry extends BufferGeometry {
  26237. /**
  26238. * Constructs a new shape geometry.
  26239. *
  26240. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26241. * @param {number} [curveSegments=12] - Number of segments per shape.
  26242. */
  26243. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26244. super();
  26245. this.type = 'ShapeGeometry';
  26246. /**
  26247. * Holds the constructor parameters that have been
  26248. * used to generate the geometry. Any modification
  26249. * after instantiation does not change the geometry.
  26250. *
  26251. * @type {Object}
  26252. */
  26253. this.parameters = {
  26254. shapes: shapes,
  26255. curveSegments: curveSegments
  26256. };
  26257. // buffers
  26258. const indices = [];
  26259. const vertices = [];
  26260. const normals = [];
  26261. const uvs = [];
  26262. // helper variables
  26263. let groupStart = 0;
  26264. let groupCount = 0;
  26265. // allow single and array values for "shapes" parameter
  26266. if ( Array.isArray( shapes ) === false ) {
  26267. addShape( shapes );
  26268. } else {
  26269. for ( let i = 0; i < shapes.length; i ++ ) {
  26270. addShape( shapes[ i ] );
  26271. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26272. groupStart += groupCount;
  26273. groupCount = 0;
  26274. }
  26275. }
  26276. // build geometry
  26277. this.setIndex( indices );
  26278. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26279. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26280. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26281. // helper functions
  26282. function addShape( shape ) {
  26283. const indexOffset = vertices.length / 3;
  26284. const points = shape.extractPoints( curveSegments );
  26285. let shapeVertices = points.shape;
  26286. const shapeHoles = points.holes;
  26287. // check direction of vertices
  26288. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26289. shapeVertices = shapeVertices.reverse();
  26290. }
  26291. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26292. const shapeHole = shapeHoles[ i ];
  26293. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26294. shapeHoles[ i ] = shapeHole.reverse();
  26295. }
  26296. }
  26297. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26298. // join vertices of inner and outer paths to a single array
  26299. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26300. const shapeHole = shapeHoles[ i ];
  26301. shapeVertices = shapeVertices.concat( shapeHole );
  26302. }
  26303. // vertices, normals, uvs
  26304. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26305. const vertex = shapeVertices[ i ];
  26306. vertices.push( vertex.x, vertex.y, 0 );
  26307. normals.push( 0, 0, 1 );
  26308. uvs.push( vertex.x, vertex.y ); // world uvs
  26309. }
  26310. // indices
  26311. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26312. const face = faces[ i ];
  26313. const a = face[ 0 ] + indexOffset;
  26314. const b = face[ 1 ] + indexOffset;
  26315. const c = face[ 2 ] + indexOffset;
  26316. indices.push( a, b, c );
  26317. groupCount += 3;
  26318. }
  26319. }
  26320. }
  26321. copy( source ) {
  26322. super.copy( source );
  26323. this.parameters = Object.assign( {}, source.parameters );
  26324. return this;
  26325. }
  26326. toJSON() {
  26327. const data = super.toJSON();
  26328. const shapes = this.parameters.shapes;
  26329. return toJSON( shapes, data );
  26330. }
  26331. /**
  26332. * Factory method for creating an instance of this class from the given
  26333. * JSON object.
  26334. *
  26335. * @param {Object} data - A JSON object representing the serialized geometry.
  26336. * @param {Array<Shape>} shapes - An array of shapes.
  26337. * @return {ShapeGeometry} A new instance.
  26338. */
  26339. static fromJSON( data, shapes ) {
  26340. const geometryShapes = [];
  26341. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26342. const shape = shapes[ data.shapes[ j ] ];
  26343. geometryShapes.push( shape );
  26344. }
  26345. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26346. }
  26347. }
  26348. function toJSON( shapes, data ) {
  26349. data.shapes = [];
  26350. if ( Array.isArray( shapes ) ) {
  26351. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26352. const shape = shapes[ i ];
  26353. data.shapes.push( shape.uuid );
  26354. }
  26355. } else {
  26356. data.shapes.push( shapes.uuid );
  26357. }
  26358. return data;
  26359. }
  26360. /**
  26361. * A class for generating a sphere geometry.
  26362. *
  26363. * ```js
  26364. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26365. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26366. * const sphere = new THREE.Mesh( geometry, material );
  26367. * scene.add( sphere );
  26368. * ```
  26369. *
  26370. * @augments BufferGeometry
  26371. * @demo scenes/geometry-browser.html#SphereGeometry
  26372. */
  26373. class SphereGeometry extends BufferGeometry {
  26374. /**
  26375. * Constructs a new sphere geometry.
  26376. *
  26377. * @param {number} [radius=1] - The sphere radius.
  26378. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26379. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26380. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26381. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26382. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26383. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26384. */
  26385. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26386. super();
  26387. this.type = 'SphereGeometry';
  26388. /**
  26389. * Holds the constructor parameters that have been
  26390. * used to generate the geometry. Any modification
  26391. * after instantiation does not change the geometry.
  26392. *
  26393. * @type {Object}
  26394. */
  26395. this.parameters = {
  26396. radius: radius,
  26397. widthSegments: widthSegments,
  26398. heightSegments: heightSegments,
  26399. phiStart: phiStart,
  26400. phiLength: phiLength,
  26401. thetaStart: thetaStart,
  26402. thetaLength: thetaLength
  26403. };
  26404. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26405. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26406. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26407. let index = 0;
  26408. const grid = [];
  26409. const vertex = new Vector3();
  26410. const normal = new Vector3();
  26411. // buffers
  26412. const indices = [];
  26413. const vertices = [];
  26414. const normals = [];
  26415. const uvs = [];
  26416. // generate vertices, normals and uvs
  26417. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26418. const verticesRow = [];
  26419. const v = iy / heightSegments;
  26420. // special case for the poles
  26421. let uOffset = 0;
  26422. if ( iy === 0 && thetaStart === 0 ) {
  26423. uOffset = 0.5 / widthSegments;
  26424. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26425. uOffset = -0.5 / widthSegments;
  26426. }
  26427. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26428. const u = ix / widthSegments;
  26429. // vertex
  26430. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26431. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26432. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26433. vertices.push( vertex.x, vertex.y, vertex.z );
  26434. // normal
  26435. normal.copy( vertex ).normalize();
  26436. normals.push( normal.x, normal.y, normal.z );
  26437. // uv
  26438. uvs.push( u + uOffset, 1 - v );
  26439. verticesRow.push( index ++ );
  26440. }
  26441. grid.push( verticesRow );
  26442. }
  26443. // indices
  26444. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26445. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26446. const a = grid[ iy ][ ix + 1 ];
  26447. const b = grid[ iy ][ ix ];
  26448. const c = grid[ iy + 1 ][ ix ];
  26449. const d = grid[ iy + 1 ][ ix + 1 ];
  26450. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26451. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26452. }
  26453. }
  26454. // build geometry
  26455. this.setIndex( indices );
  26456. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26457. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26458. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26459. }
  26460. copy( source ) {
  26461. super.copy( source );
  26462. this.parameters = Object.assign( {}, source.parameters );
  26463. return this;
  26464. }
  26465. /**
  26466. * Factory method for creating an instance of this class from the given
  26467. * JSON object.
  26468. *
  26469. * @param {Object} data - A JSON object representing the serialized geometry.
  26470. * @return {SphereGeometry} A new instance.
  26471. */
  26472. static fromJSON( data ) {
  26473. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26474. }
  26475. }
  26476. /**
  26477. * A geometry class for representing an tetrahedron.
  26478. *
  26479. * ```js
  26480. * const geometry = new THREE.TetrahedronGeometry();
  26481. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26482. * const tetrahedron = new THREE.Mesh( geometry, material );
  26483. * scene.add( tetrahedron );
  26484. * ```
  26485. *
  26486. * @augments PolyhedronGeometry
  26487. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  26488. */
  26489. class TetrahedronGeometry extends PolyhedronGeometry {
  26490. /**
  26491. * Constructs a new tetrahedron geometry.
  26492. *
  26493. * @param {number} [radius=1] - Radius of the tetrahedron.
  26494. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26495. */
  26496. constructor( radius = 1, detail = 0 ) {
  26497. const vertices = [
  26498. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26499. ];
  26500. const indices = [
  26501. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26502. ];
  26503. super( vertices, indices, radius, detail );
  26504. this.type = 'TetrahedronGeometry';
  26505. /**
  26506. * Holds the constructor parameters that have been
  26507. * used to generate the geometry. Any modification
  26508. * after instantiation does not change the geometry.
  26509. *
  26510. * @type {Object}
  26511. */
  26512. this.parameters = {
  26513. radius: radius,
  26514. detail: detail
  26515. };
  26516. }
  26517. /**
  26518. * Factory method for creating an instance of this class from the given
  26519. * JSON object.
  26520. *
  26521. * @param {Object} data - A JSON object representing the serialized geometry.
  26522. * @return {TetrahedronGeometry} A new instance.
  26523. */
  26524. static fromJSON( data ) {
  26525. return new TetrahedronGeometry( data.radius, data.detail );
  26526. }
  26527. }
  26528. /**
  26529. * A geometry class for representing an torus.
  26530. *
  26531. * ```js
  26532. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26533. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26534. * const torus = new THREE.Mesh( geometry, material );
  26535. * scene.add( torus );
  26536. * ```
  26537. *
  26538. * @augments BufferGeometry
  26539. * @demo scenes/geometry-browser.html#TorusGeometry
  26540. */
  26541. class TorusGeometry extends BufferGeometry {
  26542. /**
  26543. * Constructs a new torus geometry.
  26544. *
  26545. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26546. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26547. * @param {number} [radialSegments=12] - The number of radial segments.
  26548. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26549. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26550. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  26551. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  26552. */
  26553. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26554. super();
  26555. this.type = 'TorusGeometry';
  26556. /**
  26557. * Holds the constructor parameters that have been
  26558. * used to generate the geometry. Any modification
  26559. * after instantiation does not change the geometry.
  26560. *
  26561. * @type {Object}
  26562. */
  26563. this.parameters = {
  26564. radius: radius,
  26565. tube: tube,
  26566. radialSegments: radialSegments,
  26567. tubularSegments: tubularSegments,
  26568. arc: arc,
  26569. thetaStart: thetaStart,
  26570. thetaLength: thetaLength,
  26571. };
  26572. radialSegments = Math.floor( radialSegments );
  26573. tubularSegments = Math.floor( tubularSegments );
  26574. // buffers
  26575. const indices = [];
  26576. const vertices = [];
  26577. const normals = [];
  26578. const uvs = [];
  26579. // helper variables
  26580. const center = new Vector3();
  26581. const vertex = new Vector3();
  26582. const normal = new Vector3();
  26583. // generate vertices, normals and uvs
  26584. for ( let j = 0; j <= radialSegments; j ++ ) {
  26585. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  26586. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26587. const u = i / tubularSegments * arc;
  26588. // vertex
  26589. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26590. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26591. vertex.z = tube * Math.sin( v );
  26592. vertices.push( vertex.x, vertex.y, vertex.z );
  26593. // normal
  26594. center.x = radius * Math.cos( u );
  26595. center.y = radius * Math.sin( u );
  26596. normal.subVectors( vertex, center ).normalize();
  26597. normals.push( normal.x, normal.y, normal.z );
  26598. // uv
  26599. uvs.push( i / tubularSegments );
  26600. uvs.push( j / radialSegments );
  26601. }
  26602. }
  26603. // generate indices
  26604. for ( let j = 1; j <= radialSegments; j ++ ) {
  26605. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26606. // indices
  26607. const a = ( tubularSegments + 1 ) * j + i - 1;
  26608. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26609. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26610. const d = ( tubularSegments + 1 ) * j + i;
  26611. // faces
  26612. indices.push( a, b, d );
  26613. indices.push( b, c, d );
  26614. }
  26615. }
  26616. // build geometry
  26617. this.setIndex( indices );
  26618. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26619. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26620. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26621. }
  26622. copy( source ) {
  26623. super.copy( source );
  26624. this.parameters = Object.assign( {}, source.parameters );
  26625. return this;
  26626. }
  26627. /**
  26628. * Factory method for creating an instance of this class from the given
  26629. * JSON object.
  26630. *
  26631. * @param {Object} data - A JSON object representing the serialized geometry.
  26632. * @return {TorusGeometry} A new instance.
  26633. */
  26634. static fromJSON( data ) {
  26635. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26636. }
  26637. }
  26638. /**
  26639. * Creates a torus knot, the particular shape of which is defined by a pair
  26640. * of coprime integers, p and q. If p and q are not coprime, the result will
  26641. * be a torus link.
  26642. *
  26643. * ```js
  26644. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26645. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26646. * const torusKnot = new THREE.Mesh( geometry, material );
  26647. * scene.add( torusKnot );
  26648. * ```
  26649. *
  26650. * @augments BufferGeometry
  26651. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  26652. */
  26653. class TorusKnotGeometry extends BufferGeometry {
  26654. /**
  26655. * Constructs a new torus knot geometry.
  26656. *
  26657. * @param {number} [radius=1] - Radius of the torus knot.
  26658. * @param {number} [tube=0.4] - Radius of the tube.
  26659. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26660. * @param {number} [radialSegments=8] - The number of radial segments.
  26661. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26662. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26663. */
  26664. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26665. super();
  26666. this.type = 'TorusKnotGeometry';
  26667. /**
  26668. * Holds the constructor parameters that have been
  26669. * used to generate the geometry. Any modification
  26670. * after instantiation does not change the geometry.
  26671. *
  26672. * @type {Object}
  26673. */
  26674. this.parameters = {
  26675. radius: radius,
  26676. tube: tube,
  26677. tubularSegments: tubularSegments,
  26678. radialSegments: radialSegments,
  26679. p: p,
  26680. q: q
  26681. };
  26682. tubularSegments = Math.floor( tubularSegments );
  26683. radialSegments = Math.floor( radialSegments );
  26684. // buffers
  26685. const indices = [];
  26686. const vertices = [];
  26687. const normals = [];
  26688. const uvs = [];
  26689. // helper variables
  26690. const vertex = new Vector3();
  26691. const normal = new Vector3();
  26692. const P1 = new Vector3();
  26693. const P2 = new Vector3();
  26694. const B = new Vector3();
  26695. const T = new Vector3();
  26696. const N = new Vector3();
  26697. // generate vertices, normals and uvs
  26698. for ( let i = 0; i <= tubularSegments; ++ i ) {
  26699. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  26700. const u = i / tubularSegments * p * Math.PI * 2;
  26701. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  26702. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26703. calculatePositionOnCurve( u, p, q, radius, P1 );
  26704. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  26705. // calculate orthonormal basis
  26706. T.subVectors( P2, P1 );
  26707. N.addVectors( P2, P1 );
  26708. B.crossVectors( T, N );
  26709. N.crossVectors( B, T );
  26710. // normalize B, N. T can be ignored, we don't use it
  26711. B.normalize();
  26712. N.normalize();
  26713. for ( let j = 0; j <= radialSegments; ++ j ) {
  26714. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26715. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26716. const v = j / radialSegments * Math.PI * 2;
  26717. const cx = - tube * Math.cos( v );
  26718. const cy = tube * Math.sin( v );
  26719. // now calculate the final vertex position.
  26720. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  26721. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  26722. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  26723. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  26724. vertices.push( vertex.x, vertex.y, vertex.z );
  26725. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  26726. normal.subVectors( vertex, P1 ).normalize();
  26727. normals.push( normal.x, normal.y, normal.z );
  26728. // uv
  26729. uvs.push( i / tubularSegments );
  26730. uvs.push( j / radialSegments );
  26731. }
  26732. }
  26733. // generate indices
  26734. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26735. for ( let i = 1; i <= radialSegments; i ++ ) {
  26736. // indices
  26737. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26738. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26739. const c = ( radialSegments + 1 ) * j + i;
  26740. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26741. // faces
  26742. indices.push( a, b, d );
  26743. indices.push( b, c, d );
  26744. }
  26745. }
  26746. // build geometry
  26747. this.setIndex( indices );
  26748. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26749. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26750. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26751. // this function calculates the current position on the torus curve
  26752. function calculatePositionOnCurve( u, p, q, radius, position ) {
  26753. const cu = Math.cos( u );
  26754. const su = Math.sin( u );
  26755. const quOverP = q / p * u;
  26756. const cs = Math.cos( quOverP );
  26757. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  26758. position.y = radius * ( 2 + cs ) * su * 0.5;
  26759. position.z = radius * Math.sin( quOverP ) * 0.5;
  26760. }
  26761. }
  26762. copy( source ) {
  26763. super.copy( source );
  26764. this.parameters = Object.assign( {}, source.parameters );
  26765. return this;
  26766. }
  26767. /**
  26768. * Factory method for creating an instance of this class from the given
  26769. * JSON object.
  26770. *
  26771. * @param {Object} data - A JSON object representing the serialized geometry.
  26772. * @return {TorusKnotGeometry} A new instance.
  26773. */
  26774. static fromJSON( data ) {
  26775. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  26776. }
  26777. }
  26778. /**
  26779. * Creates a tube that extrudes along a 3D curve.
  26780. *
  26781. * ```js
  26782. * class CustomSinCurve extends THREE.Curve {
  26783. *
  26784. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  26785. *
  26786. * const tx = t * 3 - 1.5;
  26787. * const ty = Math.sin( 2 * Math.PI * t );
  26788. * const tz = 0;
  26789. *
  26790. * return optionalTarget.set( tx, ty, tz );
  26791. * }
  26792. *
  26793. * }
  26794. *
  26795. * const path = new CustomSinCurve( 10 );
  26796. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  26797. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26798. * const mesh = new THREE.Mesh( geometry, material );
  26799. * scene.add( mesh );
  26800. * ```
  26801. *
  26802. * @augments BufferGeometry
  26803. * @demo scenes/geometry-browser.html#TubeGeometry
  26804. */
  26805. class TubeGeometry extends BufferGeometry {
  26806. /**
  26807. * Constructs a new tube geometry.
  26808. *
  26809. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  26810. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  26811. * @param {number} [radius=1] -The radius of the tube.
  26812. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  26813. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  26814. */
  26815. 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 ) {
  26816. super();
  26817. this.type = 'TubeGeometry';
  26818. /**
  26819. * Holds the constructor parameters that have been
  26820. * used to generate the geometry. Any modification
  26821. * after instantiation does not change the geometry.
  26822. *
  26823. * @type {Object}
  26824. */
  26825. this.parameters = {
  26826. path: path,
  26827. tubularSegments: tubularSegments,
  26828. radius: radius,
  26829. radialSegments: radialSegments,
  26830. closed: closed
  26831. };
  26832. const frames = path.computeFrenetFrames( tubularSegments, closed );
  26833. // expose internals
  26834. this.tangents = frames.tangents;
  26835. this.normals = frames.normals;
  26836. this.binormals = frames.binormals;
  26837. // helper variables
  26838. const vertex = new Vector3();
  26839. const normal = new Vector3();
  26840. const uv = new Vector2();
  26841. let P = new Vector3();
  26842. // buffer
  26843. const vertices = [];
  26844. const normals = [];
  26845. const uvs = [];
  26846. const indices = [];
  26847. // create buffer data
  26848. generateBufferData();
  26849. // build geometry
  26850. this.setIndex( indices );
  26851. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26852. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26853. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26854. // functions
  26855. function generateBufferData() {
  26856. for ( let i = 0; i < tubularSegments; i ++ ) {
  26857. generateSegment( i );
  26858. }
  26859. // if the geometry is not closed, generate the last row of vertices and normals
  26860. // at the regular position on the given path
  26861. //
  26862. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  26863. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  26864. // uvs are generated in a separate function.
  26865. // this makes it easy compute correct values for closed geometries
  26866. generateUVs();
  26867. // finally create faces
  26868. generateIndices();
  26869. }
  26870. function generateSegment( i ) {
  26871. // we use getPointAt to sample evenly distributed points from the given path
  26872. P = path.getPointAt( i / tubularSegments, P );
  26873. // retrieve corresponding normal and binormal
  26874. const N = frames.normals[ i ];
  26875. const B = frames.binormals[ i ];
  26876. // generate normals and vertices for the current segment
  26877. for ( let j = 0; j <= radialSegments; j ++ ) {
  26878. const v = j / radialSegments * Math.PI * 2;
  26879. const sin = Math.sin( v );
  26880. const cos = - Math.cos( v );
  26881. // normal
  26882. normal.x = ( cos * N.x + sin * B.x );
  26883. normal.y = ( cos * N.y + sin * B.y );
  26884. normal.z = ( cos * N.z + sin * B.z );
  26885. normal.normalize();
  26886. normals.push( normal.x, normal.y, normal.z );
  26887. // vertex
  26888. vertex.x = P.x + radius * normal.x;
  26889. vertex.y = P.y + radius * normal.y;
  26890. vertex.z = P.z + radius * normal.z;
  26891. vertices.push( vertex.x, vertex.y, vertex.z );
  26892. }
  26893. }
  26894. function generateIndices() {
  26895. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26896. for ( let i = 1; i <= radialSegments; i ++ ) {
  26897. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26898. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26899. const c = ( radialSegments + 1 ) * j + i;
  26900. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26901. // faces
  26902. indices.push( a, b, d );
  26903. indices.push( b, c, d );
  26904. }
  26905. }
  26906. }
  26907. function generateUVs() {
  26908. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26909. for ( let j = 0; j <= radialSegments; j ++ ) {
  26910. uv.x = i / tubularSegments;
  26911. uv.y = j / radialSegments;
  26912. uvs.push( uv.x, uv.y );
  26913. }
  26914. }
  26915. }
  26916. }
  26917. copy( source ) {
  26918. super.copy( source );
  26919. this.parameters = Object.assign( {}, source.parameters );
  26920. return this;
  26921. }
  26922. toJSON() {
  26923. const data = super.toJSON();
  26924. data.path = this.parameters.path.toJSON();
  26925. return data;
  26926. }
  26927. /**
  26928. * Factory method for creating an instance of this class from the given
  26929. * JSON object.
  26930. *
  26931. * @param {Object} data - A JSON object representing the serialized geometry.
  26932. * @return {TubeGeometry} A new instance.
  26933. */
  26934. static fromJSON( data ) {
  26935. // This only works for built-in curves (e.g. CatmullRomCurve3).
  26936. // User defined curves or instances of CurvePath will not be deserialized.
  26937. return new TubeGeometry(
  26938. new Curves[ data.path.type ]().fromJSON( data.path ),
  26939. data.tubularSegments,
  26940. data.radius,
  26941. data.radialSegments,
  26942. data.closed
  26943. );
  26944. }
  26945. }
  26946. /**
  26947. * Can be used as a helper object to visualize a geometry as a wireframe.
  26948. *
  26949. * ```js
  26950. * const geometry = new THREE.SphereGeometry();
  26951. *
  26952. * const wireframe = new THREE.WireframeGeometry( geometry );
  26953. *
  26954. * const line = new THREE.LineSegments( wireframe );
  26955. * line.material.depthWrite = false;
  26956. * line.material.opacity = 0.25;
  26957. * line.material.transparent = true;
  26958. *
  26959. * scene.add( line );
  26960. * ```
  26961. *
  26962. * Note: It is not yet possible to serialize/deserialize instances of this class.
  26963. *
  26964. * @augments BufferGeometry
  26965. */
  26966. class WireframeGeometry extends BufferGeometry {
  26967. /**
  26968. * Constructs a new wireframe geometry.
  26969. *
  26970. * @param {?BufferGeometry} [geometry=null] - The geometry.
  26971. */
  26972. constructor( geometry = null ) {
  26973. super();
  26974. this.type = 'WireframeGeometry';
  26975. /**
  26976. * Holds the constructor parameters that have been
  26977. * used to generate the geometry. Any modification
  26978. * after instantiation does not change the geometry.
  26979. *
  26980. * @type {Object}
  26981. */
  26982. this.parameters = {
  26983. geometry: geometry
  26984. };
  26985. if ( geometry !== null ) {
  26986. // buffer
  26987. const vertices = [];
  26988. const edges = new Set();
  26989. // helper variables
  26990. const start = new Vector3();
  26991. const end = new Vector3();
  26992. if ( geometry.index !== null ) {
  26993. // indexed BufferGeometry
  26994. const position = geometry.attributes.position;
  26995. const indices = geometry.index;
  26996. let groups = geometry.groups;
  26997. if ( groups.length === 0 ) {
  26998. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  26999. }
  27000. // create a data structure that contains all edges without duplicates
  27001. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27002. const group = groups[ o ];
  27003. const groupStart = group.start;
  27004. const groupCount = group.count;
  27005. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27006. for ( let j = 0; j < 3; j ++ ) {
  27007. const index1 = indices.getX( i + j );
  27008. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27009. start.fromBufferAttribute( position, index1 );
  27010. end.fromBufferAttribute( position, index2 );
  27011. if ( isUniqueEdge( start, end, edges ) === true ) {
  27012. vertices.push( start.x, start.y, start.z );
  27013. vertices.push( end.x, end.y, end.z );
  27014. }
  27015. }
  27016. }
  27017. }
  27018. } else {
  27019. // non-indexed BufferGeometry
  27020. const position = geometry.attributes.position;
  27021. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27022. for ( let j = 0; j < 3; j ++ ) {
  27023. // three edges per triangle, an edge is represented as (index1, index2)
  27024. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27025. const index1 = 3 * i + j;
  27026. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27027. start.fromBufferAttribute( position, index1 );
  27028. end.fromBufferAttribute( position, index2 );
  27029. if ( isUniqueEdge( start, end, edges ) === true ) {
  27030. vertices.push( start.x, start.y, start.z );
  27031. vertices.push( end.x, end.y, end.z );
  27032. }
  27033. }
  27034. }
  27035. }
  27036. // build geometry
  27037. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27038. }
  27039. }
  27040. copy( source ) {
  27041. super.copy( source );
  27042. this.parameters = Object.assign( {}, source.parameters );
  27043. return this;
  27044. }
  27045. }
  27046. function isUniqueEdge( start, end, edges ) {
  27047. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27048. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27049. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27050. return false;
  27051. } else {
  27052. edges.add( hash1 );
  27053. edges.add( hash2 );
  27054. return true;
  27055. }
  27056. }
  27057. var Geometries = /*#__PURE__*/Object.freeze({
  27058. __proto__: null,
  27059. BoxGeometry: BoxGeometry,
  27060. CapsuleGeometry: CapsuleGeometry,
  27061. CircleGeometry: CircleGeometry,
  27062. ConeGeometry: ConeGeometry,
  27063. CylinderGeometry: CylinderGeometry,
  27064. DodecahedronGeometry: DodecahedronGeometry,
  27065. EdgesGeometry: EdgesGeometry,
  27066. ExtrudeGeometry: ExtrudeGeometry,
  27067. IcosahedronGeometry: IcosahedronGeometry,
  27068. LatheGeometry: LatheGeometry,
  27069. OctahedronGeometry: OctahedronGeometry,
  27070. PlaneGeometry: PlaneGeometry,
  27071. PolyhedronGeometry: PolyhedronGeometry,
  27072. RingGeometry: RingGeometry,
  27073. ShapeGeometry: ShapeGeometry,
  27074. SphereGeometry: SphereGeometry,
  27075. TetrahedronGeometry: TetrahedronGeometry,
  27076. TorusGeometry: TorusGeometry,
  27077. TorusKnotGeometry: TorusKnotGeometry,
  27078. TubeGeometry: TubeGeometry,
  27079. WireframeGeometry: WireframeGeometry
  27080. });
  27081. /**
  27082. * This material can receive shadows, but otherwise is completely transparent.
  27083. *
  27084. * ```js
  27085. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27086. * geometry.rotateX( - Math.PI / 2 );
  27087. *
  27088. * const material = new THREE.ShadowMaterial();
  27089. * material.opacity = 0.2;
  27090. *
  27091. * const plane = new THREE.Mesh( geometry, material );
  27092. * plane.position.y = -200;
  27093. * plane.receiveShadow = true;
  27094. * scene.add( plane );
  27095. * ```
  27096. *
  27097. * @augments Material
  27098. */
  27099. class ShadowMaterial extends Material {
  27100. /**
  27101. * Constructs a new shadow material.
  27102. *
  27103. * @param {Object} [parameters] - An object with one or more properties
  27104. * defining the material's appearance. Any property of the material
  27105. * (including any property from inherited materials) can be passed
  27106. * in here. Color values can be passed any type of value accepted
  27107. * by {@link Color#set}.
  27108. */
  27109. constructor( parameters ) {
  27110. super();
  27111. /**
  27112. * This flag can be used for type testing.
  27113. *
  27114. * @type {boolean}
  27115. * @readonly
  27116. * @default true
  27117. */
  27118. this.isShadowMaterial = true;
  27119. this.type = 'ShadowMaterial';
  27120. /**
  27121. * Color of the material.
  27122. *
  27123. * @type {Color}
  27124. * @default (0,0,0)
  27125. */
  27126. this.color = new Color( 0x000000 );
  27127. /**
  27128. * Overwritten since shadow materials are transparent
  27129. * by default.
  27130. *
  27131. * @type {boolean}
  27132. * @default true
  27133. */
  27134. this.transparent = true;
  27135. /**
  27136. * Whether the material is affected by fog or not.
  27137. *
  27138. * @type {boolean}
  27139. * @default true
  27140. */
  27141. this.fog = true;
  27142. this.setValues( parameters );
  27143. }
  27144. copy( source ) {
  27145. super.copy( source );
  27146. this.color.copy( source.color );
  27147. this.fog = source.fog;
  27148. return this;
  27149. }
  27150. }
  27151. /**
  27152. * Provides utility functions for managing uniforms.
  27153. *
  27154. * @module UniformsUtils
  27155. */
  27156. /**
  27157. * Clones the given uniform definitions by performing a deep-copy. That means
  27158. * if the value of a uniform refers to an object like a Vector3 or Texture,
  27159. * the cloned uniform will refer to a new object reference.
  27160. *
  27161. * @param {Object} src - An object representing uniform definitions.
  27162. * @return {Object} The cloned uniforms.
  27163. */
  27164. function cloneUniforms( src ) {
  27165. const dst = {};
  27166. for ( const u in src ) {
  27167. dst[ u ] = {};
  27168. for ( const p in src[ u ] ) {
  27169. const property = src[ u ][ p ];
  27170. if ( isThreeObject( property ) ) {
  27171. if ( property.isRenderTargetTexture ) {
  27172. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  27173. dst[ u ][ p ] = null;
  27174. } else {
  27175. dst[ u ][ p ] = property.clone();
  27176. }
  27177. } else if ( Array.isArray( property ) ) {
  27178. if ( isThreeObject( property[ 0 ] ) ) {
  27179. const clonedProperty = [];
  27180. for ( let i = 0, l = property.length; i < l; i ++ ) {
  27181. clonedProperty[ i ] = property[ i ].clone();
  27182. }
  27183. dst[ u ][ p ] = clonedProperty;
  27184. } else {
  27185. dst[ u ][ p ] = property.slice();
  27186. }
  27187. } else {
  27188. dst[ u ][ p ] = property;
  27189. }
  27190. }
  27191. }
  27192. return dst;
  27193. }
  27194. /**
  27195. * Merges the given uniform definitions into a single object. Since the
  27196. * method internally uses cloneUniforms(), it performs a deep-copy when
  27197. * producing the merged uniform definitions.
  27198. *
  27199. * @param {Array} uniforms - An array of objects containing uniform definitions.
  27200. * @return {Object} The merged uniforms.
  27201. */
  27202. function mergeUniforms( uniforms ) {
  27203. const merged = {};
  27204. for ( let u = 0; u < uniforms.length; u ++ ) {
  27205. const tmp = cloneUniforms( uniforms[ u ] );
  27206. for ( const p in tmp ) {
  27207. merged[ p ] = tmp[ p ];
  27208. }
  27209. }
  27210. return merged;
  27211. }
  27212. function isThreeObject( property ) {
  27213. return ( property && ( property.isColor ||
  27214. property.isMatrix3 || property.isMatrix4 ||
  27215. property.isVector2 || property.isVector3 || property.isVector4 ||
  27216. property.isTexture || property.isQuaternion ) );
  27217. }
  27218. function cloneUniformsGroups( src ) {
  27219. const dst = [];
  27220. for ( let u = 0; u < src.length; u ++ ) {
  27221. dst.push( src[ u ].clone() );
  27222. }
  27223. return dst;
  27224. }
  27225. function getUnlitUniformColorSpace( renderer ) {
  27226. const currentRenderTarget = renderer.getRenderTarget();
  27227. if ( currentRenderTarget === null ) {
  27228. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  27229. return renderer.outputColorSpace;
  27230. }
  27231. // https://github.com/mrdoob/three.js/issues/27868
  27232. if ( currentRenderTarget.isXRRenderTarget === true ) {
  27233. return currentRenderTarget.texture.colorSpace;
  27234. }
  27235. return ColorManagement.workingColorSpace;
  27236. }
  27237. // Legacy
  27238. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  27239. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  27240. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  27241. /**
  27242. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  27243. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  27244. * effect not included with any of the built-in materials.
  27245. *
  27246. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  27247. *
  27248. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  27249. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  27250. * you don't want that, use {@link RawShaderMaterial} instead.
  27251. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  27252. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  27253. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  27254. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  27255. * - The loop variable has to be *i*.
  27256. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  27257. * value of *i* for the given iteration and can be used in preprocessor
  27258. * statements.
  27259. *
  27260. * ```js
  27261. * const material = new THREE.ShaderMaterial( {
  27262. * uniforms: {
  27263. * time: { value: 1.0 },
  27264. * resolution: { value: new THREE.Vector2() }
  27265. * },
  27266. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  27267. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  27268. * } );
  27269. * ```
  27270. *
  27271. * @augments Material
  27272. */
  27273. class ShaderMaterial extends Material {
  27274. /**
  27275. * Constructs a new shader material.
  27276. *
  27277. * @param {Object} [parameters] - An object with one or more properties
  27278. * defining the material's appearance. Any property of the material
  27279. * (including any property from inherited materials) can be passed
  27280. * in here. Color values can be passed any type of value accepted
  27281. * by {@link Color#set}.
  27282. */
  27283. constructor( parameters ) {
  27284. super();
  27285. /**
  27286. * This flag can be used for type testing.
  27287. *
  27288. * @type {boolean}
  27289. * @readonly
  27290. * @default true
  27291. */
  27292. this.isShaderMaterial = true;
  27293. this.type = 'ShaderMaterial';
  27294. /**
  27295. * Defines custom constants using `#define` directives within the GLSL code
  27296. * for both the vertex shader and the fragment shader; each key/value pair
  27297. * yields another directive.
  27298. * ```js
  27299. * defines: {
  27300. * FOO: 15,
  27301. * BAR: true
  27302. * }
  27303. * ```
  27304. * Yields the lines:
  27305. * ```
  27306. * #define FOO 15
  27307. * #define BAR true
  27308. * ```
  27309. *
  27310. * @type {Object}
  27311. */
  27312. this.defines = {};
  27313. /**
  27314. * An object of the form:
  27315. * ```js
  27316. * {
  27317. * "uniform1": { value: 1.0 },
  27318. * "uniform2": { value: 2 }
  27319. * }
  27320. * ```
  27321. * specifying the uniforms to be passed to the shader code; keys are uniform
  27322. * names, values are definitions of the form
  27323. * ```
  27324. * {
  27325. * value: 1.0
  27326. * }
  27327. * ```
  27328. * where `value` is the value of the uniform. Names must match the name of
  27329. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  27330. * on every frame, so updating the value of the uniform will immediately
  27331. * update the value available to the GLSL code.
  27332. *
  27333. * @type {Object}
  27334. */
  27335. this.uniforms = {};
  27336. /**
  27337. * An array holding uniforms groups for configuring UBOs.
  27338. *
  27339. * @type {Array<UniformsGroup>}
  27340. */
  27341. this.uniformsGroups = [];
  27342. /**
  27343. * Vertex shader GLSL code. This is the actual code for the shader.
  27344. *
  27345. * @type {string}
  27346. */
  27347. this.vertexShader = default_vertex;
  27348. /**
  27349. * Fragment shader GLSL code. This is the actual code for the shader.
  27350. *
  27351. * @type {string}
  27352. */
  27353. this.fragmentShader = default_fragment;
  27354. /**
  27355. * Controls line thickness or lines.
  27356. *
  27357. * WebGL and WebGPU ignore this setting and always render line primitives with a
  27358. * width of one pixel.
  27359. *
  27360. * @type {number}
  27361. * @default 1
  27362. */
  27363. this.linewidth = 1;
  27364. /**
  27365. * Renders the geometry as a wireframe.
  27366. *
  27367. * @type {boolean}
  27368. * @default false
  27369. */
  27370. this.wireframe = false;
  27371. /**
  27372. * Controls the thickness of the wireframe.
  27373. *
  27374. * WebGL and WebGPU ignore this property and always render
  27375. * 1 pixel wide lines.
  27376. *
  27377. * @type {number}
  27378. * @default 1
  27379. */
  27380. this.wireframeLinewidth = 1;
  27381. /**
  27382. * Defines whether the material color is affected by global fog settings; `true`
  27383. * to pass fog uniforms to the shader.
  27384. *
  27385. * Setting this property to `true` requires the definition of fog uniforms. It is
  27386. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  27387. * with predefined fog uniforms.
  27388. *
  27389. * ```js
  27390. * const material = new ShaderMaterial( {
  27391. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  27392. * vertexShader: vertexShader,
  27393. * fragmentShader: fragmentShader,
  27394. * fog: true
  27395. * } );
  27396. * ```
  27397. *
  27398. * @type {boolean}
  27399. * @default false
  27400. */
  27401. this.fog = false;
  27402. /**
  27403. * Defines whether this material uses lighting; `true` to pass uniform data
  27404. * related to lighting to this shader.
  27405. *
  27406. * @type {boolean}
  27407. * @default false
  27408. */
  27409. this.lights = false;
  27410. /**
  27411. * Defines whether this material supports clipping; `true` to let the renderer
  27412. * pass the clippingPlanes uniform.
  27413. *
  27414. * @type {boolean}
  27415. * @default false
  27416. */
  27417. this.clipping = false;
  27418. /**
  27419. * Overwritten and set to `true` by default.
  27420. *
  27421. * @type {boolean}
  27422. * @default true
  27423. */
  27424. this.forceSinglePass = true;
  27425. /**
  27426. * This object allows to enable certain WebGL 2 extensions.
  27427. *
  27428. * - clipCullDistance: set to `true` to use vertex shader clipping
  27429. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  27430. *
  27431. * @type {{clipCullDistance:false,multiDraw:false}}
  27432. */
  27433. this.extensions = {
  27434. clipCullDistance: false, // set to use vertex shader clipping
  27435. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  27436. };
  27437. /**
  27438. * When the rendered geometry doesn't include these attributes but the
  27439. * material does, these default values will be passed to the shaders. This
  27440. * avoids errors when buffer data is missing.
  27441. *
  27442. * - color: [ 1, 1, 1 ]
  27443. * - uv: [ 0, 0 ]
  27444. * - uv1: [ 0, 0 ]
  27445. *
  27446. * @type {Object}
  27447. */
  27448. this.defaultAttributeValues = {
  27449. 'color': [ 1, 1, 1 ],
  27450. 'uv': [ 0, 0 ],
  27451. 'uv1': [ 0, 0 ]
  27452. };
  27453. /**
  27454. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  27455. * to bind a generic vertex index to an attribute variable.
  27456. *
  27457. * @type {string|undefined}
  27458. * @default undefined
  27459. */
  27460. this.index0AttributeName = undefined;
  27461. /**
  27462. * Can be used to force a uniform update while changing uniforms in
  27463. * {@link Object3D#onBeforeRender}.
  27464. *
  27465. * @type {boolean}
  27466. * @default false
  27467. */
  27468. this.uniformsNeedUpdate = false;
  27469. /**
  27470. * Defines the GLSL version of custom shader code.
  27471. *
  27472. * @type {?(GLSL1|GLSL3)}
  27473. * @default null
  27474. */
  27475. this.glslVersion = null;
  27476. if ( parameters !== undefined ) {
  27477. this.setValues( parameters );
  27478. }
  27479. }
  27480. copy( source ) {
  27481. super.copy( source );
  27482. this.fragmentShader = source.fragmentShader;
  27483. this.vertexShader = source.vertexShader;
  27484. this.uniforms = cloneUniforms( source.uniforms );
  27485. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  27486. this.defines = Object.assign( {}, source.defines );
  27487. this.wireframe = source.wireframe;
  27488. this.wireframeLinewidth = source.wireframeLinewidth;
  27489. this.fog = source.fog;
  27490. this.lights = source.lights;
  27491. this.clipping = source.clipping;
  27492. this.extensions = Object.assign( {}, source.extensions );
  27493. this.glslVersion = source.glslVersion;
  27494. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  27495. this.index0AttributeName = source.index0AttributeName;
  27496. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  27497. return this;
  27498. }
  27499. toJSON( meta ) {
  27500. const data = super.toJSON( meta );
  27501. data.glslVersion = this.glslVersion;
  27502. data.uniforms = {};
  27503. for ( const name in this.uniforms ) {
  27504. const uniform = this.uniforms[ name ];
  27505. const value = uniform.value;
  27506. if ( value && value.isTexture ) {
  27507. data.uniforms[ name ] = {
  27508. type: 't',
  27509. value: value.toJSON( meta ).uuid
  27510. };
  27511. } else if ( value && value.isColor ) {
  27512. data.uniforms[ name ] = {
  27513. type: 'c',
  27514. value: value.getHex()
  27515. };
  27516. } else if ( value && value.isVector2 ) {
  27517. data.uniforms[ name ] = {
  27518. type: 'v2',
  27519. value: value.toArray()
  27520. };
  27521. } else if ( value && value.isVector3 ) {
  27522. data.uniforms[ name ] = {
  27523. type: 'v3',
  27524. value: value.toArray()
  27525. };
  27526. } else if ( value && value.isVector4 ) {
  27527. data.uniforms[ name ] = {
  27528. type: 'v4',
  27529. value: value.toArray()
  27530. };
  27531. } else if ( value && value.isMatrix3 ) {
  27532. data.uniforms[ name ] = {
  27533. type: 'm3',
  27534. value: value.toArray()
  27535. };
  27536. } else if ( value && value.isMatrix4 ) {
  27537. data.uniforms[ name ] = {
  27538. type: 'm4',
  27539. value: value.toArray()
  27540. };
  27541. } else {
  27542. data.uniforms[ name ] = {
  27543. value: value
  27544. };
  27545. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  27546. }
  27547. }
  27548. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  27549. data.vertexShader = this.vertexShader;
  27550. data.fragmentShader = this.fragmentShader;
  27551. data.lights = this.lights;
  27552. data.clipping = this.clipping;
  27553. const extensions = {};
  27554. for ( const key in this.extensions ) {
  27555. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  27556. }
  27557. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  27558. return data;
  27559. }
  27560. }
  27561. /**
  27562. * This class works just like {@link ShaderMaterial}, except that definitions
  27563. * of built-in uniforms and attributes are not automatically prepended to the
  27564. * GLSL shader code.
  27565. *
  27566. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27567. *
  27568. * @augments ShaderMaterial
  27569. */
  27570. class RawShaderMaterial extends ShaderMaterial {
  27571. /**
  27572. * Constructs a new raw shader material.
  27573. *
  27574. * @param {Object} [parameters] - An object with one or more properties
  27575. * defining the material's appearance. Any property of the material
  27576. * (including any property from inherited materials) can be passed
  27577. * in here. Color values can be passed any type of value accepted
  27578. * by {@link Color#set}.
  27579. */
  27580. constructor( parameters ) {
  27581. super( parameters );
  27582. /**
  27583. * This flag can be used for type testing.
  27584. *
  27585. * @type {boolean}
  27586. * @readonly
  27587. * @default true
  27588. */
  27589. this.isRawShaderMaterial = true;
  27590. this.type = 'RawShaderMaterial';
  27591. }
  27592. }
  27593. /**
  27594. * A standard physically based material, using Metallic-Roughness workflow.
  27595. *
  27596. * Physically based rendering (PBR) has recently become the standard in many
  27597. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27598. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27599. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27600. *
  27601. * This approach differs from older approaches in that instead of using
  27602. * approximations for the way in which light interacts with a surface, a
  27603. * physically correct model is used. The idea is that, instead of tweaking
  27604. * materials to look good under specific lighting, a material can be created
  27605. * that will react 'correctly' under all lighting scenarios.
  27606. *
  27607. * In practice this gives a more accurate and realistic looking result than
  27608. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27609. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27610. * shading.
  27611. *
  27612. * Note that for best results you should always specify an environment map when using this material.
  27613. *
  27614. * For a non-technical introduction to the concept of PBR and how to set up a
  27615. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27616. *
  27617. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27618. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27619. *
  27620. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27621. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27622. * (pdf), by Brent Burley.
  27623. *
  27624. * @augments Material
  27625. * @demo scenes/material-browser.html#MeshStandardMaterial
  27626. */
  27627. class MeshStandardMaterial extends Material {
  27628. /**
  27629. * Constructs a new mesh standard material.
  27630. *
  27631. * @param {Object} [parameters] - An object with one or more properties
  27632. * defining the material's appearance. Any property of the material
  27633. * (including any property from inherited materials) can be passed
  27634. * in here. Color values can be passed any type of value accepted
  27635. * by {@link Color#set}.
  27636. */
  27637. constructor( parameters ) {
  27638. super();
  27639. /**
  27640. * This flag can be used for type testing.
  27641. *
  27642. * @type {boolean}
  27643. * @readonly
  27644. * @default true
  27645. */
  27646. this.isMeshStandardMaterial = true;
  27647. this.type = 'MeshStandardMaterial';
  27648. this.defines = { 'STANDARD': '' };
  27649. /**
  27650. * Color of the material.
  27651. *
  27652. * @type {Color}
  27653. * @default (1,1,1)
  27654. */
  27655. this.color = new Color( 0xffffff ); // diffuse
  27656. /**
  27657. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27658. * means fully diffuse. If `roughnessMap` is also provided,
  27659. * both values are multiplied.
  27660. *
  27661. * @type {number}
  27662. * @default 1
  27663. */
  27664. this.roughness = 1.0;
  27665. /**
  27666. * How much the material is like a metal. Non-metallic materials such as wood
  27667. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27668. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27669. * If `metalnessMap` is also provided, both values are multiplied.
  27670. *
  27671. * @type {number}
  27672. * @default 0
  27673. */
  27674. this.metalness = 0.0;
  27675. /**
  27676. * The color map. May optionally include an alpha channel, typically combined
  27677. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27678. * color is modulated by the diffuse `color`.
  27679. *
  27680. * @type {?Texture}
  27681. * @default null
  27682. */
  27683. this.map = null;
  27684. /**
  27685. * The light map. Requires a second set of UVs.
  27686. *
  27687. * @type {?Texture}
  27688. * @default null
  27689. */
  27690. this.lightMap = null;
  27691. /**
  27692. * Intensity of the baked light.
  27693. *
  27694. * @type {number}
  27695. * @default 1
  27696. */
  27697. this.lightMapIntensity = 1.0;
  27698. /**
  27699. * The red channel of this texture is used as the ambient occlusion map.
  27700. * Requires a second set of UVs.
  27701. *
  27702. * @type {?Texture}
  27703. * @default null
  27704. */
  27705. this.aoMap = null;
  27706. /**
  27707. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27708. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27709. * red channel is also `1`, ambient light is fully occluded on a surface.
  27710. *
  27711. * @type {number}
  27712. * @default 1
  27713. */
  27714. this.aoMapIntensity = 1.0;
  27715. /**
  27716. * Emissive (light) color of the material, essentially a solid color
  27717. * unaffected by other lighting.
  27718. *
  27719. * @type {Color}
  27720. * @default (0,0,0)
  27721. */
  27722. this.emissive = new Color( 0x000000 );
  27723. /**
  27724. * Intensity of the emissive light. Modulates the emissive color.
  27725. *
  27726. * @type {number}
  27727. * @default 1
  27728. */
  27729. this.emissiveIntensity = 1.0;
  27730. /**
  27731. * Set emissive (glow) map. The emissive map color is modulated by the
  27732. * emissive color and the emissive intensity. If you have an emissive map,
  27733. * be sure to set the emissive color to something other than black.
  27734. *
  27735. * @type {?Texture}
  27736. * @default null
  27737. */
  27738. this.emissiveMap = null;
  27739. /**
  27740. * The texture to create a bump map. The black and white values map to the
  27741. * perceived depth in relation to the lights. Bump doesn't actually affect
  27742. * the geometry of the object, only the lighting. If a normal map is defined
  27743. * this will be ignored.
  27744. *
  27745. * @type {?Texture}
  27746. * @default null
  27747. */
  27748. this.bumpMap = null;
  27749. /**
  27750. * How much the bump map affects the material. Typical range is `[0,1]`.
  27751. *
  27752. * @type {number}
  27753. * @default 1
  27754. */
  27755. this.bumpScale = 1;
  27756. /**
  27757. * The texture to create a normal map. The RGB values affect the surface
  27758. * normal for each pixel fragment and change the way the color is lit. Normal
  27759. * maps do not change the actual shape of the surface, only the lighting. In
  27760. * case the material has a normal map authored using the left handed
  27761. * convention, the `y` component of `normalScale` should be negated to compensate
  27762. * for the different handedness.
  27763. *
  27764. * @type {?Texture}
  27765. * @default null
  27766. */
  27767. this.normalMap = null;
  27768. /**
  27769. * The type of normal map.
  27770. *
  27771. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27772. * @default TangentSpaceNormalMap
  27773. */
  27774. this.normalMapType = TangentSpaceNormalMap;
  27775. /**
  27776. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27777. *
  27778. * @type {Vector2}
  27779. * @default (1,1)
  27780. */
  27781. this.normalScale = new Vector2( 1, 1 );
  27782. /**
  27783. * The displacement map affects the position of the mesh's vertices. Unlike
  27784. * other maps which only affect the light and shade of the material the
  27785. * displaced vertices can cast shadows, block other objects, and otherwise
  27786. * act as real geometry. The displacement texture is an image where the value
  27787. * of each pixel (white being the highest) is mapped against, and
  27788. * repositions, the vertices of the mesh.
  27789. *
  27790. * @type {?Texture}
  27791. * @default null
  27792. */
  27793. this.displacementMap = null;
  27794. /**
  27795. * How much the displacement map affects the mesh (where black is no
  27796. * displacement, and white is maximum displacement). Without a displacement
  27797. * map set, this value is not applied.
  27798. *
  27799. * @type {number}
  27800. * @default 0
  27801. */
  27802. this.displacementScale = 1;
  27803. /**
  27804. * The offset of the displacement map's values on the mesh's vertices.
  27805. * The bias is added to the scaled sample of the displacement map.
  27806. * Without a displacement map set, this value is not applied.
  27807. *
  27808. * @type {number}
  27809. * @default 0
  27810. */
  27811. this.displacementBias = 0;
  27812. /**
  27813. * The green channel of this texture is used to alter the roughness of the
  27814. * material.
  27815. *
  27816. * @type {?Texture}
  27817. * @default null
  27818. */
  27819. this.roughnessMap = null;
  27820. /**
  27821. * The blue channel of this texture is used to alter the metalness of the
  27822. * material.
  27823. *
  27824. * @type {?Texture}
  27825. * @default null
  27826. */
  27827. this.metalnessMap = null;
  27828. /**
  27829. * The alpha map is a grayscale texture that controls the opacity across the
  27830. * surface (black: fully transparent; white: fully opaque).
  27831. *
  27832. * Only the color of the texture is used, ignoring the alpha channel if one
  27833. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27834. * when sampling this texture due to the extra bit of precision provided for
  27835. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27836. * luminance/alpha textures will also still work as expected.
  27837. *
  27838. * @type {?Texture}
  27839. * @default null
  27840. */
  27841. this.alphaMap = null;
  27842. /**
  27843. * The environment map. To ensure a physically correct rendering, environment maps
  27844. * are internally pre-processed with {@link PMREMGenerator}.
  27845. *
  27846. * @type {?Texture}
  27847. * @default null
  27848. */
  27849. this.envMap = null;
  27850. /**
  27851. * The rotation of the environment map in radians.
  27852. *
  27853. * @type {Euler}
  27854. * @default (0,0,0)
  27855. */
  27856. this.envMapRotation = new Euler();
  27857. /**
  27858. * Scales the effect of the environment map by multiplying its color.
  27859. *
  27860. * @type {number}
  27861. * @default 1
  27862. */
  27863. this.envMapIntensity = 1.0;
  27864. /**
  27865. * Renders the geometry as a wireframe.
  27866. *
  27867. * @type {boolean}
  27868. * @default false
  27869. */
  27870. this.wireframe = false;
  27871. /**
  27872. * Controls the thickness of the wireframe.
  27873. *
  27874. * Can only be used with {@link SVGRenderer}.
  27875. *
  27876. * @type {number}
  27877. * @default 1
  27878. */
  27879. this.wireframeLinewidth = 1;
  27880. /**
  27881. * Defines appearance of wireframe ends.
  27882. *
  27883. * Can only be used with {@link SVGRenderer}.
  27884. *
  27885. * @type {('round'|'bevel'|'miter')}
  27886. * @default 'round'
  27887. */
  27888. this.wireframeLinecap = 'round';
  27889. /**
  27890. * Defines appearance of wireframe joints.
  27891. *
  27892. * Can only be used with {@link SVGRenderer}.
  27893. *
  27894. * @type {('round'|'bevel'|'miter')}
  27895. * @default 'round'
  27896. */
  27897. this.wireframeLinejoin = 'round';
  27898. /**
  27899. * Whether the material is rendered with flat shading or not.
  27900. *
  27901. * @type {boolean}
  27902. * @default false
  27903. */
  27904. this.flatShading = false;
  27905. /**
  27906. * Whether the material is affected by fog or not.
  27907. *
  27908. * @type {boolean}
  27909. * @default true
  27910. */
  27911. this.fog = true;
  27912. this.setValues( parameters );
  27913. }
  27914. copy( source ) {
  27915. super.copy( source );
  27916. this.defines = { 'STANDARD': '' };
  27917. this.color.copy( source.color );
  27918. this.roughness = source.roughness;
  27919. this.metalness = source.metalness;
  27920. this.map = source.map;
  27921. this.lightMap = source.lightMap;
  27922. this.lightMapIntensity = source.lightMapIntensity;
  27923. this.aoMap = source.aoMap;
  27924. this.aoMapIntensity = source.aoMapIntensity;
  27925. this.emissive.copy( source.emissive );
  27926. this.emissiveMap = source.emissiveMap;
  27927. this.emissiveIntensity = source.emissiveIntensity;
  27928. this.bumpMap = source.bumpMap;
  27929. this.bumpScale = source.bumpScale;
  27930. this.normalMap = source.normalMap;
  27931. this.normalMapType = source.normalMapType;
  27932. this.normalScale.copy( source.normalScale );
  27933. this.displacementMap = source.displacementMap;
  27934. this.displacementScale = source.displacementScale;
  27935. this.displacementBias = source.displacementBias;
  27936. this.roughnessMap = source.roughnessMap;
  27937. this.metalnessMap = source.metalnessMap;
  27938. this.alphaMap = source.alphaMap;
  27939. this.envMap = source.envMap;
  27940. this.envMapRotation.copy( source.envMapRotation );
  27941. this.envMapIntensity = source.envMapIntensity;
  27942. this.wireframe = source.wireframe;
  27943. this.wireframeLinewidth = source.wireframeLinewidth;
  27944. this.wireframeLinecap = source.wireframeLinecap;
  27945. this.wireframeLinejoin = source.wireframeLinejoin;
  27946. this.flatShading = source.flatShading;
  27947. this.fog = source.fog;
  27948. return this;
  27949. }
  27950. }
  27951. /**
  27952. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27953. * physically-based rendering properties:
  27954. *
  27955. * - Anisotropy: Ability to represent the anisotropic property of materials
  27956. * as observable with brushed metals.
  27957. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27958. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27959. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27960. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27961. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27962. * wings of many insects.
  27963. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27964. * transparent materials are less reflective. Physically-based transmission provides a more
  27965. * realistic option for thin, transparent surfaces like glass.
  27966. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27967. * - Sheen: Can be used for representing cloth and fabric materials.
  27968. *
  27969. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27970. * higher performance cost, per pixel, than other three.js materials. Most
  27971. * effects are disabled by default, and add cost as they are enabled. For
  27972. * best results, always specify an environment map when using this material.
  27973. *
  27974. * @augments MeshStandardMaterial
  27975. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  27976. */
  27977. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27978. /**
  27979. * Constructs a new mesh physical material.
  27980. *
  27981. * @param {Object} [parameters] - An object with one or more properties
  27982. * defining the material's appearance. Any property of the material
  27983. * (including any property from inherited materials) can be passed
  27984. * in here. Color values can be passed any type of value accepted
  27985. * by {@link Color#set}.
  27986. */
  27987. constructor( parameters ) {
  27988. super();
  27989. /**
  27990. * This flag can be used for type testing.
  27991. *
  27992. * @type {boolean}
  27993. * @readonly
  27994. * @default true
  27995. */
  27996. this.isMeshPhysicalMaterial = true;
  27997. this.defines = {
  27998. 'STANDARD': '',
  27999. 'PHYSICAL': ''
  28000. };
  28001. this.type = 'MeshPhysicalMaterial';
  28002. /**
  28003. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28004. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28005. * property provides additional rotation to the vectors in the texture.
  28006. *
  28007. * @type {number}
  28008. * @default 1
  28009. */
  28010. this.anisotropyRotation = 0;
  28011. /**
  28012. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28013. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28014. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28015. *
  28016. * @type {?Texture}
  28017. * @default null
  28018. */
  28019. this.anisotropyMap = null;
  28020. /**
  28021. * The red channel of this texture is multiplied against `clearcoat`,
  28022. * for per-pixel control over a coating's intensity.
  28023. *
  28024. * @type {?Texture}
  28025. * @default null
  28026. */
  28027. this.clearcoatMap = null;
  28028. /**
  28029. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28030. *
  28031. * @type {number}
  28032. * @default 0
  28033. */
  28034. this.clearcoatRoughness = 0.0;
  28035. /**
  28036. * The green channel of this texture is multiplied against
  28037. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28038. *
  28039. * @type {?Texture}
  28040. * @default null
  28041. */
  28042. this.clearcoatRoughnessMap = null;
  28043. /**
  28044. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28045. * `(0,0)` to `(1,1)`.
  28046. *
  28047. * @type {Vector2}
  28048. * @default (1,1)
  28049. */
  28050. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28051. /**
  28052. * Can be used to enable independent normals for the clear coat layer.
  28053. *
  28054. * @type {?Texture}
  28055. * @default null
  28056. */
  28057. this.clearcoatNormalMap = null;
  28058. /**
  28059. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28060. *
  28061. * @type {number}
  28062. * @default 1.5
  28063. */
  28064. this.ior = 1.5;
  28065. /**
  28066. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28067. * corresponds to an index-of-refraction of `1.5`.
  28068. *
  28069. * This models the reflectivity of non-metallic materials. It has no effect
  28070. * when `metalness` is `1.0`
  28071. *
  28072. * @name MeshPhysicalMaterial#reflectivity
  28073. * @type {number}
  28074. * @default 0.5
  28075. */
  28076. Object.defineProperty( this, 'reflectivity', {
  28077. get: function () {
  28078. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28079. },
  28080. set: function ( reflectivity ) {
  28081. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28082. }
  28083. } );
  28084. /**
  28085. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28086. * control over iridescence.
  28087. *
  28088. * @type {?Texture}
  28089. * @default null
  28090. */
  28091. this.iridescenceMap = null;
  28092. /**
  28093. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28094. * Between `1.0` to `2.333`.
  28095. *
  28096. * @type {number}
  28097. * @default 1.3
  28098. */
  28099. this.iridescenceIOR = 1.3;
  28100. /**
  28101. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28102. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28103. *
  28104. * @type {Array<number,number>}
  28105. * @default [100,400]
  28106. */
  28107. this.iridescenceThicknessRange = [ 100, 400 ];
  28108. /**
  28109. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28110. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28111. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28112. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28113. * - Values in-between will linearly interpolate between the elements of the array.
  28114. *
  28115. * @type {?Texture}
  28116. * @default null
  28117. */
  28118. this.iridescenceThicknessMap = null;
  28119. /**
  28120. * The sheen tint.
  28121. *
  28122. * @type {Color}
  28123. * @default (0,0,0)
  28124. */
  28125. this.sheenColor = new Color( 0x000000 );
  28126. /**
  28127. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28128. * over sheen tint.
  28129. *
  28130. * @type {?Texture}
  28131. * @default null
  28132. */
  28133. this.sheenColorMap = null;
  28134. /**
  28135. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28136. *
  28137. * @type {number}
  28138. * @default 1
  28139. */
  28140. this.sheenRoughness = 1.0;
  28141. /**
  28142. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28143. * over sheen roughness.
  28144. *
  28145. * @type {?Texture}
  28146. * @default null
  28147. */
  28148. this.sheenRoughnessMap = null;
  28149. /**
  28150. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28151. * optical transparency.
  28152. *
  28153. * @type {?Texture}
  28154. * @default null
  28155. */
  28156. this.transmissionMap = null;
  28157. /**
  28158. * The thickness of the volume beneath the surface. The value is given in the
  28159. * coordinate space of the mesh. If the value is `0` the material is
  28160. * thin-walled. Otherwise the material is a volume boundary.
  28161. *
  28162. * @type {number}
  28163. * @default 0
  28164. */
  28165. this.thickness = 0;
  28166. /**
  28167. * A texture that defines the thickness, stored in the green channel. This will
  28168. * be multiplied by `thickness`.
  28169. *
  28170. * @type {?Texture}
  28171. * @default null
  28172. */
  28173. this.thicknessMap = null;
  28174. /**
  28175. * Density of the medium given as the average distance that light travels in
  28176. * the medium before interacting with a particle. The value is given in world
  28177. * space units, and must be greater than zero.
  28178. *
  28179. * @type {number}
  28180. * @default Infinity
  28181. */
  28182. this.attenuationDistance = Infinity;
  28183. /**
  28184. * The color that white light turns into due to absorption when reaching the
  28185. * attenuation distance.
  28186. *
  28187. * @type {Color}
  28188. * @default (1,1,1)
  28189. */
  28190. this.attenuationColor = new Color( 1, 1, 1 );
  28191. /**
  28192. * A float that scales the amount of specular reflection for non-metals only.
  28193. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28194. *
  28195. * @type {number}
  28196. * @default 1
  28197. */
  28198. this.specularIntensity = 1.0;
  28199. /**
  28200. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28201. * for per-pixel control over specular intensity.
  28202. *
  28203. * @type {?Texture}
  28204. * @default null
  28205. */
  28206. this.specularIntensityMap = null;
  28207. /**
  28208. * Tints the specular reflection at normal incidence for non-metals only.
  28209. *
  28210. * @type {Color}
  28211. * @default (1,1,1)
  28212. */
  28213. this.specularColor = new Color( 1, 1, 1 );
  28214. /**
  28215. * The RGB channels of this texture are multiplied against `specularColor`,
  28216. * for per-pixel control over specular color.
  28217. *
  28218. * @type {?Texture}
  28219. * @default null
  28220. */
  28221. this.specularColorMap = null;
  28222. this._anisotropy = 0;
  28223. this._clearcoat = 0;
  28224. this._dispersion = 0;
  28225. this._iridescence = 0;
  28226. this._sheen = 0.0;
  28227. this._transmission = 0;
  28228. this.setValues( parameters );
  28229. }
  28230. /**
  28231. * The anisotropy strength, from `0.0` to `1.0`.
  28232. *
  28233. * @type {number}
  28234. * @default 0
  28235. */
  28236. get anisotropy() {
  28237. return this._anisotropy;
  28238. }
  28239. set anisotropy( value ) {
  28240. if ( this._anisotropy > 0 !== value > 0 ) {
  28241. this.version ++;
  28242. }
  28243. this._anisotropy = value;
  28244. }
  28245. /**
  28246. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28247. * clear coat related properties to enable multilayer materials that have a
  28248. * thin translucent layer over the base layer.
  28249. *
  28250. * @type {number}
  28251. * @default 0
  28252. */
  28253. get clearcoat() {
  28254. return this._clearcoat;
  28255. }
  28256. set clearcoat( value ) {
  28257. if ( this._clearcoat > 0 !== value > 0 ) {
  28258. this.version ++;
  28259. }
  28260. this._clearcoat = value;
  28261. }
  28262. /**
  28263. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28264. * the surface and the viewer, from `0.0` to `1.0`.
  28265. *
  28266. * @type {number}
  28267. * @default 0
  28268. */
  28269. get iridescence() {
  28270. return this._iridescence;
  28271. }
  28272. set iridescence( value ) {
  28273. if ( this._iridescence > 0 !== value > 0 ) {
  28274. this.version ++;
  28275. }
  28276. this._iridescence = value;
  28277. }
  28278. /**
  28279. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28280. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28281. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28282. *
  28283. * @type {number}
  28284. * @default 0
  28285. */
  28286. get dispersion() {
  28287. return this._dispersion;
  28288. }
  28289. set dispersion( value ) {
  28290. if ( this._dispersion > 0 !== value > 0 ) {
  28291. this.version ++;
  28292. }
  28293. this._dispersion = value;
  28294. }
  28295. /**
  28296. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28297. *
  28298. * @type {number}
  28299. * @default 0
  28300. */
  28301. get sheen() {
  28302. return this._sheen;
  28303. }
  28304. set sheen( value ) {
  28305. if ( this._sheen > 0 !== value > 0 ) {
  28306. this.version ++;
  28307. }
  28308. this._sheen = value;
  28309. }
  28310. /**
  28311. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28312. *
  28313. * Thin, transparent or semitransparent, plastic or glass materials remain
  28314. * largely reflective even if they are fully transmissive. The transmission
  28315. * property can be used to model these materials.
  28316. *
  28317. * When transmission is non-zero, `opacity` should be set to `1`.
  28318. *
  28319. * @type {number}
  28320. * @default 0
  28321. */
  28322. get transmission() {
  28323. return this._transmission;
  28324. }
  28325. set transmission( value ) {
  28326. if ( this._transmission > 0 !== value > 0 ) {
  28327. this.version ++;
  28328. }
  28329. this._transmission = value;
  28330. }
  28331. copy( source ) {
  28332. super.copy( source );
  28333. this.defines = {
  28334. 'STANDARD': '',
  28335. 'PHYSICAL': ''
  28336. };
  28337. this.anisotropy = source.anisotropy;
  28338. this.anisotropyRotation = source.anisotropyRotation;
  28339. this.anisotropyMap = source.anisotropyMap;
  28340. this.clearcoat = source.clearcoat;
  28341. this.clearcoatMap = source.clearcoatMap;
  28342. this.clearcoatRoughness = source.clearcoatRoughness;
  28343. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28344. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28345. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28346. this.dispersion = source.dispersion;
  28347. this.ior = source.ior;
  28348. this.iridescence = source.iridescence;
  28349. this.iridescenceMap = source.iridescenceMap;
  28350. this.iridescenceIOR = source.iridescenceIOR;
  28351. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28352. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28353. this.sheen = source.sheen;
  28354. this.sheenColor.copy( source.sheenColor );
  28355. this.sheenColorMap = source.sheenColorMap;
  28356. this.sheenRoughness = source.sheenRoughness;
  28357. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28358. this.transmission = source.transmission;
  28359. this.transmissionMap = source.transmissionMap;
  28360. this.thickness = source.thickness;
  28361. this.thicknessMap = source.thicknessMap;
  28362. this.attenuationDistance = source.attenuationDistance;
  28363. this.attenuationColor.copy( source.attenuationColor );
  28364. this.specularIntensity = source.specularIntensity;
  28365. this.specularIntensityMap = source.specularIntensityMap;
  28366. this.specularColor.copy( source.specularColor );
  28367. this.specularColorMap = source.specularColorMap;
  28368. return this;
  28369. }
  28370. }
  28371. /**
  28372. * A material for shiny surfaces with specular highlights.
  28373. *
  28374. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28375. * model for calculating reflectance. Unlike the Lambertian model used in the
  28376. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28377. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28378. *
  28379. * Performance will generally be greater when using this material over the
  28380. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28381. * some graphical accuracy.
  28382. *
  28383. * @augments Material
  28384. * @demo scenes/material-browser.html#MeshPhongMaterial
  28385. */
  28386. class MeshPhongMaterial extends Material {
  28387. /**
  28388. * Constructs a new mesh phong material.
  28389. *
  28390. * @param {Object} [parameters] - An object with one or more properties
  28391. * defining the material's appearance. Any property of the material
  28392. * (including any property from inherited materials) can be passed
  28393. * in here. Color values can be passed any type of value accepted
  28394. * by {@link Color#set}.
  28395. */
  28396. constructor( parameters ) {
  28397. super();
  28398. /**
  28399. * This flag can be used for type testing.
  28400. *
  28401. * @type {boolean}
  28402. * @readonly
  28403. * @default true
  28404. */
  28405. this.isMeshPhongMaterial = true;
  28406. this.type = 'MeshPhongMaterial';
  28407. /**
  28408. * Color of the material.
  28409. *
  28410. * @type {Color}
  28411. * @default (1,1,1)
  28412. */
  28413. this.color = new Color( 0xffffff ); // diffuse
  28414. /**
  28415. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28416. *
  28417. * This defines how shiny the material is and the color of its shine.
  28418. *
  28419. * @type {Color}
  28420. */
  28421. this.specular = new Color( 0x111111 );
  28422. /**
  28423. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28424. *
  28425. * @type {number}
  28426. * @default 30
  28427. */
  28428. this.shininess = 30;
  28429. /**
  28430. * The color map. May optionally include an alpha channel, typically combined
  28431. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28432. * color is modulated by the diffuse `color`.
  28433. *
  28434. * @type {?Texture}
  28435. * @default null
  28436. */
  28437. this.map = null;
  28438. /**
  28439. * The light map. Requires a second set of UVs.
  28440. *
  28441. * @type {?Texture}
  28442. * @default null
  28443. */
  28444. this.lightMap = null;
  28445. /**
  28446. * Intensity of the baked light.
  28447. *
  28448. * @type {number}
  28449. * @default 1
  28450. */
  28451. this.lightMapIntensity = 1.0;
  28452. /**
  28453. * The red channel of this texture is used as the ambient occlusion map.
  28454. * Requires a second set of UVs.
  28455. *
  28456. * @type {?Texture}
  28457. * @default null
  28458. */
  28459. this.aoMap = null;
  28460. /**
  28461. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28462. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28463. * red channel is also `1`, ambient light is fully occluded on a surface.
  28464. *
  28465. * @type {number}
  28466. * @default 1
  28467. */
  28468. this.aoMapIntensity = 1.0;
  28469. /**
  28470. * Emissive (light) color of the material, essentially a solid color
  28471. * unaffected by other lighting.
  28472. *
  28473. * @type {Color}
  28474. * @default (0,0,0)
  28475. */
  28476. this.emissive = new Color( 0x000000 );
  28477. /**
  28478. * Intensity of the emissive light. Modulates the emissive color.
  28479. *
  28480. * @type {number}
  28481. * @default 1
  28482. */
  28483. this.emissiveIntensity = 1.0;
  28484. /**
  28485. * Set emissive (glow) map. The emissive map color is modulated by the
  28486. * emissive color and the emissive intensity. If you have an emissive map,
  28487. * be sure to set the emissive color to something other than black.
  28488. *
  28489. * @type {?Texture}
  28490. * @default null
  28491. */
  28492. this.emissiveMap = null;
  28493. /**
  28494. * The texture to create a bump map. The black and white values map to the
  28495. * perceived depth in relation to the lights. Bump doesn't actually affect
  28496. * the geometry of the object, only the lighting. If a normal map is defined
  28497. * this will be ignored.
  28498. *
  28499. * @type {?Texture}
  28500. * @default null
  28501. */
  28502. this.bumpMap = null;
  28503. /**
  28504. * How much the bump map affects the material. Typical range is `[0,1]`.
  28505. *
  28506. * @type {number}
  28507. * @default 1
  28508. */
  28509. this.bumpScale = 1;
  28510. /**
  28511. * The texture to create a normal map. The RGB values affect the surface
  28512. * normal for each pixel fragment and change the way the color is lit. Normal
  28513. * maps do not change the actual shape of the surface, only the lighting. In
  28514. * case the material has a normal map authored using the left handed
  28515. * convention, the `y` component of `normalScale` should be negated to compensate
  28516. * for the different handedness.
  28517. *
  28518. * @type {?Texture}
  28519. * @default null
  28520. */
  28521. this.normalMap = null;
  28522. /**
  28523. * The type of normal map.
  28524. *
  28525. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28526. * @default TangentSpaceNormalMap
  28527. */
  28528. this.normalMapType = TangentSpaceNormalMap;
  28529. /**
  28530. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28531. *
  28532. * @type {Vector2}
  28533. * @default (1,1)
  28534. */
  28535. this.normalScale = new Vector2( 1, 1 );
  28536. /**
  28537. * The displacement map affects the position of the mesh's vertices. Unlike
  28538. * other maps which only affect the light and shade of the material the
  28539. * displaced vertices can cast shadows, block other objects, and otherwise
  28540. * act as real geometry. The displacement texture is an image where the value
  28541. * of each pixel (white being the highest) is mapped against, and
  28542. * repositions, the vertices of the mesh.
  28543. *
  28544. * @type {?Texture}
  28545. * @default null
  28546. */
  28547. this.displacementMap = null;
  28548. /**
  28549. * How much the displacement map affects the mesh (where black is no
  28550. * displacement, and white is maximum displacement). Without a displacement
  28551. * map set, this value is not applied.
  28552. *
  28553. * @type {number}
  28554. * @default 0
  28555. */
  28556. this.displacementScale = 1;
  28557. /**
  28558. * The offset of the displacement map's values on the mesh's vertices.
  28559. * The bias is added to the scaled sample of the displacement map.
  28560. * Without a displacement map set, this value is not applied.
  28561. *
  28562. * @type {number}
  28563. * @default 0
  28564. */
  28565. this.displacementBias = 0;
  28566. /**
  28567. * The specular map value affects both how much the specular surface
  28568. * highlight contributes and how much of the environment map affects the
  28569. * surface.
  28570. *
  28571. * @type {?Texture}
  28572. * @default null
  28573. */
  28574. this.specularMap = null;
  28575. /**
  28576. * The alpha map is a grayscale texture that controls the opacity across the
  28577. * surface (black: fully transparent; white: fully opaque).
  28578. *
  28579. * Only the color of the texture is used, ignoring the alpha channel if one
  28580. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28581. * when sampling this texture due to the extra bit of precision provided for
  28582. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28583. * luminance/alpha textures will also still work as expected.
  28584. *
  28585. * @type {?Texture}
  28586. * @default null
  28587. */
  28588. this.alphaMap = null;
  28589. /**
  28590. * The environment map.
  28591. *
  28592. * @type {?Texture}
  28593. * @default null
  28594. */
  28595. this.envMap = null;
  28596. /**
  28597. * The rotation of the environment map in radians.
  28598. *
  28599. * @type {Euler}
  28600. * @default (0,0,0)
  28601. */
  28602. this.envMapRotation = new Euler();
  28603. /**
  28604. * How to combine the result of the surface's color with the environment map, if any.
  28605. *
  28606. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28607. * blend between the two colors.
  28608. *
  28609. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28610. * @default MultiplyOperation
  28611. */
  28612. this.combine = MultiplyOperation;
  28613. /**
  28614. * How much the environment map affects the surface.
  28615. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28616. *
  28617. * @type {number}
  28618. * @default 1
  28619. */
  28620. this.reflectivity = 1;
  28621. /**
  28622. * Scales the effect of the environment map by multiplying its color.
  28623. *
  28624. * @type {number}
  28625. * @default 1
  28626. */
  28627. this.envMapIntensity = 1.0;
  28628. /**
  28629. * The index of refraction (IOR) of air (approximately 1) divided by the
  28630. * index of refraction of the material. It is used with environment mapping
  28631. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28632. * The refraction ratio should not exceed `1`.
  28633. *
  28634. * @type {number}
  28635. * @default 0.98
  28636. */
  28637. this.refractionRatio = 0.98;
  28638. /**
  28639. * Renders the geometry as a wireframe.
  28640. *
  28641. * @type {boolean}
  28642. * @default false
  28643. */
  28644. this.wireframe = false;
  28645. /**
  28646. * Controls the thickness of the wireframe.
  28647. *
  28648. * Can only be used with {@link SVGRenderer}.
  28649. *
  28650. * @type {number}
  28651. * @default 1
  28652. */
  28653. this.wireframeLinewidth = 1;
  28654. /**
  28655. * Defines appearance of wireframe ends.
  28656. *
  28657. * Can only be used with {@link SVGRenderer}.
  28658. *
  28659. * @type {('round'|'bevel'|'miter')}
  28660. * @default 'round'
  28661. */
  28662. this.wireframeLinecap = 'round';
  28663. /**
  28664. * Defines appearance of wireframe joints.
  28665. *
  28666. * Can only be used with {@link SVGRenderer}.
  28667. *
  28668. * @type {('round'|'bevel'|'miter')}
  28669. * @default 'round'
  28670. */
  28671. this.wireframeLinejoin = 'round';
  28672. /**
  28673. * Whether the material is rendered with flat shading or not.
  28674. *
  28675. * @type {boolean}
  28676. * @default false
  28677. */
  28678. this.flatShading = false;
  28679. /**
  28680. * Whether the material is affected by fog or not.
  28681. *
  28682. * @type {boolean}
  28683. * @default true
  28684. */
  28685. this.fog = true;
  28686. this.setValues( parameters );
  28687. }
  28688. copy( source ) {
  28689. super.copy( source );
  28690. this.color.copy( source.color );
  28691. this.specular.copy( source.specular );
  28692. this.shininess = source.shininess;
  28693. this.map = source.map;
  28694. this.lightMap = source.lightMap;
  28695. this.lightMapIntensity = source.lightMapIntensity;
  28696. this.aoMap = source.aoMap;
  28697. this.aoMapIntensity = source.aoMapIntensity;
  28698. this.emissive.copy( source.emissive );
  28699. this.emissiveMap = source.emissiveMap;
  28700. this.emissiveIntensity = source.emissiveIntensity;
  28701. this.bumpMap = source.bumpMap;
  28702. this.bumpScale = source.bumpScale;
  28703. this.normalMap = source.normalMap;
  28704. this.normalMapType = source.normalMapType;
  28705. this.normalScale.copy( source.normalScale );
  28706. this.displacementMap = source.displacementMap;
  28707. this.displacementScale = source.displacementScale;
  28708. this.displacementBias = source.displacementBias;
  28709. this.specularMap = source.specularMap;
  28710. this.alphaMap = source.alphaMap;
  28711. this.envMap = source.envMap;
  28712. this.envMapRotation.copy( source.envMapRotation );
  28713. this.combine = source.combine;
  28714. this.reflectivity = source.reflectivity;
  28715. this.envMapIntensity = source.envMapIntensity;
  28716. this.refractionRatio = source.refractionRatio;
  28717. this.wireframe = source.wireframe;
  28718. this.wireframeLinewidth = source.wireframeLinewidth;
  28719. this.wireframeLinecap = source.wireframeLinecap;
  28720. this.wireframeLinejoin = source.wireframeLinejoin;
  28721. this.flatShading = source.flatShading;
  28722. this.fog = source.fog;
  28723. return this;
  28724. }
  28725. }
  28726. /**
  28727. * A material implementing toon shading.
  28728. *
  28729. * @augments Material
  28730. * @demo scenes/material-browser.html#MeshToonMaterial
  28731. */
  28732. class MeshToonMaterial extends Material {
  28733. /**
  28734. * Constructs a new mesh toon material.
  28735. *
  28736. * @param {Object} [parameters] - An object with one or more properties
  28737. * defining the material's appearance. Any property of the material
  28738. * (including any property from inherited materials) can be passed
  28739. * in here. Color values can be passed any type of value accepted
  28740. * by {@link Color#set}.
  28741. */
  28742. constructor( parameters ) {
  28743. super();
  28744. /**
  28745. * This flag can be used for type testing.
  28746. *
  28747. * @type {boolean}
  28748. * @readonly
  28749. * @default true
  28750. */
  28751. this.isMeshToonMaterial = true;
  28752. this.defines = { 'TOON': '' };
  28753. this.type = 'MeshToonMaterial';
  28754. /**
  28755. * Color of the material.
  28756. *
  28757. * @type {Color}
  28758. * @default (1,1,1)
  28759. */
  28760. this.color = new Color( 0xffffff );
  28761. /**
  28762. * The color map. May optionally include an alpha channel, typically combined
  28763. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28764. * color is modulated by the diffuse `color`.
  28765. *
  28766. * @type {?Texture}
  28767. * @default null
  28768. */
  28769. this.map = null;
  28770. /**
  28771. * Gradient map for toon shading. It's required to set
  28772. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@link NearestFilter}
  28773. * when using this type of texture.
  28774. *
  28775. * @type {?Texture}
  28776. * @default null
  28777. */
  28778. this.gradientMap = null;
  28779. /**
  28780. * The light map. Requires a second set of UVs.
  28781. *
  28782. * @type {?Texture}
  28783. * @default null
  28784. */
  28785. this.lightMap = null;
  28786. /**
  28787. * Intensity of the baked light.
  28788. *
  28789. * @type {number}
  28790. * @default 1
  28791. */
  28792. this.lightMapIntensity = 1.0;
  28793. /**
  28794. * The red channel of this texture is used as the ambient occlusion map.
  28795. * Requires a second set of UVs.
  28796. *
  28797. * @type {?Texture}
  28798. * @default null
  28799. */
  28800. this.aoMap = null;
  28801. /**
  28802. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28803. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28804. * red channel is also `1`, ambient light is fully occluded on a surface.
  28805. *
  28806. * @type {number}
  28807. * @default 1
  28808. */
  28809. this.aoMapIntensity = 1.0;
  28810. /**
  28811. * Emissive (light) color of the material, essentially a solid color
  28812. * unaffected by other lighting.
  28813. *
  28814. * @type {Color}
  28815. * @default (0,0,0)
  28816. */
  28817. this.emissive = new Color( 0x000000 );
  28818. /**
  28819. * Intensity of the emissive light. Modulates the emissive color.
  28820. *
  28821. * @type {number}
  28822. * @default 1
  28823. */
  28824. this.emissiveIntensity = 1.0;
  28825. /**
  28826. * Set emissive (glow) map. The emissive map color is modulated by the
  28827. * emissive color and the emissive intensity. If you have an emissive map,
  28828. * be sure to set the emissive color to something other than black.
  28829. *
  28830. * @type {?Texture}
  28831. * @default null
  28832. */
  28833. this.emissiveMap = null;
  28834. /**
  28835. * The texture to create a bump map. The black and white values map to the
  28836. * perceived depth in relation to the lights. Bump doesn't actually affect
  28837. * the geometry of the object, only the lighting. If a normal map is defined
  28838. * this will be ignored.
  28839. *
  28840. * @type {?Texture}
  28841. * @default null
  28842. */
  28843. this.bumpMap = null;
  28844. /**
  28845. * How much the bump map affects the material. Typical range is `[0,1]`.
  28846. *
  28847. * @type {number}
  28848. * @default 1
  28849. */
  28850. this.bumpScale = 1;
  28851. /**
  28852. * The texture to create a normal map. The RGB values affect the surface
  28853. * normal for each pixel fragment and change the way the color is lit. Normal
  28854. * maps do not change the actual shape of the surface, only the lighting. In
  28855. * case the material has a normal map authored using the left handed
  28856. * convention, the `y` component of `normalScale` should be negated to compensate
  28857. * for the different handedness.
  28858. *
  28859. * @type {?Texture}
  28860. * @default null
  28861. */
  28862. this.normalMap = null;
  28863. /**
  28864. * The type of normal map.
  28865. *
  28866. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28867. * @default TangentSpaceNormalMap
  28868. */
  28869. this.normalMapType = TangentSpaceNormalMap;
  28870. /**
  28871. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28872. *
  28873. * @type {Vector2}
  28874. * @default (1,1)
  28875. */
  28876. this.normalScale = new Vector2( 1, 1 );
  28877. /**
  28878. * The displacement map affects the position of the mesh's vertices. Unlike
  28879. * other maps which only affect the light and shade of the material the
  28880. * displaced vertices can cast shadows, block other objects, and otherwise
  28881. * act as real geometry. The displacement texture is an image where the value
  28882. * of each pixel (white being the highest) is mapped against, and
  28883. * repositions, the vertices of the mesh.
  28884. *
  28885. * @type {?Texture}
  28886. * @default null
  28887. */
  28888. this.displacementMap = null;
  28889. /**
  28890. * How much the displacement map affects the mesh (where black is no
  28891. * displacement, and white is maximum displacement). Without a displacement
  28892. * map set, this value is not applied.
  28893. *
  28894. * @type {number}
  28895. * @default 0
  28896. */
  28897. this.displacementScale = 1;
  28898. /**
  28899. * The offset of the displacement map's values on the mesh's vertices.
  28900. * The bias is added to the scaled sample of the displacement map.
  28901. * Without a displacement map set, this value is not applied.
  28902. *
  28903. * @type {number}
  28904. * @default 0
  28905. */
  28906. this.displacementBias = 0;
  28907. /**
  28908. * The alpha map is a grayscale texture that controls the opacity across the
  28909. * surface (black: fully transparent; white: fully opaque).
  28910. *
  28911. * Only the color of the texture is used, ignoring the alpha channel if one
  28912. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28913. * when sampling this texture due to the extra bit of precision provided for
  28914. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28915. * luminance/alpha textures will also still work as expected.
  28916. *
  28917. * @type {?Texture}
  28918. * @default null
  28919. */
  28920. this.alphaMap = null;
  28921. /**
  28922. * Renders the geometry as a wireframe.
  28923. *
  28924. * @type {boolean}
  28925. * @default false
  28926. */
  28927. this.wireframe = false;
  28928. /**
  28929. * Controls the thickness of the wireframe.
  28930. *
  28931. * Can only be used with {@link SVGRenderer}.
  28932. *
  28933. * @type {number}
  28934. * @default 1
  28935. */
  28936. this.wireframeLinewidth = 1;
  28937. /**
  28938. * Defines appearance of wireframe ends.
  28939. *
  28940. * Can only be used with {@link SVGRenderer}.
  28941. *
  28942. * @type {('round'|'bevel'|'miter')}
  28943. * @default 'round'
  28944. */
  28945. this.wireframeLinecap = 'round';
  28946. /**
  28947. * Defines appearance of wireframe joints.
  28948. *
  28949. * Can only be used with {@link SVGRenderer}.
  28950. *
  28951. * @type {('round'|'bevel'|'miter')}
  28952. * @default 'round'
  28953. */
  28954. this.wireframeLinejoin = 'round';
  28955. /**
  28956. * Whether the material is affected by fog or not.
  28957. *
  28958. * @type {boolean}
  28959. * @default true
  28960. */
  28961. this.fog = true;
  28962. this.setValues( parameters );
  28963. }
  28964. copy( source ) {
  28965. super.copy( source );
  28966. this.color.copy( source.color );
  28967. this.map = source.map;
  28968. this.gradientMap = source.gradientMap;
  28969. this.lightMap = source.lightMap;
  28970. this.lightMapIntensity = source.lightMapIntensity;
  28971. this.aoMap = source.aoMap;
  28972. this.aoMapIntensity = source.aoMapIntensity;
  28973. this.emissive.copy( source.emissive );
  28974. this.emissiveMap = source.emissiveMap;
  28975. this.emissiveIntensity = source.emissiveIntensity;
  28976. this.bumpMap = source.bumpMap;
  28977. this.bumpScale = source.bumpScale;
  28978. this.normalMap = source.normalMap;
  28979. this.normalMapType = source.normalMapType;
  28980. this.normalScale.copy( source.normalScale );
  28981. this.displacementMap = source.displacementMap;
  28982. this.displacementScale = source.displacementScale;
  28983. this.displacementBias = source.displacementBias;
  28984. this.alphaMap = source.alphaMap;
  28985. this.wireframe = source.wireframe;
  28986. this.wireframeLinewidth = source.wireframeLinewidth;
  28987. this.wireframeLinecap = source.wireframeLinecap;
  28988. this.wireframeLinejoin = source.wireframeLinejoin;
  28989. this.fog = source.fog;
  28990. return this;
  28991. }
  28992. }
  28993. /**
  28994. * A material that maps the normal vectors to RGB colors.
  28995. *
  28996. * @augments Material
  28997. * @demo scenes/material-browser.html#MeshNormalMaterial
  28998. */
  28999. class MeshNormalMaterial extends Material {
  29000. /**
  29001. * Constructs a new mesh normal material.
  29002. *
  29003. * @param {Object} [parameters] - An object with one or more properties
  29004. * defining the material's appearance. Any property of the material
  29005. * (including any property from inherited materials) can be passed
  29006. * in here. Color values can be passed any type of value accepted
  29007. * by {@link Color#set}.
  29008. */
  29009. constructor( parameters ) {
  29010. super();
  29011. /**
  29012. * This flag can be used for type testing.
  29013. *
  29014. * @type {boolean}
  29015. * @readonly
  29016. * @default true
  29017. */
  29018. this.isMeshNormalMaterial = true;
  29019. this.type = 'MeshNormalMaterial';
  29020. /**
  29021. * The texture to create a bump map. The black and white values map to the
  29022. * perceived depth in relation to the lights. Bump doesn't actually affect
  29023. * the geometry of the object, only the lighting. If a normal map is defined
  29024. * this will be ignored.
  29025. *
  29026. * @type {?Texture}
  29027. * @default null
  29028. */
  29029. this.bumpMap = null;
  29030. /**
  29031. * How much the bump map affects the material. Typical range is `[0,1]`.
  29032. *
  29033. * @type {number}
  29034. * @default 1
  29035. */
  29036. this.bumpScale = 1;
  29037. /**
  29038. * The texture to create a normal map. The RGB values affect the surface
  29039. * normal for each pixel fragment and change the way the color is lit. Normal
  29040. * maps do not change the actual shape of the surface, only the lighting. In
  29041. * case the material has a normal map authored using the left handed
  29042. * convention, the `y` component of `normalScale` should be negated to compensate
  29043. * for the different handedness.
  29044. *
  29045. * @type {?Texture}
  29046. * @default null
  29047. */
  29048. this.normalMap = null;
  29049. /**
  29050. * The type of normal map.
  29051. *
  29052. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29053. * @default TangentSpaceNormalMap
  29054. */
  29055. this.normalMapType = TangentSpaceNormalMap;
  29056. /**
  29057. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29058. *
  29059. * @type {Vector2}
  29060. * @default (1,1)
  29061. */
  29062. this.normalScale = new Vector2( 1, 1 );
  29063. /**
  29064. * The displacement map affects the position of the mesh's vertices. Unlike
  29065. * other maps which only affect the light and shade of the material the
  29066. * displaced vertices can cast shadows, block other objects, and otherwise
  29067. * act as real geometry. The displacement texture is an image where the value
  29068. * of each pixel (white being the highest) is mapped against, and
  29069. * repositions, the vertices of the mesh.
  29070. *
  29071. * @type {?Texture}
  29072. * @default null
  29073. */
  29074. this.displacementMap = null;
  29075. /**
  29076. * How much the displacement map affects the mesh (where black is no
  29077. * displacement, and white is maximum displacement). Without a displacement
  29078. * map set, this value is not applied.
  29079. *
  29080. * @type {number}
  29081. * @default 0
  29082. */
  29083. this.displacementScale = 1;
  29084. /**
  29085. * The offset of the displacement map's values on the mesh's vertices.
  29086. * The bias is added to the scaled sample of the displacement map.
  29087. * Without a displacement map set, this value is not applied.
  29088. *
  29089. * @type {number}
  29090. * @default 0
  29091. */
  29092. this.displacementBias = 0;
  29093. /**
  29094. * Renders the geometry as a wireframe.
  29095. *
  29096. * @type {boolean}
  29097. * @default false
  29098. */
  29099. this.wireframe = false;
  29100. /**
  29101. * Controls the thickness of the wireframe.
  29102. *
  29103. * WebGL and WebGPU ignore this property and always render
  29104. * 1 pixel wide lines.
  29105. *
  29106. * @type {number}
  29107. * @default 1
  29108. */
  29109. this.wireframeLinewidth = 1;
  29110. /**
  29111. * Whether the material is rendered with flat shading or not.
  29112. *
  29113. * @type {boolean}
  29114. * @default false
  29115. */
  29116. this.flatShading = false;
  29117. this.setValues( parameters );
  29118. }
  29119. copy( source ) {
  29120. super.copy( source );
  29121. this.bumpMap = source.bumpMap;
  29122. this.bumpScale = source.bumpScale;
  29123. this.normalMap = source.normalMap;
  29124. this.normalMapType = source.normalMapType;
  29125. this.normalScale.copy( source.normalScale );
  29126. this.displacementMap = source.displacementMap;
  29127. this.displacementScale = source.displacementScale;
  29128. this.displacementBias = source.displacementBias;
  29129. this.wireframe = source.wireframe;
  29130. this.wireframeLinewidth = source.wireframeLinewidth;
  29131. this.flatShading = source.flatShading;
  29132. return this;
  29133. }
  29134. }
  29135. /**
  29136. * A material for non-shiny surfaces, without specular highlights.
  29137. *
  29138. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29139. * model for calculating reflectance. This can simulate some surfaces (such
  29140. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29141. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29142. * shading.
  29143. *
  29144. * Due to the simplicity of the reflectance and illumination models,
  29145. * performance will be greater when using this material over the
  29146. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29147. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29148. *
  29149. * @augments Material
  29150. * @demo scenes/material-browser.html#MeshLambertMaterial
  29151. */
  29152. class MeshLambertMaterial extends Material {
  29153. /**
  29154. * Constructs a new mesh lambert material.
  29155. *
  29156. * @param {Object} [parameters] - An object with one or more properties
  29157. * defining the material's appearance. Any property of the material
  29158. * (including any property from inherited materials) can be passed
  29159. * in here. Color values can be passed any type of value accepted
  29160. * by {@link Color#set}.
  29161. */
  29162. constructor( parameters ) {
  29163. super();
  29164. /**
  29165. * This flag can be used for type testing.
  29166. *
  29167. * @type {boolean}
  29168. * @readonly
  29169. * @default true
  29170. */
  29171. this.isMeshLambertMaterial = true;
  29172. this.type = 'MeshLambertMaterial';
  29173. /**
  29174. * Color of the material.
  29175. *
  29176. * @type {Color}
  29177. * @default (1,1,1)
  29178. */
  29179. this.color = new Color( 0xffffff ); // diffuse
  29180. /**
  29181. * The color map. May optionally include an alpha channel, typically combined
  29182. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29183. * color is modulated by the diffuse `color`.
  29184. *
  29185. * @type {?Texture}
  29186. * @default null
  29187. */
  29188. this.map = null;
  29189. /**
  29190. * The light map. Requires a second set of UVs.
  29191. *
  29192. * @type {?Texture}
  29193. * @default null
  29194. */
  29195. this.lightMap = null;
  29196. /**
  29197. * Intensity of the baked light.
  29198. *
  29199. * @type {number}
  29200. * @default 1
  29201. */
  29202. this.lightMapIntensity = 1.0;
  29203. /**
  29204. * The red channel of this texture is used as the ambient occlusion map.
  29205. * Requires a second set of UVs.
  29206. *
  29207. * @type {?Texture}
  29208. * @default null
  29209. */
  29210. this.aoMap = null;
  29211. /**
  29212. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29213. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29214. * red channel is also `1`, ambient light is fully occluded on a surface.
  29215. *
  29216. * @type {number}
  29217. * @default 1
  29218. */
  29219. this.aoMapIntensity = 1.0;
  29220. /**
  29221. * Emissive (light) color of the material, essentially a solid color
  29222. * unaffected by other lighting.
  29223. *
  29224. * @type {Color}
  29225. * @default (0,0,0)
  29226. */
  29227. this.emissive = new Color( 0x000000 );
  29228. /**
  29229. * Intensity of the emissive light. Modulates the emissive color.
  29230. *
  29231. * @type {number}
  29232. * @default 1
  29233. */
  29234. this.emissiveIntensity = 1.0;
  29235. /**
  29236. * Set emissive (glow) map. The emissive map color is modulated by the
  29237. * emissive color and the emissive intensity. If you have an emissive map,
  29238. * be sure to set the emissive color to something other than black.
  29239. *
  29240. * @type {?Texture}
  29241. * @default null
  29242. */
  29243. this.emissiveMap = null;
  29244. /**
  29245. * The texture to create a bump map. The black and white values map to the
  29246. * perceived depth in relation to the lights. Bump doesn't actually affect
  29247. * the geometry of the object, only the lighting. If a normal map is defined
  29248. * this will be ignored.
  29249. *
  29250. * @type {?Texture}
  29251. * @default null
  29252. */
  29253. this.bumpMap = null;
  29254. /**
  29255. * How much the bump map affects the material. Typical range is `[0,1]`.
  29256. *
  29257. * @type {number}
  29258. * @default 1
  29259. */
  29260. this.bumpScale = 1;
  29261. /**
  29262. * The texture to create a normal map. The RGB values affect the surface
  29263. * normal for each pixel fragment and change the way the color is lit. Normal
  29264. * maps do not change the actual shape of the surface, only the lighting. In
  29265. * case the material has a normal map authored using the left handed
  29266. * convention, the `y` component of `normalScale` should be negated to compensate
  29267. * for the different handedness.
  29268. *
  29269. * @type {?Texture}
  29270. * @default null
  29271. */
  29272. this.normalMap = null;
  29273. /**
  29274. * The type of normal map.
  29275. *
  29276. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29277. * @default TangentSpaceNormalMap
  29278. */
  29279. this.normalMapType = TangentSpaceNormalMap;
  29280. /**
  29281. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29282. *
  29283. * @type {Vector2}
  29284. * @default (1,1)
  29285. */
  29286. this.normalScale = new Vector2( 1, 1 );
  29287. /**
  29288. * The displacement map affects the position of the mesh's vertices. Unlike
  29289. * other maps which only affect the light and shade of the material the
  29290. * displaced vertices can cast shadows, block other objects, and otherwise
  29291. * act as real geometry. The displacement texture is an image where the value
  29292. * of each pixel (white being the highest) is mapped against, and
  29293. * repositions, the vertices of the mesh.
  29294. *
  29295. * @type {?Texture}
  29296. * @default null
  29297. */
  29298. this.displacementMap = null;
  29299. /**
  29300. * How much the displacement map affects the mesh (where black is no
  29301. * displacement, and white is maximum displacement). Without a displacement
  29302. * map set, this value is not applied.
  29303. *
  29304. * @type {number}
  29305. * @default 0
  29306. */
  29307. this.displacementScale = 1;
  29308. /**
  29309. * The offset of the displacement map's values on the mesh's vertices.
  29310. * The bias is added to the scaled sample of the displacement map.
  29311. * Without a displacement map set, this value is not applied.
  29312. *
  29313. * @type {number}
  29314. * @default 0
  29315. */
  29316. this.displacementBias = 0;
  29317. /**
  29318. * Specular map used by the material.
  29319. *
  29320. * @type {?Texture}
  29321. * @default null
  29322. */
  29323. this.specularMap = null;
  29324. /**
  29325. * The alpha map is a grayscale texture that controls the opacity across the
  29326. * surface (black: fully transparent; white: fully opaque).
  29327. *
  29328. * Only the color of the texture is used, ignoring the alpha channel if one
  29329. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29330. * when sampling this texture due to the extra bit of precision provided for
  29331. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29332. * luminance/alpha textures will also still work as expected.
  29333. *
  29334. * @type {?Texture}
  29335. * @default null
  29336. */
  29337. this.alphaMap = null;
  29338. /**
  29339. * The environment map.
  29340. *
  29341. * @type {?Texture}
  29342. * @default null
  29343. */
  29344. this.envMap = null;
  29345. /**
  29346. * The rotation of the environment map in radians.
  29347. *
  29348. * @type {Euler}
  29349. * @default (0,0,0)
  29350. */
  29351. this.envMapRotation = new Euler();
  29352. /**
  29353. * How to combine the result of the surface's color with the environment map, if any.
  29354. *
  29355. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29356. * blend between the two colors.
  29357. *
  29358. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29359. * @default MultiplyOperation
  29360. */
  29361. this.combine = MultiplyOperation;
  29362. /**
  29363. * How much the environment map affects the surface.
  29364. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29365. *
  29366. * @type {number}
  29367. * @default 1
  29368. */
  29369. this.reflectivity = 1;
  29370. /**
  29371. * Scales the effect of the environment map by multiplying its color.
  29372. *
  29373. * @type {number}
  29374. * @default 1
  29375. */
  29376. this.envMapIntensity = 1.0;
  29377. /**
  29378. * The index of refraction (IOR) of air (approximately 1) divided by the
  29379. * index of refraction of the material. It is used with environment mapping
  29380. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29381. * The refraction ratio should not exceed `1`.
  29382. *
  29383. * @type {number}
  29384. * @default 0.98
  29385. */
  29386. this.refractionRatio = 0.98;
  29387. /**
  29388. * Renders the geometry as a wireframe.
  29389. *
  29390. * @type {boolean}
  29391. * @default false
  29392. */
  29393. this.wireframe = false;
  29394. /**
  29395. * Controls the thickness of the wireframe.
  29396. *
  29397. * Can only be used with {@link SVGRenderer}.
  29398. *
  29399. * @type {number}
  29400. * @default 1
  29401. */
  29402. this.wireframeLinewidth = 1;
  29403. /**
  29404. * Defines appearance of wireframe ends.
  29405. *
  29406. * Can only be used with {@link SVGRenderer}.
  29407. *
  29408. * @type {('round'|'bevel'|'miter')}
  29409. * @default 'round'
  29410. */
  29411. this.wireframeLinecap = 'round';
  29412. /**
  29413. * Defines appearance of wireframe joints.
  29414. *
  29415. * Can only be used with {@link SVGRenderer}.
  29416. *
  29417. * @type {('round'|'bevel'|'miter')}
  29418. * @default 'round'
  29419. */
  29420. this.wireframeLinejoin = 'round';
  29421. /**
  29422. * Whether the material is rendered with flat shading or not.
  29423. *
  29424. * @type {boolean}
  29425. * @default false
  29426. */
  29427. this.flatShading = false;
  29428. /**
  29429. * Whether the material is affected by fog or not.
  29430. *
  29431. * @type {boolean}
  29432. * @default true
  29433. */
  29434. this.fog = true;
  29435. this.setValues( parameters );
  29436. }
  29437. copy( source ) {
  29438. super.copy( source );
  29439. this.color.copy( source.color );
  29440. this.map = source.map;
  29441. this.lightMap = source.lightMap;
  29442. this.lightMapIntensity = source.lightMapIntensity;
  29443. this.aoMap = source.aoMap;
  29444. this.aoMapIntensity = source.aoMapIntensity;
  29445. this.emissive.copy( source.emissive );
  29446. this.emissiveMap = source.emissiveMap;
  29447. this.emissiveIntensity = source.emissiveIntensity;
  29448. this.bumpMap = source.bumpMap;
  29449. this.bumpScale = source.bumpScale;
  29450. this.normalMap = source.normalMap;
  29451. this.normalMapType = source.normalMapType;
  29452. this.normalScale.copy( source.normalScale );
  29453. this.displacementMap = source.displacementMap;
  29454. this.displacementScale = source.displacementScale;
  29455. this.displacementBias = source.displacementBias;
  29456. this.specularMap = source.specularMap;
  29457. this.alphaMap = source.alphaMap;
  29458. this.envMap = source.envMap;
  29459. this.envMapRotation.copy( source.envMapRotation );
  29460. this.combine = source.combine;
  29461. this.reflectivity = source.reflectivity;
  29462. this.envMapIntensity = source.envMapIntensity;
  29463. this.refractionRatio = source.refractionRatio;
  29464. this.wireframe = source.wireframe;
  29465. this.wireframeLinewidth = source.wireframeLinewidth;
  29466. this.wireframeLinecap = source.wireframeLinecap;
  29467. this.wireframeLinejoin = source.wireframeLinejoin;
  29468. this.flatShading = source.flatShading;
  29469. this.fog = source.fog;
  29470. return this;
  29471. }
  29472. }
  29473. /**
  29474. * A material for drawing geometry by depth. Depth is based off of the camera
  29475. * near and far plane. White is nearest, black is farthest.
  29476. *
  29477. * @augments Material
  29478. * @demo scenes/material-browser.html#MeshDepthMaterial
  29479. */
  29480. class MeshDepthMaterial extends Material {
  29481. /**
  29482. * Constructs a new mesh depth material.
  29483. *
  29484. * @param {Object} [parameters] - An object with one or more properties
  29485. * defining the material's appearance. Any property of the material
  29486. * (including any property from inherited materials) can be passed
  29487. * in here. Color values can be passed any type of value accepted
  29488. * by {@link Color#set}.
  29489. */
  29490. constructor( parameters ) {
  29491. super();
  29492. /**
  29493. * This flag can be used for type testing.
  29494. *
  29495. * @type {boolean}
  29496. * @readonly
  29497. * @default true
  29498. */
  29499. this.isMeshDepthMaterial = true;
  29500. this.type = 'MeshDepthMaterial';
  29501. /**
  29502. * Type for depth packing.
  29503. *
  29504. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29505. * @default BasicDepthPacking
  29506. */
  29507. this.depthPacking = BasicDepthPacking;
  29508. /**
  29509. * The color map. May optionally include an alpha channel, typically combined
  29510. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29511. *
  29512. * @type {?Texture}
  29513. * @default null
  29514. */
  29515. this.map = null;
  29516. /**
  29517. * The alpha map is a grayscale texture that controls the opacity across the
  29518. * surface (black: fully transparent; white: fully opaque).
  29519. *
  29520. * Only the color of the texture is used, ignoring the alpha channel if one
  29521. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29522. * when sampling this texture due to the extra bit of precision provided for
  29523. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29524. * luminance/alpha textures will also still work as expected.
  29525. *
  29526. * @type {?Texture}
  29527. * @default null
  29528. */
  29529. this.alphaMap = null;
  29530. /**
  29531. * The displacement map affects the position of the mesh's vertices. Unlike
  29532. * other maps which only affect the light and shade of the material the
  29533. * displaced vertices can cast shadows, block other objects, and otherwise
  29534. * act as real geometry. The displacement texture is an image where the value
  29535. * of each pixel (white being the highest) is mapped against, and
  29536. * repositions, the vertices of the mesh.
  29537. *
  29538. * @type {?Texture}
  29539. * @default null
  29540. */
  29541. this.displacementMap = null;
  29542. /**
  29543. * How much the displacement map affects the mesh (where black is no
  29544. * displacement, and white is maximum displacement). Without a displacement
  29545. * map set, this value is not applied.
  29546. *
  29547. * @type {number}
  29548. * @default 0
  29549. */
  29550. this.displacementScale = 1;
  29551. /**
  29552. * The offset of the displacement map's values on the mesh's vertices.
  29553. * The bias is added to the scaled sample of the displacement map.
  29554. * Without a displacement map set, this value is not applied.
  29555. *
  29556. * @type {number}
  29557. * @default 0
  29558. */
  29559. this.displacementBias = 0;
  29560. /**
  29561. * Renders the geometry as a wireframe.
  29562. *
  29563. * @type {boolean}
  29564. * @default false
  29565. */
  29566. this.wireframe = false;
  29567. /**
  29568. * Controls the thickness of the wireframe.
  29569. *
  29570. * WebGL and WebGPU ignore this property and always render
  29571. * 1 pixel wide lines.
  29572. *
  29573. * @type {number}
  29574. * @default 1
  29575. */
  29576. this.wireframeLinewidth = 1;
  29577. this.setValues( parameters );
  29578. }
  29579. copy( source ) {
  29580. super.copy( source );
  29581. this.depthPacking = source.depthPacking;
  29582. this.map = source.map;
  29583. this.alphaMap = source.alphaMap;
  29584. this.displacementMap = source.displacementMap;
  29585. this.displacementScale = source.displacementScale;
  29586. this.displacementBias = source.displacementBias;
  29587. this.wireframe = source.wireframe;
  29588. this.wireframeLinewidth = source.wireframeLinewidth;
  29589. return this;
  29590. }
  29591. }
  29592. /**
  29593. * A material used internally for implementing shadow mapping with
  29594. * point lights.
  29595. *
  29596. * Can also be used to customize the shadow casting of an object by assigning
  29597. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29598. * The following examples demonstrates this approach in order to ensure
  29599. * transparent parts of objects do not cast shadows.
  29600. *
  29601. * @augments Material
  29602. */
  29603. class MeshDistanceMaterial extends Material {
  29604. /**
  29605. * Constructs a new mesh distance material.
  29606. *
  29607. * @param {Object} [parameters] - An object with one or more properties
  29608. * defining the material's appearance. Any property of the material
  29609. * (including any property from inherited materials) can be passed
  29610. * in here. Color values can be passed any type of value accepted
  29611. * by {@link Color#set}.
  29612. */
  29613. constructor( parameters ) {
  29614. super();
  29615. /**
  29616. * This flag can be used for type testing.
  29617. *
  29618. * @type {boolean}
  29619. * @readonly
  29620. * @default true
  29621. */
  29622. this.isMeshDistanceMaterial = true;
  29623. this.type = 'MeshDistanceMaterial';
  29624. /**
  29625. * The color map. May optionally include an alpha channel, typically combined
  29626. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29627. *
  29628. * @type {?Texture}
  29629. * @default null
  29630. */
  29631. this.map = null;
  29632. /**
  29633. * The alpha map is a grayscale texture that controls the opacity across the
  29634. * surface (black: fully transparent; white: fully opaque).
  29635. *
  29636. * Only the color of the texture is used, ignoring the alpha channel if one
  29637. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29638. * when sampling this texture due to the extra bit of precision provided for
  29639. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29640. * luminance/alpha textures will also still work as expected.
  29641. *
  29642. * @type {?Texture}
  29643. * @default null
  29644. */
  29645. this.alphaMap = null;
  29646. /**
  29647. * The displacement map affects the position of the mesh's vertices. Unlike
  29648. * other maps which only affect the light and shade of the material the
  29649. * displaced vertices can cast shadows, block other objects, and otherwise
  29650. * act as real geometry. The displacement texture is an image where the value
  29651. * of each pixel (white being the highest) is mapped against, and
  29652. * repositions, the vertices of the mesh.
  29653. *
  29654. * @type {?Texture}
  29655. * @default null
  29656. */
  29657. this.displacementMap = null;
  29658. /**
  29659. * How much the displacement map affects the mesh (where black is no
  29660. * displacement, and white is maximum displacement). Without a displacement
  29661. * map set, this value is not applied.
  29662. *
  29663. * @type {number}
  29664. * @default 0
  29665. */
  29666. this.displacementScale = 1;
  29667. /**
  29668. * The offset of the displacement map's values on the mesh's vertices.
  29669. * The bias is added to the scaled sample of the displacement map.
  29670. * Without a displacement map set, this value is not applied.
  29671. *
  29672. * @type {number}
  29673. * @default 0
  29674. */
  29675. this.displacementBias = 0;
  29676. this.setValues( parameters );
  29677. }
  29678. copy( source ) {
  29679. super.copy( source );
  29680. this.map = source.map;
  29681. this.alphaMap = source.alphaMap;
  29682. this.displacementMap = source.displacementMap;
  29683. this.displacementScale = source.displacementScale;
  29684. this.displacementBias = source.displacementBias;
  29685. return this;
  29686. }
  29687. }
  29688. /**
  29689. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29690. * material color and shading.
  29691. *
  29692. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29693. * baked lighting. It will cast a shadow onto an object that receives shadows
  29694. * (and shadow clipping works), but it will not self-shadow or receive
  29695. * shadows.
  29696. *
  29697. * @augments Material
  29698. * @demo scenes/material-browser.html#MeshMatcapMaterial
  29699. */
  29700. class MeshMatcapMaterial extends Material {
  29701. /**
  29702. * Constructs a new mesh matcap material.
  29703. *
  29704. * @param {Object} [parameters] - An object with one or more properties
  29705. * defining the material's appearance. Any property of the material
  29706. * (including any property from inherited materials) can be passed
  29707. * in here. Color values can be passed any type of value accepted
  29708. * by {@link Color#set}.
  29709. */
  29710. constructor( parameters ) {
  29711. super();
  29712. /**
  29713. * This flag can be used for type testing.
  29714. *
  29715. * @type {boolean}
  29716. * @readonly
  29717. * @default true
  29718. */
  29719. this.isMeshMatcapMaterial = true;
  29720. this.defines = { 'MATCAP': '' };
  29721. this.type = 'MeshMatcapMaterial';
  29722. /**
  29723. * Color of the material.
  29724. *
  29725. * @type {Color}
  29726. * @default (1,1,1)
  29727. */
  29728. this.color = new Color( 0xffffff ); // diffuse
  29729. /**
  29730. * The matcap map.
  29731. *
  29732. * @type {?Texture}
  29733. * @default null
  29734. */
  29735. this.matcap = null;
  29736. /**
  29737. * The color map. May optionally include an alpha channel, typically combined
  29738. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29739. * color is modulated by the diffuse `color`.
  29740. *
  29741. * @type {?Texture}
  29742. * @default null
  29743. */
  29744. this.map = null;
  29745. /**
  29746. * The texture to create a bump map. The black and white values map to the
  29747. * perceived depth in relation to the lights. Bump doesn't actually affect
  29748. * the geometry of the object, only the lighting. If a normal map is defined
  29749. * this will be ignored.
  29750. *
  29751. * @type {?Texture}
  29752. * @default null
  29753. */
  29754. this.bumpMap = null;
  29755. /**
  29756. * How much the bump map affects the material. Typical range is `[0,1]`.
  29757. *
  29758. * @type {number}
  29759. * @default 1
  29760. */
  29761. this.bumpScale = 1;
  29762. /**
  29763. * The texture to create a normal map. The RGB values affect the surface
  29764. * normal for each pixel fragment and change the way the color is lit. Normal
  29765. * maps do not change the actual shape of the surface, only the lighting. In
  29766. * case the material has a normal map authored using the left handed
  29767. * convention, the `y` component of `normalScale` should be negated to compensate
  29768. * for the different handedness.
  29769. *
  29770. * @type {?Texture}
  29771. * @default null
  29772. */
  29773. this.normalMap = null;
  29774. /**
  29775. * The type of normal map.
  29776. *
  29777. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29778. * @default TangentSpaceNormalMap
  29779. */
  29780. this.normalMapType = TangentSpaceNormalMap;
  29781. /**
  29782. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29783. *
  29784. * @type {Vector2}
  29785. * @default (1,1)
  29786. */
  29787. this.normalScale = new Vector2( 1, 1 );
  29788. /**
  29789. * The displacement map affects the position of the mesh's vertices. Unlike
  29790. * other maps which only affect the light and shade of the material the
  29791. * displaced vertices can cast shadows, block other objects, and otherwise
  29792. * act as real geometry. The displacement texture is an image where the value
  29793. * of each pixel (white being the highest) is mapped against, and
  29794. * repositions, the vertices of the mesh.
  29795. *
  29796. * @type {?Texture}
  29797. * @default null
  29798. */
  29799. this.displacementMap = null;
  29800. /**
  29801. * How much the displacement map affects the mesh (where black is no
  29802. * displacement, and white is maximum displacement). Without a displacement
  29803. * map set, this value is not applied.
  29804. *
  29805. * @type {number}
  29806. * @default 0
  29807. */
  29808. this.displacementScale = 1;
  29809. /**
  29810. * The offset of the displacement map's values on the mesh's vertices.
  29811. * The bias is added to the scaled sample of the displacement map.
  29812. * Without a displacement map set, this value is not applied.
  29813. *
  29814. * @type {number}
  29815. * @default 0
  29816. */
  29817. this.displacementBias = 0;
  29818. /**
  29819. * The alpha map is a grayscale texture that controls the opacity across the
  29820. * surface (black: fully transparent; white: fully opaque).
  29821. *
  29822. * Only the color of the texture is used, ignoring the alpha channel if one
  29823. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29824. * when sampling this texture due to the extra bit of precision provided for
  29825. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29826. * luminance/alpha textures will also still work as expected.
  29827. *
  29828. * @type {?Texture}
  29829. * @default null
  29830. */
  29831. this.alphaMap = null;
  29832. /**
  29833. * Renders the geometry as a wireframe.
  29834. *
  29835. * @type {boolean}
  29836. * @default false
  29837. */
  29838. this.wireframe = false;
  29839. /**
  29840. * Controls the thickness of the wireframe.
  29841. *
  29842. * Can only be used with {@link SVGRenderer}.
  29843. *
  29844. * @type {number}
  29845. * @default 1
  29846. */
  29847. this.wireframeLinewidth = 1;
  29848. /**
  29849. * Whether the material is rendered with flat shading or not.
  29850. *
  29851. * @type {boolean}
  29852. * @default false
  29853. */
  29854. this.flatShading = false;
  29855. /**
  29856. * Whether the material is affected by fog or not.
  29857. *
  29858. * @type {boolean}
  29859. * @default true
  29860. */
  29861. this.fog = true;
  29862. this.setValues( parameters );
  29863. }
  29864. copy( source ) {
  29865. super.copy( source );
  29866. this.defines = { 'MATCAP': '' };
  29867. this.color.copy( source.color );
  29868. this.matcap = source.matcap;
  29869. this.map = source.map;
  29870. this.bumpMap = source.bumpMap;
  29871. this.bumpScale = source.bumpScale;
  29872. this.normalMap = source.normalMap;
  29873. this.normalMapType = source.normalMapType;
  29874. this.normalScale.copy( source.normalScale );
  29875. this.displacementMap = source.displacementMap;
  29876. this.displacementScale = source.displacementScale;
  29877. this.displacementBias = source.displacementBias;
  29878. this.alphaMap = source.alphaMap;
  29879. this.wireframe = source.wireframe;
  29880. this.wireframeLinewidth = source.wireframeLinewidth;
  29881. this.flatShading = source.flatShading;
  29882. this.fog = source.fog;
  29883. return this;
  29884. }
  29885. }
  29886. /**
  29887. * A material for rendering line primitives.
  29888. *
  29889. * Materials define the appearance of renderable 3D objects.
  29890. *
  29891. * ```js
  29892. * const material = new THREE.LineDashedMaterial( {
  29893. * color: 0xffffff,
  29894. * scale: 1,
  29895. * dashSize: 3,
  29896. * gapSize: 1,
  29897. * } );
  29898. * ```
  29899. *
  29900. * @augments LineBasicMaterial
  29901. */
  29902. class LineDashedMaterial extends LineBasicMaterial {
  29903. /**
  29904. * Constructs a new line dashed material.
  29905. *
  29906. * @param {Object} [parameters] - An object with one or more properties
  29907. * defining the material's appearance. Any property of the material
  29908. * (including any property from inherited materials) can be passed
  29909. * in here. Color values can be passed any type of value accepted
  29910. * by {@link Color#set}.
  29911. */
  29912. constructor( parameters ) {
  29913. super();
  29914. /**
  29915. * This flag can be used for type testing.
  29916. *
  29917. * @type {boolean}
  29918. * @readonly
  29919. * @default true
  29920. */
  29921. this.isLineDashedMaterial = true;
  29922. this.type = 'LineDashedMaterial';
  29923. /**
  29924. * The scale of the dashed part of a line.
  29925. *
  29926. * @type {number}
  29927. * @default 1
  29928. */
  29929. this.scale = 1;
  29930. /**
  29931. * The size of the dash. This is both the gap with the stroke.
  29932. *
  29933. * @type {number}
  29934. * @default 3
  29935. */
  29936. this.dashSize = 3;
  29937. /**
  29938. * The size of the gap.
  29939. *
  29940. * @type {number}
  29941. * @default 1
  29942. */
  29943. this.gapSize = 1;
  29944. this.setValues( parameters );
  29945. }
  29946. copy( source ) {
  29947. super.copy( source );
  29948. this.scale = source.scale;
  29949. this.dashSize = source.dashSize;
  29950. this.gapSize = source.gapSize;
  29951. return this;
  29952. }
  29953. }
  29954. /**
  29955. * Converts an array to a specific type.
  29956. *
  29957. * @param {TypedArray|Array} array - The array to convert.
  29958. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29959. * @return {TypedArray} The converted array.
  29960. */
  29961. function convertArray( array, type ) {
  29962. if ( ! array || array.constructor === type ) return array;
  29963. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29964. return new type( array ); // create typed array
  29965. }
  29966. return Array.prototype.slice.call( array ); // create Array
  29967. }
  29968. /**
  29969. * Returns an array by which times and values can be sorted.
  29970. *
  29971. * @param {Array<number>} times - The keyframe time values.
  29972. * @return {Array<number>} The array.
  29973. */
  29974. function getKeyframeOrder( times ) {
  29975. function compareTime( i, j ) {
  29976. return times[ i ] - times[ j ];
  29977. }
  29978. const n = times.length;
  29979. const result = new Array( n );
  29980. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29981. result.sort( compareTime );
  29982. return result;
  29983. }
  29984. /**
  29985. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29986. *
  29987. * @param {Array<number>} values - The values to sort.
  29988. * @param {number} stride - The stride.
  29989. * @param {Array<number>} order - The sort order.
  29990. * @return {Array<number>} The sorted values.
  29991. */
  29992. function sortedArray( values, stride, order ) {
  29993. const nValues = values.length;
  29994. const result = new values.constructor( nValues );
  29995. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29996. const srcOffset = order[ i ] * stride;
  29997. for ( let j = 0; j !== stride; ++ j ) {
  29998. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29999. }
  30000. }
  30001. return result;
  30002. }
  30003. /**
  30004. * Used for parsing AOS keyframe formats.
  30005. *
  30006. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30007. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30008. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30009. * @param {string} valuePropertyName - The name of the property to use.
  30010. */
  30011. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30012. let i = 1, key = jsonKeys[ 0 ];
  30013. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30014. key = jsonKeys[ i ++ ];
  30015. }
  30016. if ( key === undefined ) return; // no data
  30017. let value = key[ valuePropertyName ];
  30018. if ( value === undefined ) return; // no data
  30019. if ( Array.isArray( value ) ) {
  30020. do {
  30021. value = key[ valuePropertyName ];
  30022. if ( value !== undefined ) {
  30023. times.push( key.time );
  30024. values.push( ...value ); // push all elements
  30025. }
  30026. key = jsonKeys[ i ++ ];
  30027. } while ( key !== undefined );
  30028. } else if ( value.toArray !== undefined ) {
  30029. // ...assume THREE.Math-ish
  30030. do {
  30031. value = key[ valuePropertyName ];
  30032. if ( value !== undefined ) {
  30033. times.push( key.time );
  30034. value.toArray( values, values.length );
  30035. }
  30036. key = jsonKeys[ i ++ ];
  30037. } while ( key !== undefined );
  30038. } else {
  30039. // otherwise push as-is
  30040. do {
  30041. value = key[ valuePropertyName ];
  30042. if ( value !== undefined ) {
  30043. times.push( key.time );
  30044. values.push( value );
  30045. }
  30046. key = jsonKeys[ i ++ ];
  30047. } while ( key !== undefined );
  30048. }
  30049. }
  30050. /**
  30051. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30052. *
  30053. * @param {AnimationClip} sourceClip - The values to sort.
  30054. * @param {string} name - The name of the clip.
  30055. * @param {number} startFrame - The start frame.
  30056. * @param {number} endFrame - The end frame.
  30057. * @param {number} [fps=30] - The FPS.
  30058. * @return {AnimationClip} The new sub clip.
  30059. */
  30060. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30061. const clip = sourceClip.clone();
  30062. clip.name = name;
  30063. const tracks = [];
  30064. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30065. const track = clip.tracks[ i ];
  30066. const valueSize = track.getValueSize();
  30067. const times = [];
  30068. const values = [];
  30069. for ( let j = 0; j < track.times.length; ++ j ) {
  30070. const frame = track.times[ j ] * fps;
  30071. if ( frame < startFrame || frame >= endFrame ) continue;
  30072. times.push( track.times[ j ] );
  30073. for ( let k = 0; k < valueSize; ++ k ) {
  30074. values.push( track.values[ j * valueSize + k ] );
  30075. }
  30076. }
  30077. if ( times.length === 0 ) continue;
  30078. track.times = convertArray( times, track.times.constructor );
  30079. track.values = convertArray( values, track.values.constructor );
  30080. tracks.push( track );
  30081. }
  30082. clip.tracks = tracks;
  30083. // find minimum .times value across all tracks in the trimmed clip
  30084. let minStartTime = Infinity;
  30085. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30086. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30087. minStartTime = clip.tracks[ i ].times[ 0 ];
  30088. }
  30089. }
  30090. // shift all tracks such that clip begins at t=0
  30091. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30092. clip.tracks[ i ].shift( -1 * minStartTime );
  30093. }
  30094. clip.resetDuration();
  30095. return clip;
  30096. }
  30097. /**
  30098. * Converts the keyframes of the given animation clip to an additive format.
  30099. *
  30100. * @param {AnimationClip} targetClip - The clip to make additive.
  30101. * @param {number} [referenceFrame=0] - The reference frame.
  30102. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30103. * @param {number} [fps=30] - The FPS.
  30104. * @return {AnimationClip} The updated clip which is now additive.
  30105. */
  30106. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30107. if ( fps <= 0 ) fps = 30;
  30108. const numTracks = referenceClip.tracks.length;
  30109. const referenceTime = referenceFrame / fps;
  30110. // Make each track's values relative to the values at the reference frame
  30111. for ( let i = 0; i < numTracks; ++ i ) {
  30112. const referenceTrack = referenceClip.tracks[ i ];
  30113. const referenceTrackType = referenceTrack.ValueTypeName;
  30114. // Skip this track if it's non-numeric
  30115. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30116. // Find the track in the target clip whose name and type matches the reference track
  30117. const targetTrack = targetClip.tracks.find( function ( track ) {
  30118. return track.name === referenceTrack.name
  30119. && track.ValueTypeName === referenceTrackType;
  30120. } );
  30121. if ( targetTrack === undefined ) continue;
  30122. let referenceOffset = 0;
  30123. const referenceValueSize = referenceTrack.getValueSize();
  30124. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30125. referenceOffset = referenceValueSize / 3;
  30126. }
  30127. let targetOffset = 0;
  30128. const targetValueSize = targetTrack.getValueSize();
  30129. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30130. targetOffset = targetValueSize / 3;
  30131. }
  30132. const lastIndex = referenceTrack.times.length - 1;
  30133. let referenceValue;
  30134. // Find the value to subtract out of the track
  30135. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30136. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30137. const startIndex = referenceOffset;
  30138. const endIndex = referenceValueSize - referenceOffset;
  30139. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30140. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30141. // Reference frame is after the last keyframe, so just use the last keyframe
  30142. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30143. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30144. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30145. } else {
  30146. // Interpolate to the reference value
  30147. const interpolant = referenceTrack.createInterpolant();
  30148. const startIndex = referenceOffset;
  30149. const endIndex = referenceValueSize - referenceOffset;
  30150. interpolant.evaluate( referenceTime );
  30151. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30152. }
  30153. // Conjugate the quaternion
  30154. if ( referenceTrackType === 'quaternion' ) {
  30155. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30156. referenceQuat.toArray( referenceValue );
  30157. }
  30158. // Subtract the reference value from all of the track values
  30159. const numTimes = targetTrack.times.length;
  30160. for ( let j = 0; j < numTimes; ++ j ) {
  30161. const valueStart = j * targetValueSize + targetOffset;
  30162. if ( referenceTrackType === 'quaternion' ) {
  30163. // Multiply the conjugate for quaternion track types
  30164. Quaternion.multiplyQuaternionsFlat(
  30165. targetTrack.values,
  30166. valueStart,
  30167. referenceValue,
  30168. 0,
  30169. targetTrack.values,
  30170. valueStart
  30171. );
  30172. } else {
  30173. const valueEnd = targetValueSize - targetOffset * 2;
  30174. // Subtract each value for all other numeric track types
  30175. for ( let k = 0; k < valueEnd; ++ k ) {
  30176. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30177. }
  30178. }
  30179. }
  30180. }
  30181. targetClip.blendMode = AdditiveAnimationBlendMode;
  30182. return targetClip;
  30183. }
  30184. /**
  30185. * A class with various methods to assist with animations.
  30186. *
  30187. * @hideconstructor
  30188. */
  30189. class AnimationUtils {
  30190. /**
  30191. * Converts an array to a specific type
  30192. *
  30193. * @static
  30194. * @param {TypedArray|Array} array - The array to convert.
  30195. * @param {TypedArray.constructor} type - The constructor of a type array.
  30196. * @return {TypedArray} The converted array
  30197. */
  30198. static convertArray( array, type ) {
  30199. return convertArray( array, type );
  30200. }
  30201. /**
  30202. * Returns `true` if the given object is a typed array.
  30203. *
  30204. * @static
  30205. * @param {any} object - The object to check.
  30206. * @return {boolean} Whether the given object is a typed array.
  30207. */
  30208. static isTypedArray( object ) {
  30209. return isTypedArray( object );
  30210. }
  30211. /**
  30212. * Returns an array by which times and values can be sorted.
  30213. *
  30214. * @static
  30215. * @param {Array<number>} times - The keyframe time values.
  30216. * @return {Array<number>} The array.
  30217. */
  30218. static getKeyframeOrder( times ) {
  30219. return getKeyframeOrder( times );
  30220. }
  30221. /**
  30222. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30223. *
  30224. * @static
  30225. * @param {Array<number>} values - The values to sort.
  30226. * @param {number} stride - The stride.
  30227. * @param {Array<number>} order - The sort order.
  30228. * @return {Array<number>} The sorted values.
  30229. */
  30230. static sortedArray( values, stride, order ) {
  30231. return sortedArray( values, stride, order );
  30232. }
  30233. /**
  30234. * Used for parsing AOS keyframe formats.
  30235. *
  30236. * @static
  30237. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30238. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30239. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30240. * @param {string} valuePropertyName - The name of the property to use.
  30241. */
  30242. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30243. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30244. }
  30245. /**
  30246. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30247. *
  30248. * @static
  30249. * @param {AnimationClip} sourceClip - The values to sort.
  30250. * @param {string} name - The name of the clip.
  30251. * @param {number} startFrame - The start frame.
  30252. * @param {number} endFrame - The end frame.
  30253. * @param {number} [fps=30] - The FPS.
  30254. * @return {AnimationClip} The new sub clip.
  30255. */
  30256. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30257. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30258. }
  30259. /**
  30260. * Converts the keyframes of the given animation clip to an additive format.
  30261. *
  30262. * @static
  30263. * @param {AnimationClip} targetClip - The clip to make additive.
  30264. * @param {number} [referenceFrame=0] - The reference frame.
  30265. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30266. * @param {number} [fps=30] - The FPS.
  30267. * @return {AnimationClip} The updated clip which is now additive.
  30268. */
  30269. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30270. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30271. }
  30272. }
  30273. /**
  30274. * Abstract base class of interpolants over parametric samples.
  30275. *
  30276. * The parameter domain is one dimensional, typically the time or a path
  30277. * along a curve defined by the data.
  30278. *
  30279. * The sample values can have any dimensionality and derived classes may
  30280. * apply special interpretations to the data.
  30281. *
  30282. * This class provides the interval seek in a Template Method, deferring
  30283. * the actual interpolation to derived classes.
  30284. *
  30285. * Time complexity is O(1) for linear access crossing at most two points
  30286. * and O(log N) for random access, where N is the number of positions.
  30287. *
  30288. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30289. *
  30290. * @abstract
  30291. */
  30292. class Interpolant {
  30293. /**
  30294. * Constructs a new interpolant.
  30295. *
  30296. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30297. * @param {TypedArray} sampleValues - The sample values.
  30298. * @param {number} sampleSize - The sample size
  30299. * @param {TypedArray} [resultBuffer] - The result buffer.
  30300. */
  30301. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30302. /**
  30303. * The parameter positions.
  30304. *
  30305. * @type {TypedArray}
  30306. */
  30307. this.parameterPositions = parameterPositions;
  30308. /**
  30309. * A cache index.
  30310. *
  30311. * @private
  30312. * @type {number}
  30313. * @default 0
  30314. */
  30315. this._cachedIndex = 0;
  30316. /**
  30317. * The result buffer.
  30318. *
  30319. * @type {TypedArray}
  30320. */
  30321. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30322. /**
  30323. * The sample values.
  30324. *
  30325. * @type {TypedArray}
  30326. */
  30327. this.sampleValues = sampleValues;
  30328. /**
  30329. * The value size.
  30330. *
  30331. * @type {TypedArray}
  30332. */
  30333. this.valueSize = sampleSize;
  30334. /**
  30335. * The interpolation settings.
  30336. *
  30337. * @type {?Object}
  30338. * @default null
  30339. */
  30340. this.settings = null;
  30341. /**
  30342. * The default settings object.
  30343. *
  30344. * @type {Object}
  30345. */
  30346. this.DefaultSettings_ = {};
  30347. }
  30348. /**
  30349. * Evaluate the interpolant at position `t`.
  30350. *
  30351. * @param {number} t - The interpolation factor.
  30352. * @return {TypedArray} The result buffer.
  30353. */
  30354. evaluate( t ) {
  30355. const pp = this.parameterPositions;
  30356. let i1 = this._cachedIndex,
  30357. t1 = pp[ i1 ],
  30358. t0 = pp[ i1 - 1 ];
  30359. validate_interval: {
  30360. seek: {
  30361. let right;
  30362. linear_scan: {
  30363. //- See http://jsperf.com/comparison-to-undefined/3
  30364. //- slower code:
  30365. //-
  30366. //- if ( t >= t1 || t1 === undefined ) {
  30367. forward_scan: if ( ! ( t < t1 ) ) {
  30368. for ( let giveUpAt = i1 + 2; ; ) {
  30369. if ( t1 === undefined ) {
  30370. if ( t < t0 ) break forward_scan;
  30371. // after end
  30372. i1 = pp.length;
  30373. this._cachedIndex = i1;
  30374. return this.copySampleValue_( i1 - 1 );
  30375. }
  30376. if ( i1 === giveUpAt ) break; // this loop
  30377. t0 = t1;
  30378. t1 = pp[ ++ i1 ];
  30379. if ( t < t1 ) {
  30380. // we have arrived at the sought interval
  30381. break seek;
  30382. }
  30383. }
  30384. // prepare binary search on the right side of the index
  30385. right = pp.length;
  30386. break linear_scan;
  30387. }
  30388. //- slower code:
  30389. //- if ( t < t0 || t0 === undefined ) {
  30390. if ( ! ( t >= t0 ) ) {
  30391. // looping?
  30392. const t1global = pp[ 1 ];
  30393. if ( t < t1global ) {
  30394. i1 = 2; // + 1, using the scan for the details
  30395. t0 = t1global;
  30396. }
  30397. // linear reverse scan
  30398. for ( let giveUpAt = i1 - 2; ; ) {
  30399. if ( t0 === undefined ) {
  30400. // before start
  30401. this._cachedIndex = 0;
  30402. return this.copySampleValue_( 0 );
  30403. }
  30404. if ( i1 === giveUpAt ) break; // this loop
  30405. t1 = t0;
  30406. t0 = pp[ -- i1 - 1 ];
  30407. if ( t >= t0 ) {
  30408. // we have arrived at the sought interval
  30409. break seek;
  30410. }
  30411. }
  30412. // prepare binary search on the left side of the index
  30413. right = i1;
  30414. i1 = 0;
  30415. break linear_scan;
  30416. }
  30417. // the interval is valid
  30418. break validate_interval;
  30419. } // linear scan
  30420. // binary search
  30421. while ( i1 < right ) {
  30422. const mid = ( i1 + right ) >>> 1;
  30423. if ( t < pp[ mid ] ) {
  30424. right = mid;
  30425. } else {
  30426. i1 = mid + 1;
  30427. }
  30428. }
  30429. t1 = pp[ i1 ];
  30430. t0 = pp[ i1 - 1 ];
  30431. // check boundary cases, again
  30432. if ( t0 === undefined ) {
  30433. this._cachedIndex = 0;
  30434. return this.copySampleValue_( 0 );
  30435. }
  30436. if ( t1 === undefined ) {
  30437. i1 = pp.length;
  30438. this._cachedIndex = i1;
  30439. return this.copySampleValue_( i1 - 1 );
  30440. }
  30441. } // seek
  30442. this._cachedIndex = i1;
  30443. this.intervalChanged_( i1, t0, t1 );
  30444. } // validate_interval
  30445. return this.interpolate_( i1, t0, t, t1 );
  30446. }
  30447. /**
  30448. * Returns the interpolation settings.
  30449. *
  30450. * @return {Object} The interpolation settings.
  30451. */
  30452. getSettings_() {
  30453. return this.settings || this.DefaultSettings_;
  30454. }
  30455. /**
  30456. * Copies a sample value to the result buffer.
  30457. *
  30458. * @param {number} index - An index into the sample value buffer.
  30459. * @return {TypedArray} The result buffer.
  30460. */
  30461. copySampleValue_( index ) {
  30462. // copies a sample value to the result buffer
  30463. const result = this.resultBuffer,
  30464. values = this.sampleValues,
  30465. stride = this.valueSize,
  30466. offset = index * stride;
  30467. for ( let i = 0; i !== stride; ++ i ) {
  30468. result[ i ] = values[ offset + i ];
  30469. }
  30470. return result;
  30471. }
  30472. /**
  30473. * Copies a sample value to the result buffer.
  30474. *
  30475. * @abstract
  30476. * @param {number} i1 - An index into the sample value buffer.
  30477. * @param {number} t0 - The previous interpolation factor.
  30478. * @param {number} t - The current interpolation factor.
  30479. * @param {number} t1 - The next interpolation factor.
  30480. * @return {TypedArray} The result buffer.
  30481. */
  30482. interpolate_( /* i1, t0, t, t1 */ ) {
  30483. throw new Error( 'call to abstract method' );
  30484. // implementations shall return this.resultBuffer
  30485. }
  30486. /**
  30487. * Optional method that is executed when the interval has changed.
  30488. *
  30489. * @param {number} i1 - An index into the sample value buffer.
  30490. * @param {number} t0 - The previous interpolation factor.
  30491. * @param {number} t - The current interpolation factor.
  30492. */
  30493. intervalChanged_( /* i1, t0, t1 */ ) {
  30494. // empty
  30495. }
  30496. }
  30497. /**
  30498. * Fast and simple cubic spline interpolant.
  30499. *
  30500. * It was derived from a Hermitian construction setting the first derivative
  30501. * at each sample position to the linear slope between neighboring positions
  30502. * over their parameter interval.
  30503. *
  30504. * @augments Interpolant
  30505. */
  30506. class CubicInterpolant extends Interpolant {
  30507. /**
  30508. * Constructs a new cubic interpolant.
  30509. *
  30510. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30511. * @param {TypedArray} sampleValues - The sample values.
  30512. * @param {number} sampleSize - The sample size
  30513. * @param {TypedArray} [resultBuffer] - The result buffer.
  30514. */
  30515. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30516. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30517. this._weightPrev = -0;
  30518. this._offsetPrev = -0;
  30519. this._weightNext = -0;
  30520. this._offsetNext = -0;
  30521. this.DefaultSettings_ = {
  30522. endingStart: ZeroCurvatureEnding,
  30523. endingEnd: ZeroCurvatureEnding
  30524. };
  30525. }
  30526. intervalChanged_( i1, t0, t1 ) {
  30527. const pp = this.parameterPositions;
  30528. let iPrev = i1 - 2,
  30529. iNext = i1 + 1,
  30530. tPrev = pp[ iPrev ],
  30531. tNext = pp[ iNext ];
  30532. if ( tPrev === undefined ) {
  30533. switch ( this.getSettings_().endingStart ) {
  30534. case ZeroSlopeEnding:
  30535. // f'(t0) = 0
  30536. iPrev = i1;
  30537. tPrev = 2 * t0 - t1;
  30538. break;
  30539. case WrapAroundEnding:
  30540. // use the other end of the curve
  30541. iPrev = pp.length - 2;
  30542. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30543. break;
  30544. default: // ZeroCurvatureEnding
  30545. // f''(t0) = 0 a.k.a. Natural Spline
  30546. iPrev = i1;
  30547. tPrev = t1;
  30548. }
  30549. }
  30550. if ( tNext === undefined ) {
  30551. switch ( this.getSettings_().endingEnd ) {
  30552. case ZeroSlopeEnding:
  30553. // f'(tN) = 0
  30554. iNext = i1;
  30555. tNext = 2 * t1 - t0;
  30556. break;
  30557. case WrapAroundEnding:
  30558. // use the other end of the curve
  30559. iNext = 1;
  30560. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30561. break;
  30562. default: // ZeroCurvatureEnding
  30563. // f''(tN) = 0, a.k.a. Natural Spline
  30564. iNext = i1 - 1;
  30565. tNext = t0;
  30566. }
  30567. }
  30568. const halfDt = ( t1 - t0 ) * 0.5,
  30569. stride = this.valueSize;
  30570. this._weightPrev = halfDt / ( t0 - tPrev );
  30571. this._weightNext = halfDt / ( tNext - t1 );
  30572. this._offsetPrev = iPrev * stride;
  30573. this._offsetNext = iNext * stride;
  30574. }
  30575. interpolate_( i1, t0, t, t1 ) {
  30576. const result = this.resultBuffer,
  30577. values = this.sampleValues,
  30578. stride = this.valueSize,
  30579. o1 = i1 * stride, o0 = o1 - stride,
  30580. oP = this._offsetPrev, oN = this._offsetNext,
  30581. wP = this._weightPrev, wN = this._weightNext,
  30582. p = ( t - t0 ) / ( t1 - t0 ),
  30583. pp = p * p,
  30584. ppp = pp * p;
  30585. // evaluate polynomials
  30586. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30587. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30588. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30589. const sN = wN * ppp - wN * pp;
  30590. // combine data linearly
  30591. for ( let i = 0; i !== stride; ++ i ) {
  30592. result[ i ] =
  30593. sP * values[ oP + i ] +
  30594. s0 * values[ o0 + i ] +
  30595. s1 * values[ o1 + i ] +
  30596. sN * values[ oN + i ];
  30597. }
  30598. return result;
  30599. }
  30600. }
  30601. /**
  30602. * A basic linear interpolant.
  30603. *
  30604. * @augments Interpolant
  30605. */
  30606. class LinearInterpolant extends Interpolant {
  30607. /**
  30608. * Constructs a new linear interpolant.
  30609. *
  30610. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30611. * @param {TypedArray} sampleValues - The sample values.
  30612. * @param {number} sampleSize - The sample size
  30613. * @param {TypedArray} [resultBuffer] - The result buffer.
  30614. */
  30615. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30616. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30617. }
  30618. interpolate_( i1, t0, t, t1 ) {
  30619. const result = this.resultBuffer,
  30620. values = this.sampleValues,
  30621. stride = this.valueSize,
  30622. offset1 = i1 * stride,
  30623. offset0 = offset1 - stride,
  30624. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30625. weight0 = 1 - weight1;
  30626. for ( let i = 0; i !== stride; ++ i ) {
  30627. result[ i ] =
  30628. values[ offset0 + i ] * weight0 +
  30629. values[ offset1 + i ] * weight1;
  30630. }
  30631. return result;
  30632. }
  30633. }
  30634. /**
  30635. * Interpolant that evaluates to the sample value at the position preceding
  30636. * the parameter.
  30637. *
  30638. * @augments Interpolant
  30639. */
  30640. class DiscreteInterpolant extends Interpolant {
  30641. /**
  30642. * Constructs a new discrete interpolant.
  30643. *
  30644. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30645. * @param {TypedArray} sampleValues - The sample values.
  30646. * @param {number} sampleSize - The sample size
  30647. * @param {TypedArray} [resultBuffer] - The result buffer.
  30648. */
  30649. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30650. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30651. }
  30652. interpolate_( i1 /*, t0, t, t1 */ ) {
  30653. return this.copySampleValue_( i1 - 1 );
  30654. }
  30655. }
  30656. /**
  30657. * A Bezier interpolant using cubic Bezier curves with 2D control points.
  30658. *
  30659. * This interpolant supports the COLLADA/Maya style of Bezier animation where
  30660. * each keyframe has explicit in/out tangent control points specified as
  30661. * 2D coordinates (time, value).
  30662. *
  30663. * The tangent data must be provided via the `settings` object:
  30664. * - `settings.inTangents`: Float32Array with [time, value] pairs per keyframe per component
  30665. * - `settings.outTangents`: Float32Array with [time, value] pairs per keyframe per component
  30666. *
  30667. * For a track with N keyframes and stride S:
  30668. * - Each tangent array has N * S * 2 values
  30669. * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value,
  30670. * k1_c0_time, k1_c0_value, ...]
  30671. *
  30672. * @augments Interpolant
  30673. */
  30674. class BezierInterpolant extends Interpolant {
  30675. interpolate_( i1, t0, t, t1 ) {
  30676. const result = this.resultBuffer;
  30677. const values = this.sampleValues;
  30678. const stride = this.valueSize;
  30679. const offset1 = i1 * stride;
  30680. const offset0 = offset1 - stride;
  30681. const settings = this.settings || this.DefaultSettings_;
  30682. const inTangents = settings.inTangents;
  30683. const outTangents = settings.outTangents;
  30684. // If no tangent data, fall back to linear interpolation
  30685. if ( ! inTangents || ! outTangents ) {
  30686. const weight1 = ( t - t0 ) / ( t1 - t0 );
  30687. const weight0 = 1 - weight1;
  30688. for ( let i = 0; i !== stride; ++ i ) {
  30689. result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1;
  30690. }
  30691. return result;
  30692. }
  30693. const tangentStride = stride * 2;
  30694. const i0 = i1 - 1;
  30695. for ( let i = 0; i !== stride; ++ i ) {
  30696. const v0 = values[ offset0 + i ];
  30697. const v1 = values[ offset1 + i ];
  30698. // outTangent of previous keyframe (C0)
  30699. const outTangentOffset = i0 * tangentStride + i * 2;
  30700. const c0x = outTangents[ outTangentOffset ];
  30701. const c0y = outTangents[ outTangentOffset + 1 ];
  30702. // inTangent of current keyframe (C1)
  30703. const inTangentOffset = i1 * tangentStride + i * 2;
  30704. const c1x = inTangents[ inTangentOffset ];
  30705. const c1y = inTangents[ inTangentOffset + 1 ];
  30706. // Solve for Bezier parameter s where Bx(s) = t using Newton-Raphson
  30707. let s = ( t - t0 ) / ( t1 - t0 );
  30708. let s2, s3, oneMinusS, oneMinusS2, oneMinusS3;
  30709. for ( let iter = 0; iter < 8; iter ++ ) {
  30710. s2 = s * s;
  30711. s3 = s2 * s;
  30712. oneMinusS = 1 - s;
  30713. oneMinusS2 = oneMinusS * oneMinusS;
  30714. oneMinusS3 = oneMinusS2 * oneMinusS;
  30715. // Bezier X(s) = (1-s)³·t0 + 3(1-s)²s·c0x + 3(1-s)s²·c1x + s³·t1
  30716. const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1;
  30717. const error = bx - t;
  30718. if ( Math.abs( error ) < 1e-10 ) break;
  30719. // Derivative dX/ds
  30720. const dbx = 3 * oneMinusS2 * ( c0x - t0 ) + 6 * oneMinusS * s * ( c1x - c0x ) + 3 * s2 * ( t1 - c1x );
  30721. if ( Math.abs( dbx ) < 1e-10 ) break;
  30722. s = s - error / dbx;
  30723. s = Math.max( 0, Math.min( 1, s ) );
  30724. }
  30725. // Evaluate Bezier Y(s)
  30726. result[ i ] = oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1;
  30727. }
  30728. return result;
  30729. }
  30730. }
  30731. /**
  30732. * Represents a timed sequence of keyframes, which are composed of lists of
  30733. * times and related values, and which are used to animate a specific property
  30734. * of an object.
  30735. */
  30736. class KeyframeTrack {
  30737. /**
  30738. * Constructs a new keyframe track.
  30739. *
  30740. * @param {string} name - The keyframe track's name.
  30741. * @param {Array<number>} times - A list of keyframe times.
  30742. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30743. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type.
  30744. */
  30745. constructor( name, times, values, interpolation ) {
  30746. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30747. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30748. /**
  30749. * The track's name can refer to morph targets or bones or
  30750. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30751. * for the forms of strings that can be parsed for property binding.
  30752. *
  30753. * @type {string}
  30754. */
  30755. this.name = name;
  30756. /**
  30757. * The keyframe times.
  30758. *
  30759. * @type {Float32Array}
  30760. */
  30761. this.times = convertArray( times, this.TimeBufferType );
  30762. /**
  30763. * The keyframe values.
  30764. *
  30765. * @type {Float32Array}
  30766. */
  30767. this.values = convertArray( values, this.ValueBufferType );
  30768. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30769. }
  30770. /**
  30771. * Converts the keyframe track to JSON.
  30772. *
  30773. * @static
  30774. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30775. * @return {Object} The serialized keyframe track as JSON.
  30776. */
  30777. static toJSON( track ) {
  30778. const trackType = track.constructor;
  30779. let json;
  30780. // derived classes can define a static toJSON method
  30781. if ( trackType.toJSON !== this.toJSON ) {
  30782. json = trackType.toJSON( track );
  30783. } else {
  30784. // by default, we assume the data can be serialized as-is
  30785. json = {
  30786. 'name': track.name,
  30787. 'times': convertArray( track.times, Array ),
  30788. 'values': convertArray( track.values, Array )
  30789. };
  30790. const interpolation = track.getInterpolation();
  30791. if ( interpolation !== track.DefaultInterpolation ) {
  30792. json.interpolation = interpolation;
  30793. }
  30794. }
  30795. json.type = track.ValueTypeName; // mandatory
  30796. return json;
  30797. }
  30798. /**
  30799. * Factory method for creating a new discrete interpolant.
  30800. *
  30801. * @static
  30802. * @param {TypedArray} [result] - The result buffer.
  30803. * @return {DiscreteInterpolant} The new interpolant.
  30804. */
  30805. InterpolantFactoryMethodDiscrete( result ) {
  30806. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30807. }
  30808. /**
  30809. * Factory method for creating a new linear interpolant.
  30810. *
  30811. * @static
  30812. * @param {TypedArray} [result] - The result buffer.
  30813. * @return {LinearInterpolant} The new interpolant.
  30814. */
  30815. InterpolantFactoryMethodLinear( result ) {
  30816. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30817. }
  30818. /**
  30819. * Factory method for creating a new smooth interpolant.
  30820. *
  30821. * @static
  30822. * @param {TypedArray} [result] - The result buffer.
  30823. * @return {CubicInterpolant} The new interpolant.
  30824. */
  30825. InterpolantFactoryMethodSmooth( result ) {
  30826. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30827. }
  30828. /**
  30829. * Factory method for creating a new Bezier interpolant.
  30830. *
  30831. * The Bezier interpolant requires tangent data to be set via the `settings` property
  30832. * on the track before creating the interpolant. The settings should contain:
  30833. * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component
  30834. * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component
  30835. *
  30836. * @static
  30837. * @param {TypedArray} [result] - The result buffer.
  30838. * @return {BezierInterpolant} The new interpolant.
  30839. */
  30840. InterpolantFactoryMethodBezier( result ) {
  30841. const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result );
  30842. // Pass tangent data from track settings to interpolant
  30843. if ( this.settings ) {
  30844. interpolant.settings = this.settings;
  30845. }
  30846. return interpolant;
  30847. }
  30848. /**
  30849. * Defines the interpolation factor method for this keyframe track.
  30850. *
  30851. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type.
  30852. * @return {KeyframeTrack} A reference to this keyframe track.
  30853. */
  30854. setInterpolation( interpolation ) {
  30855. let factoryMethod;
  30856. switch ( interpolation ) {
  30857. case InterpolateDiscrete:
  30858. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30859. break;
  30860. case InterpolateLinear:
  30861. factoryMethod = this.InterpolantFactoryMethodLinear;
  30862. break;
  30863. case InterpolateSmooth:
  30864. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30865. break;
  30866. case InterpolateBezier:
  30867. factoryMethod = this.InterpolantFactoryMethodBezier;
  30868. break;
  30869. }
  30870. if ( factoryMethod === undefined ) {
  30871. const message = 'unsupported interpolation for ' +
  30872. this.ValueTypeName + ' keyframe track named ' + this.name;
  30873. if ( this.createInterpolant === undefined ) {
  30874. // fall back to default, unless the default itself is messed up
  30875. if ( interpolation !== this.DefaultInterpolation ) {
  30876. this.setInterpolation( this.DefaultInterpolation );
  30877. } else {
  30878. throw new Error( message ); // fatal, in this case
  30879. }
  30880. }
  30881. warn( 'KeyframeTrack:', message );
  30882. return this;
  30883. }
  30884. this.createInterpolant = factoryMethod;
  30885. return this;
  30886. }
  30887. /**
  30888. * Returns the current interpolation type.
  30889. *
  30890. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type.
  30891. */
  30892. getInterpolation() {
  30893. switch ( this.createInterpolant ) {
  30894. case this.InterpolantFactoryMethodDiscrete:
  30895. return InterpolateDiscrete;
  30896. case this.InterpolantFactoryMethodLinear:
  30897. return InterpolateLinear;
  30898. case this.InterpolantFactoryMethodSmooth:
  30899. return InterpolateSmooth;
  30900. case this.InterpolantFactoryMethodBezier:
  30901. return InterpolateBezier;
  30902. }
  30903. }
  30904. /**
  30905. * Returns the value size.
  30906. *
  30907. * @return {number} The value size.
  30908. */
  30909. getValueSize() {
  30910. return this.values.length / this.times.length;
  30911. }
  30912. /**
  30913. * Moves all keyframes either forward or backward in time.
  30914. *
  30915. * @param {number} timeOffset - The offset to move the time values.
  30916. * @return {KeyframeTrack} A reference to this keyframe track.
  30917. */
  30918. shift( timeOffset ) {
  30919. if ( timeOffset !== 0.0 ) {
  30920. const times = this.times;
  30921. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30922. times[ i ] += timeOffset;
  30923. }
  30924. }
  30925. return this;
  30926. }
  30927. /**
  30928. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30929. *
  30930. * @param {number} timeScale - The time scale.
  30931. * @return {KeyframeTrack} A reference to this keyframe track.
  30932. */
  30933. scale( timeScale ) {
  30934. if ( timeScale !== 1.0 ) {
  30935. const times = this.times;
  30936. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30937. times[ i ] *= timeScale;
  30938. }
  30939. }
  30940. return this;
  30941. }
  30942. /**
  30943. * Removes keyframes before and after animation without changing any values within the defined time range.
  30944. *
  30945. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30946. * keys this will change their values
  30947. *
  30948. * @param {number} startTime - The start time.
  30949. * @param {number} endTime - The end time.
  30950. * @return {KeyframeTrack} A reference to this keyframe track.
  30951. */
  30952. trim( startTime, endTime ) {
  30953. const times = this.times,
  30954. nKeys = times.length;
  30955. let from = 0,
  30956. to = nKeys - 1;
  30957. while ( from !== nKeys && times[ from ] < startTime ) {
  30958. ++ from;
  30959. }
  30960. while ( to !== -1 && times[ to ] > endTime ) {
  30961. -- to;
  30962. }
  30963. ++ to; // inclusive -> exclusive bound
  30964. if ( from !== 0 || to !== nKeys ) {
  30965. // empty tracks are forbidden, so keep at least one keyframe
  30966. if ( from >= to ) {
  30967. to = Math.max( to, 1 );
  30968. from = to - 1;
  30969. }
  30970. const stride = this.getValueSize();
  30971. this.times = times.slice( from, to );
  30972. this.values = this.values.slice( from * stride, to * stride );
  30973. }
  30974. return this;
  30975. }
  30976. /**
  30977. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30978. * are valid.
  30979. *
  30980. * @return {boolean} Whether the keyframes are valid or not.
  30981. */
  30982. validate() {
  30983. let valid = true;
  30984. const valueSize = this.getValueSize();
  30985. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30986. error( 'KeyframeTrack: Invalid value size in track.', this );
  30987. valid = false;
  30988. }
  30989. const times = this.times,
  30990. values = this.values,
  30991. nKeys = times.length;
  30992. if ( nKeys === 0 ) {
  30993. error( 'KeyframeTrack: Track is empty.', this );
  30994. valid = false;
  30995. }
  30996. let prevTime = null;
  30997. for ( let i = 0; i !== nKeys; i ++ ) {
  30998. const currTime = times[ i ];
  30999. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31000. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31001. valid = false;
  31002. break;
  31003. }
  31004. if ( prevTime !== null && prevTime > currTime ) {
  31005. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31006. valid = false;
  31007. break;
  31008. }
  31009. prevTime = currTime;
  31010. }
  31011. if ( values !== undefined ) {
  31012. if ( isTypedArray( values ) ) {
  31013. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31014. const value = values[ i ];
  31015. if ( isNaN( value ) ) {
  31016. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31017. valid = false;
  31018. break;
  31019. }
  31020. }
  31021. }
  31022. }
  31023. return valid;
  31024. }
  31025. /**
  31026. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31027. * common in morph target sequences).
  31028. *
  31029. * @return {KeyframeTrack} A reference to this keyframe track.
  31030. */
  31031. optimize() {
  31032. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31033. // times or values may be shared with other tracks, so overwriting is unsafe
  31034. const times = this.times.slice(),
  31035. values = this.values.slice(),
  31036. stride = this.getValueSize(),
  31037. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31038. lastIndex = times.length - 1;
  31039. let writeIndex = 1;
  31040. for ( let i = 1; i < lastIndex; ++ i ) {
  31041. let keep = false;
  31042. const time = times[ i ];
  31043. const timeNext = times[ i + 1 ];
  31044. // remove adjacent keyframes scheduled at the same time
  31045. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31046. if ( ! smoothInterpolation ) {
  31047. // remove unnecessary keyframes same as their neighbors
  31048. const offset = i * stride,
  31049. offsetP = offset - stride,
  31050. offsetN = offset + stride;
  31051. for ( let j = 0; j !== stride; ++ j ) {
  31052. const value = values[ offset + j ];
  31053. if ( value !== values[ offsetP + j ] ||
  31054. value !== values[ offsetN + j ] ) {
  31055. keep = true;
  31056. break;
  31057. }
  31058. }
  31059. } else {
  31060. keep = true;
  31061. }
  31062. }
  31063. // in-place compaction
  31064. if ( keep ) {
  31065. if ( i !== writeIndex ) {
  31066. times[ writeIndex ] = times[ i ];
  31067. const readOffset = i * stride,
  31068. writeOffset = writeIndex * stride;
  31069. for ( let j = 0; j !== stride; ++ j ) {
  31070. values[ writeOffset + j ] = values[ readOffset + j ];
  31071. }
  31072. }
  31073. ++ writeIndex;
  31074. }
  31075. }
  31076. // flush last keyframe (compaction looks ahead)
  31077. if ( lastIndex > 0 ) {
  31078. times[ writeIndex ] = times[ lastIndex ];
  31079. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31080. values[ writeOffset + j ] = values[ readOffset + j ];
  31081. }
  31082. ++ writeIndex;
  31083. }
  31084. if ( writeIndex !== times.length ) {
  31085. this.times = times.slice( 0, writeIndex );
  31086. this.values = values.slice( 0, writeIndex * stride );
  31087. } else {
  31088. this.times = times;
  31089. this.values = values;
  31090. }
  31091. return this;
  31092. }
  31093. /**
  31094. * Returns a new keyframe track with copied values from this instance.
  31095. *
  31096. * @return {KeyframeTrack} A clone of this instance.
  31097. */
  31098. clone() {
  31099. const times = this.times.slice();
  31100. const values = this.values.slice();
  31101. const TypedKeyframeTrack = this.constructor;
  31102. const track = new TypedKeyframeTrack( this.name, times, values );
  31103. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31104. track.createInterpolant = this.createInterpolant;
  31105. return track;
  31106. }
  31107. }
  31108. /**
  31109. * The value type name.
  31110. *
  31111. * @type {string}
  31112. * @default ''
  31113. */
  31114. KeyframeTrack.prototype.ValueTypeName = '';
  31115. /**
  31116. * The time buffer type of this keyframe track.
  31117. *
  31118. * @type {TypedArray|Array}
  31119. * @default Float32Array.constructor
  31120. */
  31121. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31122. /**
  31123. * The value buffer type of this keyframe track.
  31124. *
  31125. * @type {TypedArray|Array}
  31126. * @default Float32Array.constructor
  31127. */
  31128. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31129. /**
  31130. * The default interpolation type of this keyframe track.
  31131. *
  31132. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)}
  31133. * @default InterpolateLinear
  31134. */
  31135. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31136. /**
  31137. * A track for boolean keyframe values.
  31138. *
  31139. * @augments KeyframeTrack
  31140. */
  31141. class BooleanKeyframeTrack extends KeyframeTrack {
  31142. /**
  31143. * Constructs a new boolean keyframe track.
  31144. *
  31145. * This keyframe track type has no `interpolation` parameter because the
  31146. * interpolation is always discrete.
  31147. *
  31148. * @param {string} name - The keyframe track's name.
  31149. * @param {Array<number>} times - A list of keyframe times.
  31150. * @param {Array<boolean>} values - A list of keyframe values.
  31151. */
  31152. constructor( name, times, values ) {
  31153. super( name, times, values );
  31154. }
  31155. }
  31156. /**
  31157. * The value type name.
  31158. *
  31159. * @type {string}
  31160. * @default 'bool'
  31161. */
  31162. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31163. /**
  31164. * The value buffer type of this keyframe track.
  31165. *
  31166. * @type {TypedArray|Array}
  31167. * @default Array.constructor
  31168. */
  31169. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31170. /**
  31171. * The default interpolation type of this keyframe track.
  31172. *
  31173. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31174. * @default InterpolateDiscrete
  31175. */
  31176. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31177. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31178. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31179. /**
  31180. * A track for color keyframe values.
  31181. *
  31182. * @augments KeyframeTrack
  31183. */
  31184. class ColorKeyframeTrack extends KeyframeTrack {
  31185. /**
  31186. * Constructs a new color keyframe track.
  31187. *
  31188. * @param {string} name - The keyframe track's name.
  31189. * @param {Array<number>} times - A list of keyframe times.
  31190. * @param {Array<number>} values - A list of keyframe values.
  31191. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31192. */
  31193. constructor( name, times, values, interpolation ) {
  31194. super( name, times, values, interpolation );
  31195. }
  31196. }
  31197. /**
  31198. * The value type name.
  31199. *
  31200. * @type {string}
  31201. * @default 'color'
  31202. */
  31203. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31204. /**
  31205. * A track for numeric keyframe values.
  31206. *
  31207. * @augments KeyframeTrack
  31208. */
  31209. class NumberKeyframeTrack extends KeyframeTrack {
  31210. /**
  31211. * Constructs a new number keyframe track.
  31212. *
  31213. * @param {string} name - The keyframe track's name.
  31214. * @param {Array<number>} times - A list of keyframe times.
  31215. * @param {Array<number>} values - A list of keyframe values.
  31216. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31217. */
  31218. constructor( name, times, values, interpolation ) {
  31219. super( name, times, values, interpolation );
  31220. }
  31221. }
  31222. /**
  31223. * The value type name.
  31224. *
  31225. * @type {string}
  31226. * @default 'number'
  31227. */
  31228. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31229. /**
  31230. * Spherical linear unit quaternion interpolant.
  31231. *
  31232. * @augments Interpolant
  31233. */
  31234. class QuaternionLinearInterpolant extends Interpolant {
  31235. /**
  31236. * Constructs a new SLERP interpolant.
  31237. *
  31238. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31239. * @param {TypedArray} sampleValues - The sample values.
  31240. * @param {number} sampleSize - The sample size
  31241. * @param {TypedArray} [resultBuffer] - The result buffer.
  31242. */
  31243. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31244. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31245. }
  31246. interpolate_( i1, t0, t, t1 ) {
  31247. const result = this.resultBuffer,
  31248. values = this.sampleValues,
  31249. stride = this.valueSize,
  31250. alpha = ( t - t0 ) / ( t1 - t0 );
  31251. let offset = i1 * stride;
  31252. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31253. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31254. }
  31255. return result;
  31256. }
  31257. }
  31258. /**
  31259. * A track for Quaternion keyframe values.
  31260. *
  31261. * @augments KeyframeTrack
  31262. */
  31263. class QuaternionKeyframeTrack extends KeyframeTrack {
  31264. /**
  31265. * Constructs a new Quaternion keyframe track.
  31266. *
  31267. * @param {string} name - The keyframe track's name.
  31268. * @param {Array<number>} times - A list of keyframe times.
  31269. * @param {Array<number>} values - A list of keyframe values.
  31270. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31271. */
  31272. constructor( name, times, values, interpolation ) {
  31273. super( name, times, values, interpolation );
  31274. }
  31275. /**
  31276. * Overwritten so the method returns Quaternion based interpolant.
  31277. *
  31278. * @static
  31279. * @param {TypedArray} [result] - The result buffer.
  31280. * @return {QuaternionLinearInterpolant} The new interpolant.
  31281. */
  31282. InterpolantFactoryMethodLinear( result ) {
  31283. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31284. }
  31285. }
  31286. /**
  31287. * The value type name.
  31288. *
  31289. * @type {string}
  31290. * @default 'quaternion'
  31291. */
  31292. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31293. // ValueBufferType is inherited
  31294. // DefaultInterpolation is inherited;
  31295. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31296. /**
  31297. * A track for string keyframe values.
  31298. *
  31299. * @augments KeyframeTrack
  31300. */
  31301. class StringKeyframeTrack extends KeyframeTrack {
  31302. /**
  31303. * Constructs a new string keyframe track.
  31304. *
  31305. * This keyframe track type has no `interpolation` parameter because the
  31306. * interpolation is always discrete.
  31307. *
  31308. * @param {string} name - The keyframe track's name.
  31309. * @param {Array<number>} times - A list of keyframe times.
  31310. * @param {Array<string>} values - A list of keyframe values.
  31311. */
  31312. constructor( name, times, values ) {
  31313. super( name, times, values );
  31314. }
  31315. }
  31316. /**
  31317. * The value type name.
  31318. *
  31319. * @type {string}
  31320. * @default 'string'
  31321. */
  31322. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31323. /**
  31324. * The value buffer type of this keyframe track.
  31325. *
  31326. * @type {TypedArray|Array}
  31327. * @default Array.constructor
  31328. */
  31329. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31330. /**
  31331. * The default interpolation type of this keyframe track.
  31332. *
  31333. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31334. * @default InterpolateDiscrete
  31335. */
  31336. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31337. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31338. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31339. /**
  31340. * A track for vector keyframe values.
  31341. *
  31342. * @augments KeyframeTrack
  31343. */
  31344. class VectorKeyframeTrack extends KeyframeTrack {
  31345. /**
  31346. * Constructs a new vector keyframe track.
  31347. *
  31348. * @param {string} name - The keyframe track's name.
  31349. * @param {Array<number>} times - A list of keyframe times.
  31350. * @param {Array<number>} values - A list of keyframe values.
  31351. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31352. */
  31353. constructor( name, times, values, interpolation ) {
  31354. super( name, times, values, interpolation );
  31355. }
  31356. }
  31357. /**
  31358. * The value type name.
  31359. *
  31360. * @type {string}
  31361. * @default 'vector'
  31362. */
  31363. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31364. /**
  31365. * A reusable set of keyframe tracks which represent an animation.
  31366. */
  31367. class AnimationClip {
  31368. /**
  31369. * Constructs a new animation clip.
  31370. *
  31371. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31372. * use the static interface of this class for creating clips. In most cases though, animation clips
  31373. * will automatically be created by loaders when importing animated 3D assets.
  31374. *
  31375. * @param {string} [name=''] - The clip's name.
  31376. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31377. * the duration will be calculated from the passed keyframes.
  31378. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31379. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31380. * is blended/combined when two or more animations are simultaneously played.
  31381. */
  31382. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31383. /**
  31384. * The clip's name.
  31385. *
  31386. * @type {string}
  31387. */
  31388. this.name = name;
  31389. /**
  31390. * An array of keyframe tracks.
  31391. *
  31392. * @type {Array<KeyframeTrack>}
  31393. */
  31394. this.tracks = tracks;
  31395. /**
  31396. * The clip's duration in seconds.
  31397. *
  31398. * @type {number}
  31399. */
  31400. this.duration = duration;
  31401. /**
  31402. * Defines how the animation is blended/combined when two or more animations
  31403. * are simultaneously played.
  31404. *
  31405. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31406. */
  31407. this.blendMode = blendMode;
  31408. /**
  31409. * The UUID of the animation clip.
  31410. *
  31411. * @type {string}
  31412. * @readonly
  31413. */
  31414. this.uuid = generateUUID();
  31415. /**
  31416. * An object that can be used to store custom data about the animation clip.
  31417. * It should not hold references to functions as these will not be cloned.
  31418. *
  31419. * @type {Object}
  31420. */
  31421. this.userData = {};
  31422. // this means it should figure out its duration by scanning the tracks
  31423. if ( this.duration < 0 ) {
  31424. this.resetDuration();
  31425. }
  31426. }
  31427. /**
  31428. * Factory method for creating an animation clip from the given JSON.
  31429. *
  31430. * @static
  31431. * @param {Object} json - The serialized animation clip.
  31432. * @return {AnimationClip} The new animation clip.
  31433. */
  31434. static parse( json ) {
  31435. const tracks = [],
  31436. jsonTracks = json.tracks,
  31437. frameTime = 1.0 / ( json.fps || 1.0 );
  31438. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31439. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31440. }
  31441. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31442. clip.uuid = json.uuid;
  31443. clip.userData = JSON.parse( json.userData || '{}' );
  31444. return clip;
  31445. }
  31446. /**
  31447. * Serializes the given animation clip into JSON.
  31448. *
  31449. * @static
  31450. * @param {AnimationClip} clip - The animation clip to serialize.
  31451. * @return {Object} The JSON object.
  31452. */
  31453. static toJSON( clip ) {
  31454. const tracks = [],
  31455. clipTracks = clip.tracks;
  31456. const json = {
  31457. 'name': clip.name,
  31458. 'duration': clip.duration,
  31459. 'tracks': tracks,
  31460. 'uuid': clip.uuid,
  31461. 'blendMode': clip.blendMode,
  31462. 'userData': JSON.stringify( clip.userData ),
  31463. };
  31464. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31465. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31466. }
  31467. return json;
  31468. }
  31469. /**
  31470. * Returns a new animation clip from the passed morph targets array of a
  31471. * geometry, taking a name and the number of frames per second.
  31472. *
  31473. * Note: The fps parameter is required, but the animation speed can be
  31474. * overridden via {@link AnimationAction#setDuration}.
  31475. *
  31476. * @static
  31477. * @param {string} name - The name of the animation clip.
  31478. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31479. * @param {number} fps - The Frames-Per-Second value.
  31480. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31481. * @return {AnimationClip} The new animation clip.
  31482. */
  31483. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31484. const numMorphTargets = morphTargetSequence.length;
  31485. const tracks = [];
  31486. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31487. let times = [];
  31488. let values = [];
  31489. times.push(
  31490. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31491. i,
  31492. ( i + 1 ) % numMorphTargets );
  31493. values.push( 0, 1, 0 );
  31494. const order = getKeyframeOrder( times );
  31495. times = sortedArray( times, 1, order );
  31496. values = sortedArray( values, 1, order );
  31497. // if there is a key at the first frame, duplicate it as the
  31498. // last frame as well for perfect loop.
  31499. if ( ! noLoop && times[ 0 ] === 0 ) {
  31500. times.push( numMorphTargets );
  31501. values.push( values[ 0 ] );
  31502. }
  31503. tracks.push(
  31504. new NumberKeyframeTrack(
  31505. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31506. times, values
  31507. ).scale( 1.0 / fps ) );
  31508. }
  31509. return new this( name, -1, tracks );
  31510. }
  31511. /**
  31512. * Searches for an animation clip by name, taking as its first parameter
  31513. * either an array of clips, or a mesh or geometry that contains an
  31514. * array named "animations" property.
  31515. *
  31516. * @static
  31517. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31518. * @param {string} name - The name to search for.
  31519. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31520. */
  31521. static findByName( objectOrClipArray, name ) {
  31522. let clipArray = objectOrClipArray;
  31523. if ( ! Array.isArray( objectOrClipArray ) ) {
  31524. const o = objectOrClipArray;
  31525. clipArray = o.geometry && o.geometry.animations || o.animations;
  31526. }
  31527. for ( let i = 0; i < clipArray.length; i ++ ) {
  31528. if ( clipArray[ i ].name === name ) {
  31529. return clipArray[ i ];
  31530. }
  31531. }
  31532. return null;
  31533. }
  31534. /**
  31535. * Returns an array of new AnimationClips created from the morph target
  31536. * sequences of a geometry, trying to sort morph target names into
  31537. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31538. *
  31539. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31540. *
  31541. * @static
  31542. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31543. * @param {number} fps - The Frames-Per-Second value.
  31544. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31545. * @return {Array<AnimationClip>} An array of new animation clips.
  31546. */
  31547. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31548. const animationToMorphTargets = {};
  31549. // tested with https://regex101.com/ on trick sequences
  31550. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31551. const pattern = /^([\w-]*?)([\d]+)$/;
  31552. // sort morph target names into animation groups based
  31553. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31554. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31555. const morphTarget = morphTargets[ i ];
  31556. const parts = morphTarget.name.match( pattern );
  31557. if ( parts && parts.length > 1 ) {
  31558. const name = parts[ 1 ];
  31559. let animationMorphTargets = animationToMorphTargets[ name ];
  31560. if ( ! animationMorphTargets ) {
  31561. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31562. }
  31563. animationMorphTargets.push( morphTarget );
  31564. }
  31565. }
  31566. const clips = [];
  31567. for ( const name in animationToMorphTargets ) {
  31568. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31569. }
  31570. return clips;
  31571. }
  31572. /**
  31573. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31574. *
  31575. * @static
  31576. * @deprecated since r175.
  31577. * @param {Object} animation - A serialized animation clip as JSON.
  31578. * @param {Array<Bone>} bones - An array of bones.
  31579. * @return {?AnimationClip} The new animation clip.
  31580. */
  31581. static parseAnimation( animation, bones ) {
  31582. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31583. if ( ! animation ) {
  31584. error( 'AnimationClip: No animation in JSONLoader data.' );
  31585. return null;
  31586. }
  31587. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31588. // only return track if there are actually keys.
  31589. if ( animationKeys.length !== 0 ) {
  31590. const times = [];
  31591. const values = [];
  31592. flattenJSON( animationKeys, times, values, propertyName );
  31593. // empty keys are filtered out, so check again
  31594. if ( times.length !== 0 ) {
  31595. destTracks.push( new trackType( trackName, times, values ) );
  31596. }
  31597. }
  31598. };
  31599. const tracks = [];
  31600. const clipName = animation.name || 'default';
  31601. const fps = animation.fps || 30;
  31602. const blendMode = animation.blendMode;
  31603. // automatic length determination in AnimationClip.
  31604. let duration = animation.length || -1;
  31605. const hierarchyTracks = animation.hierarchy || [];
  31606. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31607. const animationKeys = hierarchyTracks[ h ].keys;
  31608. // skip empty tracks
  31609. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31610. // process morph targets
  31611. if ( animationKeys[ 0 ].morphTargets ) {
  31612. // figure out all morph targets used in this track
  31613. const morphTargetNames = {};
  31614. let k;
  31615. for ( k = 0; k < animationKeys.length; k ++ ) {
  31616. if ( animationKeys[ k ].morphTargets ) {
  31617. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31618. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31619. }
  31620. }
  31621. }
  31622. // create a track for each morph target with all zero
  31623. // morphTargetInfluences except for the keys in which
  31624. // the morphTarget is named.
  31625. for ( const morphTargetName in morphTargetNames ) {
  31626. const times = [];
  31627. const values = [];
  31628. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31629. const animationKey = animationKeys[ k ];
  31630. times.push( animationKey.time );
  31631. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31632. }
  31633. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31634. }
  31635. duration = morphTargetNames.length * fps;
  31636. } else {
  31637. // ...assume skeletal animation
  31638. const boneName = '.bones[' + bones[ h ].name + ']';
  31639. addNonemptyTrack(
  31640. VectorKeyframeTrack, boneName + '.position',
  31641. animationKeys, 'pos', tracks );
  31642. addNonemptyTrack(
  31643. QuaternionKeyframeTrack, boneName + '.quaternion',
  31644. animationKeys, 'rot', tracks );
  31645. addNonemptyTrack(
  31646. VectorKeyframeTrack, boneName + '.scale',
  31647. animationKeys, 'scl', tracks );
  31648. }
  31649. }
  31650. if ( tracks.length === 0 ) {
  31651. return null;
  31652. }
  31653. const clip = new this( clipName, duration, tracks, blendMode );
  31654. return clip;
  31655. }
  31656. /**
  31657. * Sets the duration of this clip to the duration of its longest keyframe track.
  31658. *
  31659. * @return {AnimationClip} A reference to this animation clip.
  31660. */
  31661. resetDuration() {
  31662. const tracks = this.tracks;
  31663. let duration = 0;
  31664. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31665. const track = this.tracks[ i ];
  31666. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31667. }
  31668. this.duration = duration;
  31669. return this;
  31670. }
  31671. /**
  31672. * Trims all tracks to the clip's duration.
  31673. *
  31674. * @return {AnimationClip} A reference to this animation clip.
  31675. */
  31676. trim() {
  31677. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31678. this.tracks[ i ].trim( 0, this.duration );
  31679. }
  31680. return this;
  31681. }
  31682. /**
  31683. * Performs minimal validation on each track in the clip. Returns `true` if all
  31684. * tracks are valid.
  31685. *
  31686. * @return {boolean} Whether the clip's keyframes are valid or not.
  31687. */
  31688. validate() {
  31689. let valid = true;
  31690. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31691. valid = valid && this.tracks[ i ].validate();
  31692. }
  31693. return valid;
  31694. }
  31695. /**
  31696. * Optimizes each track by removing equivalent sequential keys (which are
  31697. * common in morph target sequences).
  31698. *
  31699. * @return {AnimationClip} A reference to this animation clip.
  31700. */
  31701. optimize() {
  31702. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31703. this.tracks[ i ].optimize();
  31704. }
  31705. return this;
  31706. }
  31707. /**
  31708. * Returns a new animation clip with copied values from this instance.
  31709. *
  31710. * @return {AnimationClip} A clone of this instance.
  31711. */
  31712. clone() {
  31713. const tracks = [];
  31714. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31715. tracks.push( this.tracks[ i ].clone() );
  31716. }
  31717. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31718. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31719. return clip;
  31720. }
  31721. /**
  31722. * Serializes this animation clip into JSON.
  31723. *
  31724. * @return {Object} The JSON object.
  31725. */
  31726. toJSON() {
  31727. return this.constructor.toJSON( this );
  31728. }
  31729. }
  31730. function getTrackTypeForValueTypeName( typeName ) {
  31731. switch ( typeName.toLowerCase() ) {
  31732. case 'scalar':
  31733. case 'double':
  31734. case 'float':
  31735. case 'number':
  31736. case 'integer':
  31737. return NumberKeyframeTrack;
  31738. case 'vector':
  31739. case 'vector2':
  31740. case 'vector3':
  31741. case 'vector4':
  31742. return VectorKeyframeTrack;
  31743. case 'color':
  31744. return ColorKeyframeTrack;
  31745. case 'quaternion':
  31746. return QuaternionKeyframeTrack;
  31747. case 'bool':
  31748. case 'boolean':
  31749. return BooleanKeyframeTrack;
  31750. case 'string':
  31751. return StringKeyframeTrack;
  31752. }
  31753. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31754. }
  31755. function parseKeyframeTrack( json ) {
  31756. if ( json.type === undefined ) {
  31757. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31758. }
  31759. const trackType = getTrackTypeForValueTypeName( json.type );
  31760. if ( json.times === undefined ) {
  31761. const times = [], values = [];
  31762. flattenJSON( json.keys, times, values, 'value' );
  31763. json.times = times;
  31764. json.values = values;
  31765. }
  31766. // derived classes can define a static parse method
  31767. if ( trackType.parse !== undefined ) {
  31768. return trackType.parse( json );
  31769. } else {
  31770. // by default, we assume a constructor compatible with the base
  31771. return new trackType( json.name, json.times, json.values, json.interpolation );
  31772. }
  31773. }
  31774. /**
  31775. * @class
  31776. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31777. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31778. * @hideconstructor
  31779. */
  31780. const Cache = {
  31781. /**
  31782. * Whether caching is enabled or not.
  31783. *
  31784. * @static
  31785. * @type {boolean}
  31786. * @default false
  31787. */
  31788. enabled: false,
  31789. /**
  31790. * A dictionary that holds cached files.
  31791. *
  31792. * @static
  31793. * @type {Object<string,Object>}
  31794. */
  31795. files: {},
  31796. /**
  31797. * Adds a cache entry with a key to reference the file. If this key already
  31798. * holds a file, it is overwritten.
  31799. *
  31800. * @static
  31801. * @param {string} key - The key to reference the cached file.
  31802. * @param {Object} file - The file to be cached.
  31803. */
  31804. add: function ( key, file ) {
  31805. if ( this.enabled === false ) return;
  31806. if ( isBlobURL( key ) ) return;
  31807. // log( 'Cache', 'Adding key:', key );
  31808. this.files[ key ] = file;
  31809. },
  31810. /**
  31811. * Gets the cached value for the given key.
  31812. *
  31813. * @static
  31814. * @param {string} key - The key to reference the cached file.
  31815. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31816. */
  31817. get: function ( key ) {
  31818. if ( this.enabled === false ) return;
  31819. if ( isBlobURL( key ) ) return;
  31820. // log( 'Cache', 'Checking key:', key );
  31821. return this.files[ key ];
  31822. },
  31823. /**
  31824. * Removes the cached file associated with the given key.
  31825. *
  31826. * @static
  31827. * @param {string} key - The key to reference the cached file.
  31828. */
  31829. remove: function ( key ) {
  31830. delete this.files[ key ];
  31831. },
  31832. /**
  31833. * Remove all values from the cache.
  31834. *
  31835. * @static
  31836. */
  31837. clear: function () {
  31838. this.files = {};
  31839. }
  31840. };
  31841. /**
  31842. * Returns true if the given cache key contains the blob: scheme.
  31843. *
  31844. * @private
  31845. * @param {string} key - The cache key.
  31846. * @return {boolean} Whether the given cache key contains the blob: scheme or not.
  31847. */
  31848. function isBlobURL( key ) {
  31849. try {
  31850. const urlString = key.slice( key.indexOf( ':' ) + 1 ); // remove type identifier
  31851. const url = new URL( urlString );
  31852. return url.protocol === 'blob:';
  31853. } catch ( e ) {
  31854. // If the string is not a valid URL, it throws an error
  31855. return false;
  31856. }
  31857. }
  31858. /**
  31859. * Handles and keeps track of loaded and pending data. A default global
  31860. * instance of this class is created and used by loaders if not supplied
  31861. * manually.
  31862. *
  31863. * In general that should be sufficient, however there are times when it can
  31864. * be useful to have separate loaders - for example if you want to show
  31865. * separate loading bars for objects and textures.
  31866. *
  31867. * ```js
  31868. * const manager = new THREE.LoadingManager();
  31869. * manager.onLoad = () => console.log( 'Loading complete!' );
  31870. *
  31871. * const loader1 = new OBJLoader( manager );
  31872. * const loader2 = new ColladaLoader( manager );
  31873. * ```
  31874. */
  31875. class LoadingManager {
  31876. /**
  31877. * Constructs a new loading manager.
  31878. *
  31879. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31880. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31881. * @param {Function} [onError] - Executes when an error occurs.
  31882. */
  31883. constructor( onLoad, onProgress, onError ) {
  31884. const scope = this;
  31885. let isLoading = false;
  31886. let itemsLoaded = 0;
  31887. let itemsTotal = 0;
  31888. let urlModifier = undefined;
  31889. const handlers = [];
  31890. // Refer to #5689 for the reason why we don't set .onStart
  31891. // in the constructor
  31892. /**
  31893. * Executes when an item starts loading.
  31894. *
  31895. * @type {Function|undefined}
  31896. * @default undefined
  31897. */
  31898. this.onStart = undefined;
  31899. /**
  31900. * Executes when all items have been loaded.
  31901. *
  31902. * @type {Function|undefined}
  31903. * @default undefined
  31904. */
  31905. this.onLoad = onLoad;
  31906. /**
  31907. * Executes when single items have been loaded.
  31908. *
  31909. * @type {Function|undefined}
  31910. * @default undefined
  31911. */
  31912. this.onProgress = onProgress;
  31913. /**
  31914. * Executes when an error occurs.
  31915. *
  31916. * @type {Function|undefined}
  31917. * @default undefined
  31918. */
  31919. this.onError = onError;
  31920. /**
  31921. * Used for aborting ongoing requests in loaders using this manager.
  31922. *
  31923. * @private
  31924. * @type {AbortController | null}
  31925. */
  31926. this._abortController = null;
  31927. /**
  31928. * This should be called by any loader using the manager when the loader
  31929. * starts loading an item.
  31930. *
  31931. * @param {string} url - The URL to load.
  31932. */
  31933. this.itemStart = function ( url ) {
  31934. itemsTotal ++;
  31935. if ( isLoading === false ) {
  31936. if ( scope.onStart !== undefined ) {
  31937. scope.onStart( url, itemsLoaded, itemsTotal );
  31938. }
  31939. }
  31940. isLoading = true;
  31941. };
  31942. /**
  31943. * This should be called by any loader using the manager when the loader
  31944. * ended loading an item.
  31945. *
  31946. * @param {string} url - The URL of the loaded item.
  31947. */
  31948. this.itemEnd = function ( url ) {
  31949. itemsLoaded ++;
  31950. if ( scope.onProgress !== undefined ) {
  31951. scope.onProgress( url, itemsLoaded, itemsTotal );
  31952. }
  31953. if ( itemsLoaded === itemsTotal ) {
  31954. isLoading = false;
  31955. if ( scope.onLoad !== undefined ) {
  31956. scope.onLoad();
  31957. }
  31958. }
  31959. };
  31960. /**
  31961. * This should be called by any loader using the manager when the loader
  31962. * encounters an error when loading an item.
  31963. *
  31964. * @param {string} url - The URL of the item that produces an error.
  31965. */
  31966. this.itemError = function ( url ) {
  31967. if ( scope.onError !== undefined ) {
  31968. scope.onError( url );
  31969. }
  31970. };
  31971. /**
  31972. * Given a URL, uses the URL modifier callback (if any) and returns a
  31973. * resolved URL. If no URL modifier is set, returns the original URL.
  31974. *
  31975. * @param {string} url - The URL to load.
  31976. * @return {string} The resolved URL.
  31977. */
  31978. this.resolveURL = function ( url ) {
  31979. if ( urlModifier ) {
  31980. return urlModifier( url );
  31981. }
  31982. return url;
  31983. };
  31984. /**
  31985. * If provided, the callback will be passed each resource URL before a
  31986. * request is sent. The callback may return the original URL, or a new URL to
  31987. * override loading behavior. This behavior can be used to load assets from
  31988. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31989. *
  31990. * ```js
  31991. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31992. *
  31993. * const manager = new THREE.LoadingManager();
  31994. *
  31995. * // Initialize loading manager with URL callback.
  31996. * const objectURLs = [];
  31997. * manager.setURLModifier( ( url ) => {
  31998. *
  31999. * url = URL.createObjectURL( blobs[ url ] );
  32000. * objectURLs.push( url );
  32001. * return url;
  32002. *
  32003. * } );
  32004. *
  32005. * // Load as usual, then revoke the blob URLs.
  32006. * const loader = new GLTFLoader( manager );
  32007. * loader.load( 'fish.gltf', (gltf) => {
  32008. *
  32009. * scene.add( gltf.scene );
  32010. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32011. *
  32012. * } );
  32013. * ```
  32014. *
  32015. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32016. * @return {LoadingManager} A reference to this loading manager.
  32017. */
  32018. this.setURLModifier = function ( transform ) {
  32019. urlModifier = transform;
  32020. return this;
  32021. };
  32022. /**
  32023. * Registers a loader with the given regular expression. Can be used to
  32024. * define what loader should be used in order to load specific files. A
  32025. * typical use case is to overwrite the default loader for textures.
  32026. *
  32027. * ```js
  32028. * // add handler for TGA textures
  32029. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32030. * ```
  32031. *
  32032. * @param {string} regex - A regular expression.
  32033. * @param {Loader} loader - A loader that should handle matched cases.
  32034. * @return {LoadingManager} A reference to this loading manager.
  32035. */
  32036. this.addHandler = function ( regex, loader ) {
  32037. handlers.push( regex, loader );
  32038. return this;
  32039. };
  32040. /**
  32041. * Removes the loader for the given regular expression.
  32042. *
  32043. * @param {string} regex - A regular expression.
  32044. * @return {LoadingManager} A reference to this loading manager.
  32045. */
  32046. this.removeHandler = function ( regex ) {
  32047. const index = handlers.indexOf( regex );
  32048. if ( index !== -1 ) {
  32049. handlers.splice( index, 2 );
  32050. }
  32051. return this;
  32052. };
  32053. /**
  32054. * Can be used to retrieve the registered loader for the given file path.
  32055. *
  32056. * @param {string} file - The file path.
  32057. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32058. */
  32059. this.getHandler = function ( file ) {
  32060. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32061. const regex = handlers[ i ];
  32062. const loader = handlers[ i + 1 ];
  32063. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32064. if ( regex.test( file ) ) {
  32065. return loader;
  32066. }
  32067. }
  32068. return null;
  32069. };
  32070. /**
  32071. * Can be used to abort ongoing loading requests in loaders using this manager.
  32072. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32073. * is supported in the browser.
  32074. *
  32075. * @return {LoadingManager} A reference to this loading manager.
  32076. */
  32077. this.abort = function () {
  32078. this.abortController.abort();
  32079. this._abortController = null;
  32080. return this;
  32081. };
  32082. }
  32083. // TODO: Revert this back to a single member variable once this issue has been fixed
  32084. // https://github.com/cloudflare/workerd/issues/3657
  32085. /**
  32086. * Used for aborting ongoing requests in loaders using this manager.
  32087. *
  32088. * @type {AbortController}
  32089. */
  32090. get abortController() {
  32091. if ( ! this._abortController ) {
  32092. this._abortController = new AbortController();
  32093. }
  32094. return this._abortController;
  32095. }
  32096. }
  32097. /**
  32098. * The global default loading manager.
  32099. *
  32100. * @constant
  32101. * @type {LoadingManager}
  32102. */
  32103. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32104. /**
  32105. * Abstract base class for loaders.
  32106. *
  32107. * @abstract
  32108. */
  32109. class Loader {
  32110. /**
  32111. * Constructs a new loader.
  32112. *
  32113. * @param {LoadingManager} [manager] - The loading manager.
  32114. */
  32115. constructor( manager ) {
  32116. /**
  32117. * The loading manager.
  32118. *
  32119. * @type {LoadingManager}
  32120. * @default DefaultLoadingManager
  32121. */
  32122. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32123. /**
  32124. * The crossOrigin string to implement CORS for loading the url from a
  32125. * different domain that allows CORS.
  32126. *
  32127. * @type {string}
  32128. * @default 'anonymous'
  32129. */
  32130. this.crossOrigin = 'anonymous';
  32131. /**
  32132. * Whether the XMLHttpRequest uses credentials.
  32133. *
  32134. * @type {boolean}
  32135. * @default false
  32136. */
  32137. this.withCredentials = false;
  32138. /**
  32139. * The base path from which the asset will be loaded.
  32140. *
  32141. * @type {string}
  32142. */
  32143. this.path = '';
  32144. /**
  32145. * The base path from which additional resources like textures will be loaded.
  32146. *
  32147. * @type {string}
  32148. */
  32149. this.resourcePath = '';
  32150. /**
  32151. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32152. * used in HTTP request.
  32153. *
  32154. * @type {Object<string, any>}
  32155. */
  32156. this.requestHeader = {};
  32157. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32158. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32159. }
  32160. }
  32161. /**
  32162. * This method needs to be implemented by all concrete loaders. It holds the
  32163. * logic for loading assets from the backend.
  32164. *
  32165. * @abstract
  32166. * @param {string} url - The path/URL of the file to be loaded.
  32167. * @param {Function} onLoad - Executed when the loading process has been finished.
  32168. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32169. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32170. */
  32171. load( /* url, onLoad, onProgress, onError */ ) {}
  32172. /**
  32173. * A async version of {@link Loader#load}.
  32174. *
  32175. * @param {string} url - The path/URL of the file to be loaded.
  32176. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32177. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32178. */
  32179. loadAsync( url, onProgress ) {
  32180. const scope = this;
  32181. return new Promise( function ( resolve, reject ) {
  32182. scope.load( url, resolve, onProgress, reject );
  32183. } );
  32184. }
  32185. /**
  32186. * This method needs to be implemented by all concrete loaders. It holds the
  32187. * logic for parsing the asset into three.js entities.
  32188. *
  32189. * @abstract
  32190. * @param {any} data - The data to parse.
  32191. */
  32192. parse( /* data */ ) {}
  32193. /**
  32194. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32195. * from a different domain that allows CORS.
  32196. *
  32197. * @param {string} crossOrigin - The `crossOrigin` value.
  32198. * @return {Loader} A reference to this instance.
  32199. */
  32200. setCrossOrigin( crossOrigin ) {
  32201. this.crossOrigin = crossOrigin;
  32202. return this;
  32203. }
  32204. /**
  32205. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32206. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32207. *
  32208. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32209. *
  32210. * @param {boolean} value - The `withCredentials` value.
  32211. * @return {Loader} A reference to this instance.
  32212. */
  32213. setWithCredentials( value ) {
  32214. this.withCredentials = value;
  32215. return this;
  32216. }
  32217. /**
  32218. * Sets the base path for the asset.
  32219. *
  32220. * @param {string} path - The base path.
  32221. * @return {Loader} A reference to this instance.
  32222. */
  32223. setPath( path ) {
  32224. this.path = path;
  32225. return this;
  32226. }
  32227. /**
  32228. * Sets the base path for dependent resources like textures.
  32229. *
  32230. * @param {string} resourcePath - The resource path.
  32231. * @return {Loader} A reference to this instance.
  32232. */
  32233. setResourcePath( resourcePath ) {
  32234. this.resourcePath = resourcePath;
  32235. return this;
  32236. }
  32237. /**
  32238. * Sets the given request header.
  32239. *
  32240. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32241. * for configuring the HTTP request.
  32242. * @return {Loader} A reference to this instance.
  32243. */
  32244. setRequestHeader( requestHeader ) {
  32245. this.requestHeader = requestHeader;
  32246. return this;
  32247. }
  32248. /**
  32249. * This method can be implemented in loaders for aborting ongoing requests.
  32250. *
  32251. * @abstract
  32252. * @return {Loader} A reference to this instance.
  32253. */
  32254. abort() {
  32255. return this;
  32256. }
  32257. }
  32258. /**
  32259. * Callback for onProgress in loaders.
  32260. *
  32261. * @callback onProgressCallback
  32262. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32263. */
  32264. /**
  32265. * Callback for onError in loaders.
  32266. *
  32267. * @callback onErrorCallback
  32268. * @param {Error} error - The error which occurred during the loading process.
  32269. */
  32270. /**
  32271. * The default material name that is used by loaders
  32272. * when creating materials for loaded 3D objects.
  32273. *
  32274. * Note: Not all loaders might honor this setting.
  32275. *
  32276. * @static
  32277. * @type {string}
  32278. * @default '__DEFAULT'
  32279. */
  32280. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32281. const loading = {};
  32282. class HttpError extends Error {
  32283. constructor( message, response ) {
  32284. super( message );
  32285. this.response = response;
  32286. }
  32287. }
  32288. /**
  32289. * A low level class for loading resources with the Fetch API, used internally by
  32290. * most loaders. It can also be used directly to load any file type that does
  32291. * not have a loader.
  32292. *
  32293. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32294. * once to your application.
  32295. *
  32296. * ```js
  32297. * const loader = new THREE.FileLoader();
  32298. * const data = await loader.loadAsync( 'example.txt' );
  32299. * ```
  32300. *
  32301. * @augments Loader
  32302. */
  32303. class FileLoader extends Loader {
  32304. /**
  32305. * Constructs a new file loader.
  32306. *
  32307. * @param {LoadingManager} [manager] - The loading manager.
  32308. */
  32309. constructor( manager ) {
  32310. super( manager );
  32311. /**
  32312. * The expected mime type. Valid values can be found
  32313. * [here](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32314. *
  32315. * @type {string}
  32316. */
  32317. this.mimeType = '';
  32318. /**
  32319. * The expected response type.
  32320. *
  32321. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32322. * @default ''
  32323. */
  32324. this.responseType = '';
  32325. /**
  32326. * Used for aborting requests.
  32327. *
  32328. * @private
  32329. * @type {AbortController}
  32330. */
  32331. this._abortController = new AbortController();
  32332. }
  32333. /**
  32334. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32335. *
  32336. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32337. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32338. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32339. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32340. */
  32341. load( url, onLoad, onProgress, onError ) {
  32342. if ( url === undefined ) url = '';
  32343. if ( this.path !== undefined ) url = this.path + url;
  32344. url = this.manager.resolveURL( url );
  32345. const cached = Cache.get( `file:${url}` );
  32346. if ( cached !== undefined ) {
  32347. this.manager.itemStart( url );
  32348. setTimeout( () => {
  32349. if ( onLoad ) onLoad( cached );
  32350. this.manager.itemEnd( url );
  32351. }, 0 );
  32352. return;
  32353. }
  32354. // Check if request is duplicate
  32355. if ( loading[ url ] !== undefined ) {
  32356. loading[ url ].push( {
  32357. onLoad: onLoad,
  32358. onProgress: onProgress,
  32359. onError: onError
  32360. } );
  32361. return;
  32362. }
  32363. // Initialise array for duplicate requests
  32364. loading[ url ] = [];
  32365. loading[ url ].push( {
  32366. onLoad: onLoad,
  32367. onProgress: onProgress,
  32368. onError: onError,
  32369. } );
  32370. // create request
  32371. const req = new Request( url, {
  32372. headers: new Headers( this.requestHeader ),
  32373. credentials: this.withCredentials ? 'include' : 'same-origin',
  32374. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32375. } );
  32376. // record states ( avoid data race )
  32377. const mimeType = this.mimeType;
  32378. const responseType = this.responseType;
  32379. // start the fetch
  32380. fetch( req )
  32381. .then( response => {
  32382. if ( response.status === 200 || response.status === 0 ) {
  32383. // Some browsers return HTTP Status 0 when using non-http protocol
  32384. // e.g. 'file://' or 'data://'. Handle as success.
  32385. if ( response.status === 0 ) {
  32386. warn( 'FileLoader: HTTP Status 0 received.' );
  32387. }
  32388. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32389. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32390. return response;
  32391. }
  32392. const callbacks = loading[ url ];
  32393. const reader = response.body.getReader();
  32394. // Nginx needs X-File-Size check
  32395. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32396. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32397. const total = contentLength ? parseInt( contentLength ) : 0;
  32398. const lengthComputable = total !== 0;
  32399. let loaded = 0;
  32400. // periodically read data into the new stream tracking while download progress
  32401. const stream = new ReadableStream( {
  32402. start( controller ) {
  32403. readData();
  32404. function readData() {
  32405. reader.read().then( ( { done, value } ) => {
  32406. if ( done ) {
  32407. controller.close();
  32408. } else {
  32409. loaded += value.byteLength;
  32410. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32411. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32412. const callback = callbacks[ i ];
  32413. if ( callback.onProgress ) callback.onProgress( event );
  32414. }
  32415. controller.enqueue( value );
  32416. readData();
  32417. }
  32418. }, ( e ) => {
  32419. controller.error( e );
  32420. } );
  32421. }
  32422. }
  32423. } );
  32424. return new Response( stream );
  32425. } else {
  32426. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32427. }
  32428. } )
  32429. .then( response => {
  32430. switch ( responseType ) {
  32431. case 'arraybuffer':
  32432. return response.arrayBuffer();
  32433. case 'blob':
  32434. return response.blob();
  32435. case 'document':
  32436. return response.text()
  32437. .then( text => {
  32438. const parser = new DOMParser();
  32439. return parser.parseFromString( text, mimeType );
  32440. } );
  32441. case 'json':
  32442. return response.json();
  32443. default:
  32444. if ( mimeType === '' ) {
  32445. return response.text();
  32446. } else {
  32447. // sniff encoding
  32448. const re = /charset="?([^;"\s]*)"?/i;
  32449. const exec = re.exec( mimeType );
  32450. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32451. const decoder = new TextDecoder( label );
  32452. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32453. }
  32454. }
  32455. } )
  32456. .then( data => {
  32457. // Add to cache only on HTTP success, so that we do not cache
  32458. // error response bodies as proper responses to requests.
  32459. Cache.add( `file:${url}`, data );
  32460. const callbacks = loading[ url ];
  32461. delete loading[ url ];
  32462. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32463. const callback = callbacks[ i ];
  32464. if ( callback.onLoad ) callback.onLoad( data );
  32465. }
  32466. } )
  32467. .catch( err => {
  32468. // Abort errors and other errors are handled the same
  32469. const callbacks = loading[ url ];
  32470. if ( callbacks === undefined ) {
  32471. // When onLoad was called and url was deleted in `loading`
  32472. this.manager.itemError( url );
  32473. throw err;
  32474. }
  32475. delete loading[ url ];
  32476. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32477. const callback = callbacks[ i ];
  32478. if ( callback.onError ) callback.onError( err );
  32479. }
  32480. this.manager.itemError( url );
  32481. } )
  32482. .finally( () => {
  32483. this.manager.itemEnd( url );
  32484. } );
  32485. this.manager.itemStart( url );
  32486. }
  32487. /**
  32488. * Sets the expected response type.
  32489. *
  32490. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32491. * @return {FileLoader} A reference to this file loader.
  32492. */
  32493. setResponseType( value ) {
  32494. this.responseType = value;
  32495. return this;
  32496. }
  32497. /**
  32498. * Sets the expected mime type of the loaded file.
  32499. *
  32500. * @param {string} value - The mime type.
  32501. * @return {FileLoader} A reference to this file loader.
  32502. */
  32503. setMimeType( value ) {
  32504. this.mimeType = value;
  32505. return this;
  32506. }
  32507. /**
  32508. * Aborts ongoing fetch requests.
  32509. *
  32510. * @return {FileLoader} A reference to this instance.
  32511. */
  32512. abort() {
  32513. this._abortController.abort();
  32514. this._abortController = new AbortController();
  32515. return this;
  32516. }
  32517. }
  32518. /**
  32519. * Class for loading animation clips in the JSON format. The files are internally
  32520. * loaded via {@link FileLoader}.
  32521. *
  32522. * ```js
  32523. * const loader = new THREE.AnimationLoader();
  32524. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32525. * ```
  32526. *
  32527. * @augments Loader
  32528. */
  32529. class AnimationLoader extends Loader {
  32530. /**
  32531. * Constructs a new animation loader.
  32532. *
  32533. * @param {LoadingManager} [manager] - The loading manager.
  32534. */
  32535. constructor( manager ) {
  32536. super( manager );
  32537. }
  32538. /**
  32539. * Starts loading from the given URL and pass the loaded animations as an array
  32540. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32541. *
  32542. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32543. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32544. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32545. * @param {onErrorCallback} onError - Executed when errors occur.
  32546. */
  32547. load( url, onLoad, onProgress, onError ) {
  32548. const scope = this;
  32549. const loader = new FileLoader( this.manager );
  32550. loader.setPath( this.path );
  32551. loader.setRequestHeader( this.requestHeader );
  32552. loader.setWithCredentials( this.withCredentials );
  32553. loader.load( url, function ( text ) {
  32554. try {
  32555. onLoad( scope.parse( JSON.parse( text ) ) );
  32556. } catch ( e ) {
  32557. if ( onError ) {
  32558. onError( e );
  32559. } else {
  32560. error( e );
  32561. }
  32562. scope.manager.itemError( url );
  32563. }
  32564. }, onProgress, onError );
  32565. }
  32566. /**
  32567. * Parses the given JSON object and returns an array of animation clips.
  32568. *
  32569. * @param {Object} json - The serialized animation clips.
  32570. * @return {Array<AnimationClip>} The parsed animation clips.
  32571. */
  32572. parse( json ) {
  32573. const animations = [];
  32574. for ( let i = 0; i < json.length; i ++ ) {
  32575. const clip = AnimationClip.parse( json[ i ] );
  32576. animations.push( clip );
  32577. }
  32578. return animations;
  32579. }
  32580. }
  32581. /**
  32582. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32583. * Textures are internally loaded via {@link FileLoader}.
  32584. *
  32585. * Derived classes have to implement the `parse()` method which holds the parsing
  32586. * for the respective format.
  32587. *
  32588. * @abstract
  32589. * @augments Loader
  32590. */
  32591. class CompressedTextureLoader extends Loader {
  32592. /**
  32593. * Constructs a new compressed texture loader.
  32594. *
  32595. * @param {LoadingManager} [manager] - The loading manager.
  32596. */
  32597. constructor( manager ) {
  32598. super( manager );
  32599. }
  32600. /**
  32601. * Starts loading from the given URL and passes the loaded compressed texture
  32602. * to the `onLoad()` callback. The method also returns a new texture object which can
  32603. * directly be used for material creation. If you do it this way, the texture
  32604. * may pop up in your scene once the respective loading process is finished.
  32605. *
  32606. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32607. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32608. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32609. * @param {onErrorCallback} onError - Executed when errors occur.
  32610. * @return {CompressedTexture} The compressed texture.
  32611. */
  32612. load( url, onLoad, onProgress, onError ) {
  32613. const scope = this;
  32614. const images = [];
  32615. const texture = new CompressedTexture();
  32616. const loader = new FileLoader( this.manager );
  32617. loader.setPath( this.path );
  32618. loader.setResponseType( 'arraybuffer' );
  32619. loader.setRequestHeader( this.requestHeader );
  32620. loader.setWithCredentials( scope.withCredentials );
  32621. let loaded = 0;
  32622. function loadTexture( i ) {
  32623. loader.load( url[ i ], function ( buffer ) {
  32624. const texDatas = scope.parse( buffer, true );
  32625. images[ i ] = {
  32626. width: texDatas.width,
  32627. height: texDatas.height,
  32628. format: texDatas.format,
  32629. mipmaps: texDatas.mipmaps
  32630. };
  32631. loaded += 1;
  32632. if ( loaded === 6 ) {
  32633. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32634. texture.image = images;
  32635. texture.format = texDatas.format;
  32636. texture.needsUpdate = true;
  32637. if ( onLoad ) onLoad( texture );
  32638. }
  32639. }, onProgress, onError );
  32640. }
  32641. if ( Array.isArray( url ) ) {
  32642. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32643. loadTexture( i );
  32644. }
  32645. } else {
  32646. // compressed cubemap texture stored in a single DDS file
  32647. loader.load( url, function ( buffer ) {
  32648. const texDatas = scope.parse( buffer, true );
  32649. if ( texDatas.isCubemap ) {
  32650. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32651. for ( let f = 0; f < faces; f ++ ) {
  32652. images[ f ] = { mipmaps: [] };
  32653. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32654. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32655. images[ f ].format = texDatas.format;
  32656. images[ f ].width = texDatas.width;
  32657. images[ f ].height = texDatas.height;
  32658. }
  32659. }
  32660. texture.image = images;
  32661. } else {
  32662. texture.image.width = texDatas.width;
  32663. texture.image.height = texDatas.height;
  32664. texture.mipmaps = texDatas.mipmaps;
  32665. }
  32666. if ( texDatas.mipmapCount === 1 ) {
  32667. texture.minFilter = LinearFilter;
  32668. }
  32669. texture.format = texDatas.format;
  32670. texture.needsUpdate = true;
  32671. if ( onLoad ) onLoad( texture );
  32672. }, onProgress, onError );
  32673. }
  32674. return texture;
  32675. }
  32676. }
  32677. const _loading = new WeakMap();
  32678. /**
  32679. * A loader for loading images. The class loads images with the HTML `Image` API.
  32680. *
  32681. * ```js
  32682. * const loader = new THREE.ImageLoader();
  32683. * const image = await loader.loadAsync( 'image.png' );
  32684. * ```
  32685. * Please note that `ImageLoader` has dropped support for progress
  32686. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32687. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  32688. *
  32689. * @augments Loader
  32690. */
  32691. class ImageLoader extends Loader {
  32692. /**
  32693. * Constructs a new image loader.
  32694. *
  32695. * @param {LoadingManager} [manager] - The loading manager.
  32696. */
  32697. constructor( manager ) {
  32698. super( manager );
  32699. }
  32700. /**
  32701. * Starts loading from the given URL and passes the loaded image
  32702. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32703. * directly be used for texture creation. If you do it this way, the texture
  32704. * may pop up in your scene once the respective loading process is finished.
  32705. *
  32706. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32707. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32708. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32709. * @param {onErrorCallback} onError - Executed when errors occur.
  32710. * @return {Image} The image.
  32711. */
  32712. load( url, onLoad, onProgress, onError ) {
  32713. if ( this.path !== undefined ) url = this.path + url;
  32714. url = this.manager.resolveURL( url );
  32715. const scope = this;
  32716. const cached = Cache.get( `image:${url}` );
  32717. if ( cached !== undefined ) {
  32718. if ( cached.complete === true ) {
  32719. scope.manager.itemStart( url );
  32720. setTimeout( function () {
  32721. if ( onLoad ) onLoad( cached );
  32722. scope.manager.itemEnd( url );
  32723. }, 0 );
  32724. } else {
  32725. let arr = _loading.get( cached );
  32726. if ( arr === undefined ) {
  32727. arr = [];
  32728. _loading.set( cached, arr );
  32729. }
  32730. arr.push( { onLoad, onError } );
  32731. }
  32732. return cached;
  32733. }
  32734. const image = createElementNS( 'img' );
  32735. function onImageLoad() {
  32736. removeEventListeners();
  32737. if ( onLoad ) onLoad( this );
  32738. //
  32739. const callbacks = _loading.get( this ) || [];
  32740. for ( let i = 0; i < callbacks.length; i ++ ) {
  32741. const callback = callbacks[ i ];
  32742. if ( callback.onLoad ) callback.onLoad( this );
  32743. }
  32744. _loading.delete( this );
  32745. scope.manager.itemEnd( url );
  32746. }
  32747. function onImageError( event ) {
  32748. removeEventListeners();
  32749. if ( onError ) onError( event );
  32750. Cache.remove( `image:${url}` );
  32751. //
  32752. const callbacks = _loading.get( this ) || [];
  32753. for ( let i = 0; i < callbacks.length; i ++ ) {
  32754. const callback = callbacks[ i ];
  32755. if ( callback.onError ) callback.onError( event );
  32756. }
  32757. _loading.delete( this );
  32758. scope.manager.itemError( url );
  32759. scope.manager.itemEnd( url );
  32760. }
  32761. function removeEventListeners() {
  32762. image.removeEventListener( 'load', onImageLoad, false );
  32763. image.removeEventListener( 'error', onImageError, false );
  32764. }
  32765. image.addEventListener( 'load', onImageLoad, false );
  32766. image.addEventListener( 'error', onImageError, false );
  32767. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32768. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32769. }
  32770. Cache.add( `image:${url}`, image );
  32771. scope.manager.itemStart( url );
  32772. image.src = url;
  32773. return image;
  32774. }
  32775. }
  32776. /**
  32777. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32778. *
  32779. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32780. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32781. * like vertical and horizontal cross, column and row layouts are not supported.
  32782. *
  32783. * Note that, by convention, cube maps are specified in a coordinate system
  32784. * in which positive-x is to the right when looking up the positive-z axis --
  32785. * in other words, using a left-handed coordinate system. Since three.js uses
  32786. * a right-handed coordinate system, environment maps used in three.js will
  32787. * have pos-x and neg-x swapped.
  32788. *
  32789. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32790. * is set to `SRGBColorSpace` by default.
  32791. *
  32792. * ```js
  32793. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32794. * const cubeTexture = await loader.loadAsync( [
  32795. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32796. * ] );
  32797. * scene.background = cubeTexture;
  32798. * ```
  32799. *
  32800. * @augments Loader
  32801. */
  32802. class CubeTextureLoader extends Loader {
  32803. /**
  32804. * Constructs a new cube texture loader.
  32805. *
  32806. * @param {LoadingManager} [manager] - The loading manager.
  32807. */
  32808. constructor( manager ) {
  32809. super( manager );
  32810. }
  32811. /**
  32812. * Starts loading from the given URL and pass the fully loaded cube texture
  32813. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32814. * directly be used for material creation. If you do it this way, the cube texture
  32815. * may pop up in your scene once the respective loading process is finished.
  32816. *
  32817. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32818. * cube texture. The urls should be specified in the following order: pos-x,
  32819. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32820. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32821. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32822. * @param {onErrorCallback} onError - Executed when errors occur.
  32823. * @return {CubeTexture} The cube texture.
  32824. */
  32825. load( urls, onLoad, onProgress, onError ) {
  32826. const texture = new CubeTexture();
  32827. texture.colorSpace = SRGBColorSpace;
  32828. const loader = new ImageLoader( this.manager );
  32829. loader.setCrossOrigin( this.crossOrigin );
  32830. loader.setPath( this.path );
  32831. let loaded = 0;
  32832. function loadTexture( i ) {
  32833. loader.load( urls[ i ], function ( image ) {
  32834. texture.images[ i ] = image;
  32835. loaded ++;
  32836. if ( loaded === 6 ) {
  32837. texture.needsUpdate = true;
  32838. if ( onLoad ) onLoad( texture );
  32839. }
  32840. }, undefined, onError );
  32841. }
  32842. for ( let i = 0; i < urls.length; ++ i ) {
  32843. loadTexture( i );
  32844. }
  32845. return texture;
  32846. }
  32847. }
  32848. /**
  32849. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32850. * Textures are internally loaded via {@link FileLoader}.
  32851. *
  32852. * Derived classes have to implement the `parse()` method which holds the parsing
  32853. * for the respective format.
  32854. *
  32855. * @abstract
  32856. * @augments Loader
  32857. */
  32858. class DataTextureLoader extends Loader {
  32859. /**
  32860. * Constructs a new data texture loader.
  32861. *
  32862. * @param {LoadingManager} [manager] - The loading manager.
  32863. */
  32864. constructor( manager ) {
  32865. super( manager );
  32866. }
  32867. /**
  32868. * Starts loading from the given URL and passes the loaded data texture
  32869. * to the `onLoad()` callback. The method also returns a new texture object which can
  32870. * directly be used for material creation. If you do it this way, the texture
  32871. * may pop up in your scene once the respective loading process is finished.
  32872. *
  32873. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32874. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32875. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32876. * @param {onErrorCallback} onError - Executed when errors occur.
  32877. * @return {DataTexture} The data texture.
  32878. */
  32879. load( url, onLoad, onProgress, onError ) {
  32880. const scope = this;
  32881. const texture = new DataTexture();
  32882. const loader = new FileLoader( this.manager );
  32883. loader.setResponseType( 'arraybuffer' );
  32884. loader.setRequestHeader( this.requestHeader );
  32885. loader.setPath( this.path );
  32886. loader.setWithCredentials( scope.withCredentials );
  32887. loader.load( url, function ( buffer ) {
  32888. let texData;
  32889. try {
  32890. texData = scope.parse( buffer );
  32891. } catch ( e ) {
  32892. if ( onError !== undefined ) {
  32893. onError( e );
  32894. } else {
  32895. error( e );
  32896. }
  32897. return;
  32898. }
  32899. if ( texData.image !== undefined ) {
  32900. texture.image = texData.image;
  32901. } else if ( texData.data !== undefined ) {
  32902. texture.image.width = texData.width;
  32903. texture.image.height = texData.height;
  32904. texture.image.data = texData.data;
  32905. }
  32906. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32907. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32908. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32909. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32910. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32911. if ( texData.colorSpace !== undefined ) {
  32912. texture.colorSpace = texData.colorSpace;
  32913. }
  32914. if ( texData.flipY !== undefined ) {
  32915. texture.flipY = texData.flipY;
  32916. }
  32917. if ( texData.format !== undefined ) {
  32918. texture.format = texData.format;
  32919. }
  32920. if ( texData.type !== undefined ) {
  32921. texture.type = texData.type;
  32922. }
  32923. if ( texData.mipmaps !== undefined ) {
  32924. texture.mipmaps = texData.mipmaps;
  32925. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32926. }
  32927. if ( texData.mipmapCount === 1 ) {
  32928. texture.minFilter = LinearFilter;
  32929. }
  32930. if ( texData.generateMipmaps !== undefined ) {
  32931. texture.generateMipmaps = texData.generateMipmaps;
  32932. }
  32933. texture.needsUpdate = true;
  32934. if ( onLoad ) onLoad( texture, texData );
  32935. }, onProgress, onError );
  32936. return texture;
  32937. }
  32938. }
  32939. /**
  32940. * Class for loading textures. Images are internally
  32941. * loaded via {@link ImageLoader}.
  32942. *
  32943. * ```js
  32944. * const loader = new THREE.TextureLoader();
  32945. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32946. *
  32947. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32948. * ```
  32949. * Please note that `TextureLoader` has dropped support for progress
  32950. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32951. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  32952. *
  32953. * @augments Loader
  32954. */
  32955. class TextureLoader extends Loader {
  32956. /**
  32957. * Constructs a new texture loader.
  32958. *
  32959. * @param {LoadingManager} [manager] - The loading manager.
  32960. */
  32961. constructor( manager ) {
  32962. super( manager );
  32963. }
  32964. /**
  32965. * Starts loading from the given URL and pass the fully loaded texture
  32966. * to the `onLoad()` callback. The method also returns a new texture object which can
  32967. * directly be used for material creation. If you do it this way, the texture
  32968. * may pop up in your scene once the respective loading process is finished.
  32969. *
  32970. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32971. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32972. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32973. * @param {onErrorCallback} onError - Executed when errors occur.
  32974. * @return {Texture} The texture.
  32975. */
  32976. load( url, onLoad, onProgress, onError ) {
  32977. const texture = new Texture();
  32978. const loader = new ImageLoader( this.manager );
  32979. loader.setCrossOrigin( this.crossOrigin );
  32980. loader.setPath( this.path );
  32981. loader.load( url, function ( image ) {
  32982. texture.image = image;
  32983. texture.needsUpdate = true;
  32984. if ( onLoad !== undefined ) {
  32985. onLoad( texture );
  32986. }
  32987. }, onProgress, onError );
  32988. return texture;
  32989. }
  32990. }
  32991. /**
  32992. * Abstract base class for lights - all other light types inherit the
  32993. * properties and methods described here.
  32994. *
  32995. * @abstract
  32996. * @augments Object3D
  32997. */
  32998. class Light extends Object3D {
  32999. /**
  33000. * Constructs a new light.
  33001. *
  33002. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33003. * @param {number} [intensity=1] - The light's strength/intensity.
  33004. */
  33005. constructor( color, intensity = 1 ) {
  33006. super();
  33007. /**
  33008. * This flag can be used for type testing.
  33009. *
  33010. * @type {boolean}
  33011. * @readonly
  33012. * @default true
  33013. */
  33014. this.isLight = true;
  33015. this.type = 'Light';
  33016. /**
  33017. * The light's color.
  33018. *
  33019. * @type {Color}
  33020. */
  33021. this.color = new Color( color );
  33022. /**
  33023. * The light's intensity.
  33024. *
  33025. * @type {number}
  33026. * @default 1
  33027. */
  33028. this.intensity = intensity;
  33029. }
  33030. /**
  33031. * Frees the GPU-related resources allocated by this instance. Call this
  33032. * method whenever this instance is no longer used in your app.
  33033. */
  33034. dispose() {
  33035. this.dispatchEvent( { type: 'dispose' } );
  33036. }
  33037. copy( source, recursive ) {
  33038. super.copy( source, recursive );
  33039. this.color.copy( source.color );
  33040. this.intensity = source.intensity;
  33041. return this;
  33042. }
  33043. toJSON( meta ) {
  33044. const data = super.toJSON( meta );
  33045. data.object.color = this.color.getHex();
  33046. data.object.intensity = this.intensity;
  33047. return data;
  33048. }
  33049. }
  33050. /**
  33051. * A light source positioned directly above the scene, with color fading from
  33052. * the sky color to the ground color.
  33053. *
  33054. * This light cannot be used to cast shadows.
  33055. *
  33056. * ```js
  33057. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33058. * scene.add( light );
  33059. * ```
  33060. *
  33061. * @augments Light
  33062. */
  33063. class HemisphereLight extends Light {
  33064. /**
  33065. * Constructs a new hemisphere light.
  33066. *
  33067. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33068. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33069. * @param {number} [intensity=1] - The light's strength/intensity.
  33070. */
  33071. constructor( skyColor, groundColor, intensity ) {
  33072. super( skyColor, intensity );
  33073. /**
  33074. * This flag can be used for type testing.
  33075. *
  33076. * @type {boolean}
  33077. * @readonly
  33078. * @default true
  33079. */
  33080. this.isHemisphereLight = true;
  33081. this.type = 'HemisphereLight';
  33082. this.position.copy( Object3D.DEFAULT_UP );
  33083. this.updateMatrix();
  33084. /**
  33085. * The light's ground color.
  33086. *
  33087. * @type {Color}
  33088. */
  33089. this.groundColor = new Color( groundColor );
  33090. }
  33091. copy( source, recursive ) {
  33092. super.copy( source, recursive );
  33093. this.groundColor.copy( source.groundColor );
  33094. return this;
  33095. }
  33096. toJSON( meta ) {
  33097. const data = super.toJSON( meta );
  33098. data.object.groundColor = this.groundColor.getHex();
  33099. return data;
  33100. }
  33101. }
  33102. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33103. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33104. const _lookTarget = /*@__PURE__*/ new Vector3();
  33105. /**
  33106. * Abstract base class for light shadow classes. These classes
  33107. * represent the shadow configuration for different light types.
  33108. *
  33109. * @abstract
  33110. */
  33111. class LightShadow {
  33112. /**
  33113. * Constructs a new light shadow.
  33114. *
  33115. * @param {Camera} camera - The light's view of the world.
  33116. */
  33117. constructor( camera ) {
  33118. /**
  33119. * The light's view of the world.
  33120. *
  33121. * @type {Camera}
  33122. */
  33123. this.camera = camera;
  33124. /**
  33125. * The intensity of the shadow. The default is `1`.
  33126. * Valid values are in the range `[0, 1]`.
  33127. *
  33128. * @type {number}
  33129. * @default 1
  33130. */
  33131. this.intensity = 1;
  33132. /**
  33133. * Shadow map bias, how much to add or subtract from the normalized depth
  33134. * when deciding whether a surface is in shadow.
  33135. *
  33136. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33137. * may help reduce artifacts in shadows.
  33138. *
  33139. * @type {number}
  33140. * @default 0
  33141. */
  33142. this.bias = 0;
  33143. /**
  33144. * A node version of `bias`. Only supported with `WebGPURenderer`.
  33145. *
  33146. * If a bias node is defined, `bias` has no effect.
  33147. *
  33148. * @type {?Node<float>}
  33149. * @default null
  33150. */
  33151. this.biasNode = null;
  33152. /**
  33153. * Defines how much the position used to query the shadow map is offset along
  33154. * the object normal. The default is `0`. Increasing this value can be used to
  33155. * reduce shadow acne especially in large scenes where light shines onto
  33156. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33157. *
  33158. * @type {number}
  33159. * @default 0
  33160. */
  33161. this.normalBias = 0;
  33162. /**
  33163. * Setting this to values greater than 1 will blur the edges of the shadow.
  33164. * High values will cause unwanted banding effects in the shadows - a greater
  33165. * map size will allow for a higher value to be used here before these effects
  33166. * become visible.
  33167. *
  33168. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33169. *
  33170. * @type {number}
  33171. * @default 1
  33172. */
  33173. this.radius = 1;
  33174. /**
  33175. * The amount of samples to use when blurring a VSM shadow map.
  33176. *
  33177. * @type {number}
  33178. * @default 8
  33179. */
  33180. this.blurSamples = 8;
  33181. /**
  33182. * Defines the width and height of the shadow map. Higher values give better quality
  33183. * shadows at the cost of computation time. Values must be powers of two.
  33184. *
  33185. * @type {Vector2}
  33186. * @default (512,512)
  33187. */
  33188. this.mapSize = new Vector2( 512, 512 );
  33189. /**
  33190. * The type of shadow texture. The default is `UnsignedByteType`.
  33191. *
  33192. * @type {number}
  33193. * @default UnsignedByteType
  33194. */
  33195. this.mapType = UnsignedByteType;
  33196. /**
  33197. * The depth map generated using the internal camera; a location beyond a
  33198. * pixel's depth is in shadow. Computed internally during rendering.
  33199. *
  33200. * @type {?RenderTarget}
  33201. * @default null
  33202. */
  33203. this.map = null;
  33204. /**
  33205. * The distribution map generated using the internal camera; an occlusion is
  33206. * calculated based on the distribution of depths. Computed internally during
  33207. * rendering.
  33208. *
  33209. * @type {?RenderTarget}
  33210. * @default null
  33211. */
  33212. this.mapPass = null;
  33213. /**
  33214. * Model to shadow camera space, to compute location and depth in shadow map.
  33215. * This is computed internally during rendering.
  33216. *
  33217. * @type {Matrix4}
  33218. */
  33219. this.matrix = new Matrix4();
  33220. /**
  33221. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33222. * lighting / shadows, you may set this to `false`.
  33223. *
  33224. * @type {boolean}
  33225. * @default true
  33226. */
  33227. this.autoUpdate = true;
  33228. /**
  33229. * When set to `true`, shadow maps will be updated in the next `render` call.
  33230. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33231. * set this property to `true` and then make a render call to update the light's shadow.
  33232. *
  33233. * @type {boolean}
  33234. * @default false
  33235. */
  33236. this.needsUpdate = false;
  33237. this._frustum = new Frustum();
  33238. this._frameExtents = new Vector2( 1, 1 );
  33239. this._viewportCount = 1;
  33240. this._viewports = [
  33241. new Vector4( 0, 0, 1, 1 )
  33242. ];
  33243. }
  33244. /**
  33245. * Used internally by the renderer to get the number of viewports that need
  33246. * to be rendered for this shadow.
  33247. *
  33248. * @return {number} The viewport count.
  33249. */
  33250. getViewportCount() {
  33251. return this._viewportCount;
  33252. }
  33253. /**
  33254. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33255. *
  33256. * @return {Frustum} The shadow camera frustum.
  33257. */
  33258. getFrustum() {
  33259. return this._frustum;
  33260. }
  33261. /**
  33262. * Update the matrices for the camera and shadow, used internally by the renderer.
  33263. *
  33264. * @param {Light} light - The light for which the shadow is being rendered.
  33265. */
  33266. updateMatrices( light ) {
  33267. const shadowCamera = this.camera;
  33268. const shadowMatrix = this.matrix;
  33269. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33270. shadowCamera.position.copy( _lightPositionWorld );
  33271. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  33272. shadowCamera.lookAt( _lookTarget );
  33273. shadowCamera.updateMatrixWorld();
  33274. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33275. this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33276. if ( shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth ) {
  33277. shadowMatrix.set(
  33278. 0.5, 0.0, 0.0, 0.5,
  33279. 0.0, 0.5, 0.0, 0.5,
  33280. 0.0, 0.0, 1.0, 0.0, // Identity Z (preserving the correct [0, 1] range from the projection matrix)
  33281. 0.0, 0.0, 0.0, 1.0
  33282. );
  33283. } else {
  33284. shadowMatrix.set(
  33285. 0.5, 0.0, 0.0, 0.5,
  33286. 0.0, 0.5, 0.0, 0.5,
  33287. 0.0, 0.0, 0.5, 0.5,
  33288. 0.0, 0.0, 0.0, 1.0
  33289. );
  33290. }
  33291. shadowMatrix.multiply( _projScreenMatrix );
  33292. }
  33293. /**
  33294. * Returns a viewport definition for the given viewport index.
  33295. *
  33296. * @param {number} viewportIndex - The viewport index.
  33297. * @return {Vector4} The viewport.
  33298. */
  33299. getViewport( viewportIndex ) {
  33300. return this._viewports[ viewportIndex ];
  33301. }
  33302. /**
  33303. * Returns the frame extends.
  33304. *
  33305. * @return {Vector2} The frame extends.
  33306. */
  33307. getFrameExtents() {
  33308. return this._frameExtents;
  33309. }
  33310. /**
  33311. * Frees the GPU-related resources allocated by this instance. Call this
  33312. * method whenever this instance is no longer used in your app.
  33313. */
  33314. dispose() {
  33315. if ( this.map ) {
  33316. this.map.dispose();
  33317. }
  33318. if ( this.mapPass ) {
  33319. this.mapPass.dispose();
  33320. }
  33321. }
  33322. /**
  33323. * Copies the values of the given light shadow instance to this instance.
  33324. *
  33325. * @param {LightShadow} source - The light shadow to copy.
  33326. * @return {LightShadow} A reference to this light shadow instance.
  33327. */
  33328. copy( source ) {
  33329. this.camera = source.camera.clone();
  33330. this.intensity = source.intensity;
  33331. this.bias = source.bias;
  33332. this.radius = source.radius;
  33333. this.autoUpdate = source.autoUpdate;
  33334. this.needsUpdate = source.needsUpdate;
  33335. this.normalBias = source.normalBias;
  33336. this.blurSamples = source.blurSamples;
  33337. this.mapSize.copy( source.mapSize );
  33338. this.biasNode = source.biasNode;
  33339. return this;
  33340. }
  33341. /**
  33342. * Returns a new light shadow instance with copied values from this instance.
  33343. *
  33344. * @return {LightShadow} A clone of this instance.
  33345. */
  33346. clone() {
  33347. return new this.constructor().copy( this );
  33348. }
  33349. /**
  33350. * Serializes the light shadow into JSON.
  33351. *
  33352. * @return {Object} A JSON object representing the serialized light shadow.
  33353. * @see {@link ObjectLoader#parse}
  33354. */
  33355. toJSON() {
  33356. const object = {};
  33357. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33358. if ( this.bias !== 0 ) object.bias = this.bias;
  33359. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33360. if ( this.radius !== 1 ) object.radius = this.radius;
  33361. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33362. object.camera = this.camera.toJSON( false ).object;
  33363. delete object.camera.matrix;
  33364. return object;
  33365. }
  33366. }
  33367. const _position$2 = /*@__PURE__*/ new Vector3();
  33368. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  33369. const _scale$2 = /*@__PURE__*/ new Vector3();
  33370. /**
  33371. * Abstract base class for cameras. This class should always be inherited
  33372. * when you build a new camera.
  33373. *
  33374. * @abstract
  33375. * @augments Object3D
  33376. */
  33377. class Camera extends Object3D {
  33378. /**
  33379. * Constructs a new camera.
  33380. */
  33381. constructor() {
  33382. super();
  33383. /**
  33384. * This flag can be used for type testing.
  33385. *
  33386. * @type {boolean}
  33387. * @readonly
  33388. * @default true
  33389. */
  33390. this.isCamera = true;
  33391. this.type = 'Camera';
  33392. /**
  33393. * The inverse of the camera's world matrix.
  33394. *
  33395. * @type {Matrix4}
  33396. */
  33397. this.matrixWorldInverse = new Matrix4();
  33398. /**
  33399. * The camera's projection matrix.
  33400. *
  33401. * @type {Matrix4}
  33402. */
  33403. this.projectionMatrix = new Matrix4();
  33404. /**
  33405. * The inverse of the camera's projection matrix.
  33406. *
  33407. * @type {Matrix4}
  33408. */
  33409. this.projectionMatrixInverse = new Matrix4();
  33410. /**
  33411. * The coordinate system in which the camera is used.
  33412. *
  33413. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  33414. */
  33415. this.coordinateSystem = WebGLCoordinateSystem;
  33416. this._reversedDepth = false;
  33417. }
  33418. /**
  33419. * The flag that indicates whether the camera uses a reversed depth buffer.
  33420. *
  33421. * @type {boolean}
  33422. * @default false
  33423. */
  33424. get reversedDepth() {
  33425. return this._reversedDepth;
  33426. }
  33427. copy( source, recursive ) {
  33428. super.copy( source, recursive );
  33429. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  33430. this.projectionMatrix.copy( source.projectionMatrix );
  33431. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  33432. this.coordinateSystem = source.coordinateSystem;
  33433. return this;
  33434. }
  33435. /**
  33436. * Returns a vector representing the ("look") direction of the 3D object in world space.
  33437. *
  33438. * This method is overwritten since cameras have a different forward vector compared to other
  33439. * 3D objects. A camera looks down its local, negative z-axis by default.
  33440. *
  33441. * @param {Vector3} target - The target vector the result is stored to.
  33442. * @return {Vector3} The 3D object's direction in world space.
  33443. */
  33444. getWorldDirection( target ) {
  33445. return super.getWorldDirection( target ).negate();
  33446. }
  33447. updateMatrixWorld( force ) {
  33448. super.updateMatrixWorld( force );
  33449. // exclude scale from view matrix to be glTF conform
  33450. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33451. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33452. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33453. } else {
  33454. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33455. }
  33456. }
  33457. updateWorldMatrix( updateParents, updateChildren ) {
  33458. super.updateWorldMatrix( updateParents, updateChildren );
  33459. // exclude scale from view matrix to be glTF conform
  33460. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33461. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33462. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33463. } else {
  33464. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33465. }
  33466. }
  33467. clone() {
  33468. return new this.constructor().copy( this );
  33469. }
  33470. }
  33471. const _v3$1 = /*@__PURE__*/ new Vector3();
  33472. const _minTarget = /*@__PURE__*/ new Vector2();
  33473. const _maxTarget = /*@__PURE__*/ new Vector2();
  33474. /**
  33475. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  33476. *
  33477. * This projection mode is designed to mimic the way the human eye sees. It
  33478. * is the most common projection mode used for rendering a 3D scene.
  33479. *
  33480. * ```js
  33481. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  33482. * scene.add( camera );
  33483. * ```
  33484. *
  33485. * @augments Camera
  33486. */
  33487. class PerspectiveCamera extends Camera {
  33488. /**
  33489. * Constructs a new perspective camera.
  33490. *
  33491. * @param {number} [fov=50] - The vertical field of view.
  33492. * @param {number} [aspect=1] - The aspect ratio.
  33493. * @param {number} [near=0.1] - The camera's near plane.
  33494. * @param {number} [far=2000] - The camera's far plane.
  33495. */
  33496. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  33497. super();
  33498. /**
  33499. * This flag can be used for type testing.
  33500. *
  33501. * @type {boolean}
  33502. * @readonly
  33503. * @default true
  33504. */
  33505. this.isPerspectiveCamera = true;
  33506. this.type = 'PerspectiveCamera';
  33507. /**
  33508. * The vertical field of view, from bottom to top of view,
  33509. * in degrees.
  33510. *
  33511. * @type {number}
  33512. * @default 50
  33513. */
  33514. this.fov = fov;
  33515. /**
  33516. * The zoom factor of the camera.
  33517. *
  33518. * @type {number}
  33519. * @default 1
  33520. */
  33521. this.zoom = 1;
  33522. /**
  33523. * The camera's near plane. The valid range is greater than `0`
  33524. * and less than the current value of {@link PerspectiveCamera#far}.
  33525. *
  33526. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  33527. * valid value for a perspective camera's near plane.
  33528. *
  33529. * @type {number}
  33530. * @default 0.1
  33531. */
  33532. this.near = near;
  33533. /**
  33534. * The camera's far plane. Must be greater than the
  33535. * current value of {@link PerspectiveCamera#near}.
  33536. *
  33537. * @type {number}
  33538. * @default 2000
  33539. */
  33540. this.far = far;
  33541. /**
  33542. * Object distance used for stereoscopy and depth-of-field effects. This
  33543. * parameter does not influence the projection matrix unless a
  33544. * {@link StereoCamera} is being used.
  33545. *
  33546. * @type {number}
  33547. * @default 10
  33548. */
  33549. this.focus = 10;
  33550. /**
  33551. * The aspect ratio, usually the canvas width / canvas height.
  33552. *
  33553. * @type {number}
  33554. * @default 1
  33555. */
  33556. this.aspect = aspect;
  33557. /**
  33558. * Represents the frustum window specification. This property should not be edited
  33559. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33560. *
  33561. * @type {?Object}
  33562. * @default null
  33563. */
  33564. this.view = null;
  33565. /**
  33566. * Film size used for the larger axis. Default is `35` (millimeters). This
  33567. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  33568. * is set to a nonzero value.
  33569. *
  33570. * @type {number}
  33571. * @default 35
  33572. */
  33573. this.filmGauge = 35;
  33574. /**
  33575. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  33576. *
  33577. * @type {number}
  33578. * @default 0
  33579. */
  33580. this.filmOffset = 0;
  33581. this.updateProjectionMatrix();
  33582. }
  33583. copy( source, recursive ) {
  33584. super.copy( source, recursive );
  33585. this.fov = source.fov;
  33586. this.zoom = source.zoom;
  33587. this.near = source.near;
  33588. this.far = source.far;
  33589. this.focus = source.focus;
  33590. this.aspect = source.aspect;
  33591. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33592. this.filmGauge = source.filmGauge;
  33593. this.filmOffset = source.filmOffset;
  33594. return this;
  33595. }
  33596. /**
  33597. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  33598. *
  33599. * The default film gauge is 35, so that the focal length can be specified for
  33600. * a 35mm (full frame) camera.
  33601. *
  33602. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  33603. */
  33604. setFocalLength( focalLength ) {
  33605. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  33606. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  33607. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  33608. this.updateProjectionMatrix();
  33609. }
  33610. /**
  33611. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  33612. * {@link PerspectiveCamera#filmGauge}.
  33613. *
  33614. * @return {number} The computed focal length.
  33615. */
  33616. getFocalLength() {
  33617. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  33618. return 0.5 * this.getFilmHeight() / vExtentSlope;
  33619. }
  33620. /**
  33621. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  33622. *
  33623. * @return {number} The effective FOV.
  33624. */
  33625. getEffectiveFOV() {
  33626. return RAD2DEG * 2 * Math.atan(
  33627. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  33628. }
  33629. /**
  33630. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  33631. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  33632. *
  33633. * @return {number} The film width.
  33634. */
  33635. getFilmWidth() {
  33636. // film not completely covered in portrait format (aspect < 1)
  33637. return this.filmGauge * Math.min( this.aspect, 1 );
  33638. }
  33639. /**
  33640. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  33641. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  33642. *
  33643. * @return {number} The film width.
  33644. */
  33645. getFilmHeight() {
  33646. // film not completely covered in landscape format (aspect > 1)
  33647. return this.filmGauge / Math.max( this.aspect, 1 );
  33648. }
  33649. /**
  33650. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  33651. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  33652. *
  33653. * @param {number} distance - The viewing distance.
  33654. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  33655. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  33656. */
  33657. getViewBounds( distance, minTarget, maxTarget ) {
  33658. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  33659. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  33660. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  33661. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  33662. }
  33663. /**
  33664. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  33665. *
  33666. * @param {number} distance - The viewing distance.
  33667. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  33668. * @returns {Vector2} The view size.
  33669. */
  33670. getViewSize( distance, target ) {
  33671. this.getViewBounds( distance, _minTarget, _maxTarget );
  33672. return target.subVectors( _maxTarget, _minTarget );
  33673. }
  33674. /**
  33675. * Sets an offset in a larger frustum. This is useful for multi-window or
  33676. * multi-monitor/multi-machine setups.
  33677. *
  33678. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  33679. * the monitors are in grid like this
  33680. *```
  33681. * +---+---+---+
  33682. * | A | B | C |
  33683. * +---+---+---+
  33684. * | D | E | F |
  33685. * +---+---+---+
  33686. *```
  33687. * then for each monitor you would call it like this:
  33688. *```js
  33689. * const w = 1920;
  33690. * const h = 1080;
  33691. * const fullWidth = w * 3;
  33692. * const fullHeight = h * 2;
  33693. *
  33694. * // --A--
  33695. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  33696. * // --B--
  33697. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  33698. * // --C--
  33699. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  33700. * // --D--
  33701. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  33702. * // --E--
  33703. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  33704. * // --F--
  33705. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  33706. * ```
  33707. *
  33708. * Note there is no reason monitors have to be the same size or in a grid.
  33709. *
  33710. * @param {number} fullWidth - The full width of multiview setup.
  33711. * @param {number} fullHeight - The full height of multiview setup.
  33712. * @param {number} x - The horizontal offset of the subcamera.
  33713. * @param {number} y - The vertical offset of the subcamera.
  33714. * @param {number} width - The width of subcamera.
  33715. * @param {number} height - The height of subcamera.
  33716. */
  33717. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33718. this.aspect = fullWidth / fullHeight;
  33719. if ( this.view === null ) {
  33720. this.view = {
  33721. enabled: true,
  33722. fullWidth: 1,
  33723. fullHeight: 1,
  33724. offsetX: 0,
  33725. offsetY: 0,
  33726. width: 1,
  33727. height: 1
  33728. };
  33729. }
  33730. this.view.enabled = true;
  33731. this.view.fullWidth = fullWidth;
  33732. this.view.fullHeight = fullHeight;
  33733. this.view.offsetX = x;
  33734. this.view.offsetY = y;
  33735. this.view.width = width;
  33736. this.view.height = height;
  33737. this.updateProjectionMatrix();
  33738. }
  33739. /**
  33740. * Removes the view offset from the projection matrix.
  33741. */
  33742. clearViewOffset() {
  33743. if ( this.view !== null ) {
  33744. this.view.enabled = false;
  33745. }
  33746. this.updateProjectionMatrix();
  33747. }
  33748. /**
  33749. * Updates the camera's projection matrix. Must be called after any change of
  33750. * camera properties.
  33751. */
  33752. updateProjectionMatrix() {
  33753. const near = this.near;
  33754. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  33755. let height = 2 * top;
  33756. let width = this.aspect * height;
  33757. let left = -0.5 * width;
  33758. const view = this.view;
  33759. if ( this.view !== null && this.view.enabled ) {
  33760. const fullWidth = view.fullWidth,
  33761. fullHeight = view.fullHeight;
  33762. left += view.offsetX * width / fullWidth;
  33763. top -= view.offsetY * height / fullHeight;
  33764. width *= view.width / fullWidth;
  33765. height *= view.height / fullHeight;
  33766. }
  33767. const skew = this.filmOffset;
  33768. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  33769. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  33770. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33771. }
  33772. toJSON( meta ) {
  33773. const data = super.toJSON( meta );
  33774. data.object.fov = this.fov;
  33775. data.object.zoom = this.zoom;
  33776. data.object.near = this.near;
  33777. data.object.far = this.far;
  33778. data.object.focus = this.focus;
  33779. data.object.aspect = this.aspect;
  33780. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33781. data.object.filmGauge = this.filmGauge;
  33782. data.object.filmOffset = this.filmOffset;
  33783. return data;
  33784. }
  33785. }
  33786. /**
  33787. * Represents the shadow configuration of directional lights.
  33788. *
  33789. * @augments LightShadow
  33790. */
  33791. class SpotLightShadow extends LightShadow {
  33792. /**
  33793. * Constructs a new spot light shadow.
  33794. */
  33795. constructor() {
  33796. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33797. /**
  33798. * This flag can be used for type testing.
  33799. *
  33800. * @type {boolean}
  33801. * @readonly
  33802. * @default true
  33803. */
  33804. this.isSpotLightShadow = true;
  33805. /**
  33806. * Used to focus the shadow camera. The camera's field of view is set as a
  33807. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33808. *
  33809. * @type {number}
  33810. * @default 1
  33811. */
  33812. this.focus = 1;
  33813. /**
  33814. * Texture aspect ratio.
  33815. *
  33816. * @type {number}
  33817. * @default 1
  33818. */
  33819. this.aspect = 1;
  33820. }
  33821. updateMatrices( light ) {
  33822. const camera = this.camera;
  33823. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33824. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33825. const far = light.distance || camera.far;
  33826. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33827. camera.fov = fov;
  33828. camera.aspect = aspect;
  33829. camera.far = far;
  33830. camera.updateProjectionMatrix();
  33831. }
  33832. super.updateMatrices( light );
  33833. }
  33834. copy( source ) {
  33835. super.copy( source );
  33836. this.focus = source.focus;
  33837. return this;
  33838. }
  33839. }
  33840. /**
  33841. * This light gets emitted from a single point in one direction, along a cone
  33842. * that increases in size the further from the light it gets.
  33843. *
  33844. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33845. *
  33846. * ```js
  33847. * // white spotlight shining from the side, modulated by a texture
  33848. * const spotLight = new THREE.SpotLight( 0xffffff );
  33849. * spotLight.position.set( 100, 1000, 100 );
  33850. * spotLight.map = new THREE.TextureLoader().load( url );
  33851. *
  33852. * spotLight.castShadow = true;
  33853. * spotLight.shadow.mapSize.width = 1024;
  33854. * spotLight.shadow.mapSize.height = 1024;
  33855. * spotLight.shadow.camera.near = 500;
  33856. * spotLight.shadow.camera.far = 4000;
  33857. * spotLight.shadow.camera.fov = 30;s
  33858. * ```
  33859. *
  33860. * @augments Light
  33861. */
  33862. class SpotLight extends Light {
  33863. /**
  33864. * Constructs a new spot light.
  33865. *
  33866. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33867. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33868. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33869. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33870. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33871. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33872. */
  33873. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33874. super( color, intensity );
  33875. /**
  33876. * This flag can be used for type testing.
  33877. *
  33878. * @type {boolean}
  33879. * @readonly
  33880. * @default true
  33881. */
  33882. this.isSpotLight = true;
  33883. this.type = 'SpotLight';
  33884. this.position.copy( Object3D.DEFAULT_UP );
  33885. this.updateMatrix();
  33886. /**
  33887. * The spot light points from its position to the
  33888. * target's position.
  33889. *
  33890. * For the target's position to be changed to anything other
  33891. * than the default, it must be added to the scene.
  33892. *
  33893. * It is also possible to set the target to be another 3D object
  33894. * in the scene. The light will now track the target object.
  33895. *
  33896. * @type {Object3D}
  33897. */
  33898. this.target = new Object3D();
  33899. /**
  33900. * Maximum range of the light. `0` means no limit.
  33901. *
  33902. * @type {number}
  33903. * @default 0
  33904. */
  33905. this.distance = distance;
  33906. /**
  33907. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33908. *
  33909. * @type {number}
  33910. * @default Math.PI/3
  33911. */
  33912. this.angle = angle;
  33913. /**
  33914. * Percent of the spotlight cone that is attenuated due to penumbra.
  33915. * Value range is `[0,1]`.
  33916. *
  33917. * @type {number}
  33918. * @default 0
  33919. */
  33920. this.penumbra = penumbra;
  33921. /**
  33922. * The amount the light dims along the distance of the light. In context of
  33923. * physically-correct rendering the default value should not be changed.
  33924. *
  33925. * @type {number}
  33926. * @default 2
  33927. */
  33928. this.decay = decay;
  33929. /**
  33930. * A texture used to modulate the color of the light. The spot light
  33931. * color is mixed with the RGB value of this texture, with a ratio
  33932. * corresponding to its alpha value. The cookie-like masking effect is
  33933. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33934. *
  33935. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33936. *
  33937. * @type {?Texture}
  33938. * @default null
  33939. */
  33940. this.map = null;
  33941. /**
  33942. * This property holds the light's shadow configuration.
  33943. *
  33944. * @type {SpotLightShadow}
  33945. */
  33946. this.shadow = new SpotLightShadow();
  33947. }
  33948. /**
  33949. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33950. * Changing the power will also change the light's intensity.
  33951. *
  33952. * @type {number}
  33953. */
  33954. get power() {
  33955. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33956. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33957. return this.intensity * Math.PI;
  33958. }
  33959. set power( power ) {
  33960. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33961. this.intensity = power / Math.PI;
  33962. }
  33963. dispose() {
  33964. super.dispose();
  33965. this.shadow.dispose();
  33966. }
  33967. copy( source, recursive ) {
  33968. super.copy( source, recursive );
  33969. this.distance = source.distance;
  33970. this.angle = source.angle;
  33971. this.penumbra = source.penumbra;
  33972. this.decay = source.decay;
  33973. this.target = source.target.clone();
  33974. this.map = source.map;
  33975. this.shadow = source.shadow.clone();
  33976. return this;
  33977. }
  33978. toJSON( meta ) {
  33979. const data = super.toJSON( meta );
  33980. data.object.distance = this.distance;
  33981. data.object.angle = this.angle;
  33982. data.object.decay = this.decay;
  33983. data.object.penumbra = this.penumbra;
  33984. data.object.target = this.target.uuid;
  33985. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33986. data.object.shadow = this.shadow.toJSON();
  33987. return data;
  33988. }
  33989. }
  33990. /**
  33991. * Represents the shadow configuration of point lights.
  33992. *
  33993. * @augments LightShadow
  33994. */
  33995. class PointLightShadow extends LightShadow {
  33996. /**
  33997. * Constructs a new point light shadow.
  33998. */
  33999. constructor() {
  34000. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  34001. /**
  34002. * This flag can be used for type testing.
  34003. *
  34004. * @type {boolean}
  34005. * @readonly
  34006. * @default true
  34007. */
  34008. this.isPointLightShadow = true;
  34009. }
  34010. }
  34011. /**
  34012. * A light that gets emitted from a single point in all directions. A common
  34013. * use case for this is to replicate the light emitted from a bare
  34014. * lightbulb.
  34015. *
  34016. * This light can cast shadows - see the {@link PointLightShadow} for details.
  34017. *
  34018. * ```js
  34019. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  34020. * light.position.set( 50, 50, 50 );
  34021. * scene.add( light );
  34022. * ```
  34023. *
  34024. * @augments Light
  34025. */
  34026. class PointLight extends Light {
  34027. /**
  34028. * Constructs a new point light.
  34029. *
  34030. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34031. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  34032. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  34033. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  34034. */
  34035. constructor( color, intensity, distance = 0, decay = 2 ) {
  34036. super( color, intensity );
  34037. /**
  34038. * This flag can be used for type testing.
  34039. *
  34040. * @type {boolean}
  34041. * @readonly
  34042. * @default true
  34043. */
  34044. this.isPointLight = true;
  34045. this.type = 'PointLight';
  34046. /**
  34047. * When distance is zero, light will attenuate according to inverse-square
  34048. * law to infinite distance. When distance is non-zero, light will attenuate
  34049. * according to inverse-square law until near the distance cutoff, where it
  34050. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  34051. * physically correct.
  34052. *
  34053. * @type {number}
  34054. * @default 0
  34055. */
  34056. this.distance = distance;
  34057. /**
  34058. * The amount the light dims along the distance of the light. In context of
  34059. * physically-correct rendering the default value should not be changed.
  34060. *
  34061. * @type {number}
  34062. * @default 2
  34063. */
  34064. this.decay = decay;
  34065. /**
  34066. * This property holds the light's shadow configuration.
  34067. *
  34068. * @type {PointLightShadow}
  34069. */
  34070. this.shadow = new PointLightShadow();
  34071. }
  34072. /**
  34073. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34074. * Changing the power will also change the light's intensity.
  34075. *
  34076. * @type {number}
  34077. */
  34078. get power() {
  34079. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34080. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  34081. return this.intensity * 4 * Math.PI;
  34082. }
  34083. set power( power ) {
  34084. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34085. this.intensity = power / ( 4 * Math.PI );
  34086. }
  34087. dispose() {
  34088. super.dispose();
  34089. this.shadow.dispose();
  34090. }
  34091. copy( source, recursive ) {
  34092. super.copy( source, recursive );
  34093. this.distance = source.distance;
  34094. this.decay = source.decay;
  34095. this.shadow = source.shadow.clone();
  34096. return this;
  34097. }
  34098. toJSON( meta ) {
  34099. const data = super.toJSON( meta );
  34100. data.object.distance = this.distance;
  34101. data.object.decay = this.decay;
  34102. data.object.shadow = this.shadow.toJSON();
  34103. return data;
  34104. }
  34105. }
  34106. /**
  34107. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  34108. *
  34109. * In this projection mode, an object's size in the rendered image stays
  34110. * constant regardless of its distance from the camera. This can be useful
  34111. * for rendering 2D scenes and UI elements, amongst other things.
  34112. *
  34113. * ```js
  34114. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  34115. * scene.add( camera );
  34116. * ```
  34117. *
  34118. * @augments Camera
  34119. */
  34120. class OrthographicCamera extends Camera {
  34121. /**
  34122. * Constructs a new orthographic camera.
  34123. *
  34124. * @param {number} [left=-1] - The left plane of the camera's frustum.
  34125. * @param {number} [right=1] - The right plane of the camera's frustum.
  34126. * @param {number} [top=1] - The top plane of the camera's frustum.
  34127. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  34128. * @param {number} [near=0.1] - The camera's near plane.
  34129. * @param {number} [far=2000] - The camera's far plane.
  34130. */
  34131. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  34132. super();
  34133. /**
  34134. * This flag can be used for type testing.
  34135. *
  34136. * @type {boolean}
  34137. * @readonly
  34138. * @default true
  34139. */
  34140. this.isOrthographicCamera = true;
  34141. this.type = 'OrthographicCamera';
  34142. /**
  34143. * The zoom factor of the camera.
  34144. *
  34145. * @type {number}
  34146. * @default 1
  34147. */
  34148. this.zoom = 1;
  34149. /**
  34150. * Represents the frustum window specification. This property should not be edited
  34151. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34152. *
  34153. * @type {?Object}
  34154. * @default null
  34155. */
  34156. this.view = null;
  34157. /**
  34158. * The left plane of the camera's frustum.
  34159. *
  34160. * @type {number}
  34161. * @default -1
  34162. */
  34163. this.left = left;
  34164. /**
  34165. * The right plane of the camera's frustum.
  34166. *
  34167. * @type {number}
  34168. * @default 1
  34169. */
  34170. this.right = right;
  34171. /**
  34172. * The top plane of the camera's frustum.
  34173. *
  34174. * @type {number}
  34175. * @default 1
  34176. */
  34177. this.top = top;
  34178. /**
  34179. * The bottom plane of the camera's frustum.
  34180. *
  34181. * @type {number}
  34182. * @default -1
  34183. */
  34184. this.bottom = bottom;
  34185. /**
  34186. * The camera's near plane. The valid range is greater than `0`
  34187. * and less than the current value of {@link OrthographicCamera#far}.
  34188. *
  34189. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34190. * valid value for an orthographic camera's near plane.
  34191. *
  34192. * @type {number}
  34193. * @default 0.1
  34194. */
  34195. this.near = near;
  34196. /**
  34197. * The camera's far plane. Must be greater than the
  34198. * current value of {@link OrthographicCamera#near}.
  34199. *
  34200. * @type {number}
  34201. * @default 2000
  34202. */
  34203. this.far = far;
  34204. this.updateProjectionMatrix();
  34205. }
  34206. copy( source, recursive ) {
  34207. super.copy( source, recursive );
  34208. this.left = source.left;
  34209. this.right = source.right;
  34210. this.top = source.top;
  34211. this.bottom = source.bottom;
  34212. this.near = source.near;
  34213. this.far = source.far;
  34214. this.zoom = source.zoom;
  34215. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34216. return this;
  34217. }
  34218. /**
  34219. * Sets an offset in a larger frustum. This is useful for multi-window or
  34220. * multi-monitor/multi-machine setups.
  34221. *
  34222. * @param {number} fullWidth - The full width of multiview setup.
  34223. * @param {number} fullHeight - The full height of multiview setup.
  34224. * @param {number} x - The horizontal offset of the subcamera.
  34225. * @param {number} y - The vertical offset of the subcamera.
  34226. * @param {number} width - The width of subcamera.
  34227. * @param {number} height - The height of subcamera.
  34228. * @see {@link PerspectiveCamera#setViewOffset}
  34229. */
  34230. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34231. if ( this.view === null ) {
  34232. this.view = {
  34233. enabled: true,
  34234. fullWidth: 1,
  34235. fullHeight: 1,
  34236. offsetX: 0,
  34237. offsetY: 0,
  34238. width: 1,
  34239. height: 1
  34240. };
  34241. }
  34242. this.view.enabled = true;
  34243. this.view.fullWidth = fullWidth;
  34244. this.view.fullHeight = fullHeight;
  34245. this.view.offsetX = x;
  34246. this.view.offsetY = y;
  34247. this.view.width = width;
  34248. this.view.height = height;
  34249. this.updateProjectionMatrix();
  34250. }
  34251. /**
  34252. * Removes the view offset from the projection matrix.
  34253. */
  34254. clearViewOffset() {
  34255. if ( this.view !== null ) {
  34256. this.view.enabled = false;
  34257. }
  34258. this.updateProjectionMatrix();
  34259. }
  34260. /**
  34261. * Updates the camera's projection matrix. Must be called after any change of
  34262. * camera properties.
  34263. */
  34264. updateProjectionMatrix() {
  34265. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34266. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34267. const cx = ( this.right + this.left ) / 2;
  34268. const cy = ( this.top + this.bottom ) / 2;
  34269. let left = cx - dx;
  34270. let right = cx + dx;
  34271. let top = cy + dy;
  34272. let bottom = cy - dy;
  34273. if ( this.view !== null && this.view.enabled ) {
  34274. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34275. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34276. left += scaleW * this.view.offsetX;
  34277. right = left + scaleW * this.view.width;
  34278. top -= scaleH * this.view.offsetY;
  34279. bottom = top - scaleH * this.view.height;
  34280. }
  34281. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34282. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34283. }
  34284. toJSON( meta ) {
  34285. const data = super.toJSON( meta );
  34286. data.object.zoom = this.zoom;
  34287. data.object.left = this.left;
  34288. data.object.right = this.right;
  34289. data.object.top = this.top;
  34290. data.object.bottom = this.bottom;
  34291. data.object.near = this.near;
  34292. data.object.far = this.far;
  34293. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34294. return data;
  34295. }
  34296. }
  34297. /**
  34298. * Represents the shadow configuration of directional lights.
  34299. *
  34300. * @augments LightShadow
  34301. */
  34302. class DirectionalLightShadow extends LightShadow {
  34303. /**
  34304. * Constructs a new directional light shadow.
  34305. */
  34306. constructor() {
  34307. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34308. /**
  34309. * This flag can be used for type testing.
  34310. *
  34311. * @type {boolean}
  34312. * @readonly
  34313. * @default true
  34314. */
  34315. this.isDirectionalLightShadow = true;
  34316. }
  34317. }
  34318. /**
  34319. * A light that gets emitted in a specific direction. This light will behave
  34320. * as though it is infinitely far away and the rays produced from it are all
  34321. * parallel. The common use case for this is to simulate daylight; the sun is
  34322. * far enough away that its position can be considered to be infinite, and
  34323. * all light rays coming from it are parallel.
  34324. *
  34325. * A common point of confusion for directional lights is that setting the
  34326. * rotation has no effect. This is because three.js's DirectionalLight is the
  34327. * equivalent to what is often called a 'Target Direct Light' in other
  34328. * applications.
  34329. *
  34330. * This means that its direction is calculated as pointing from the light's
  34331. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34332. * (as opposed to a 'Free Direct Light' that just has a rotation
  34333. * component).
  34334. *
  34335. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34336. *
  34337. * ```js
  34338. * // White directional light at half intensity shining from the top.
  34339. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34340. * scene.add( directionalLight );
  34341. * ```
  34342. *
  34343. * @augments Light
  34344. */
  34345. class DirectionalLight extends Light {
  34346. /**
  34347. * Constructs a new directional light.
  34348. *
  34349. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34350. * @param {number} [intensity=1] - The light's strength/intensity.
  34351. */
  34352. constructor( color, intensity ) {
  34353. super( color, intensity );
  34354. /**
  34355. * This flag can be used for type testing.
  34356. *
  34357. * @type {boolean}
  34358. * @readonly
  34359. * @default true
  34360. */
  34361. this.isDirectionalLight = true;
  34362. this.type = 'DirectionalLight';
  34363. this.position.copy( Object3D.DEFAULT_UP );
  34364. this.updateMatrix();
  34365. /**
  34366. * The directional light points from its position to the
  34367. * target's position.
  34368. *
  34369. * For the target's position to be changed to anything other
  34370. * than the default, it must be added to the scene.
  34371. *
  34372. * It is also possible to set the target to be another 3D object
  34373. * in the scene. The light will now track the target object.
  34374. *
  34375. * @type {Object3D}
  34376. */
  34377. this.target = new Object3D();
  34378. /**
  34379. * This property holds the light's shadow configuration.
  34380. *
  34381. * @type {DirectionalLightShadow}
  34382. */
  34383. this.shadow = new DirectionalLightShadow();
  34384. }
  34385. dispose() {
  34386. super.dispose();
  34387. this.shadow.dispose();
  34388. }
  34389. copy( source ) {
  34390. super.copy( source );
  34391. this.target = source.target.clone();
  34392. this.shadow = source.shadow.clone();
  34393. return this;
  34394. }
  34395. toJSON( meta ) {
  34396. const data = super.toJSON( meta );
  34397. data.object.shadow = this.shadow.toJSON();
  34398. data.object.target = this.target.uuid;
  34399. return data;
  34400. }
  34401. }
  34402. /**
  34403. * This light globally illuminates all objects in the scene equally.
  34404. *
  34405. * It cannot be used to cast shadows as it does not have a direction.
  34406. *
  34407. * ```js
  34408. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34409. * scene.add( light );
  34410. * ```
  34411. *
  34412. * @augments Light
  34413. */
  34414. class AmbientLight extends Light {
  34415. /**
  34416. * Constructs a new ambient light.
  34417. *
  34418. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34419. * @param {number} [intensity=1] - The light's strength/intensity.
  34420. */
  34421. constructor( color, intensity ) {
  34422. super( color, intensity );
  34423. /**
  34424. * This flag can be used for type testing.
  34425. *
  34426. * @type {boolean}
  34427. * @readonly
  34428. * @default true
  34429. */
  34430. this.isAmbientLight = true;
  34431. this.type = 'AmbientLight';
  34432. }
  34433. }
  34434. /**
  34435. * This class emits light uniformly across the face a rectangular plane.
  34436. * This light type can be used to simulate light sources such as bright
  34437. * windows or strip lighting.
  34438. *
  34439. * Important Notes:
  34440. *
  34441. * - There is no shadow support.
  34442. * - Only PBR materials are supported.
  34443. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34444. * into your app and init the uniforms/textures.
  34445. *
  34446. * ```js
  34447. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34448. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34449. *
  34450. * const intensity = 1; const width = 10; const height = 10;
  34451. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34452. * rectLight.position.set( 5, 5, 0 );
  34453. * rectLight.lookAt( 0, 0, 0 );
  34454. * scene.add( rectLight )
  34455. * ```
  34456. *
  34457. * @augments Light
  34458. */
  34459. class RectAreaLight extends Light {
  34460. /**
  34461. * Constructs a new area light.
  34462. *
  34463. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34464. * @param {number} [intensity=1] - The light's strength/intensity.
  34465. * @param {number} [width=10] - The width of the light.
  34466. * @param {number} [height=10] - The height of the light.
  34467. */
  34468. constructor( color, intensity, width = 10, height = 10 ) {
  34469. super( color, intensity );
  34470. /**
  34471. * This flag can be used for type testing.
  34472. *
  34473. * @type {boolean}
  34474. * @readonly
  34475. * @default true
  34476. */
  34477. this.isRectAreaLight = true;
  34478. this.type = 'RectAreaLight';
  34479. /**
  34480. * The width of the light.
  34481. *
  34482. * @type {number}
  34483. * @default 10
  34484. */
  34485. this.width = width;
  34486. /**
  34487. * The height of the light.
  34488. *
  34489. * @type {number}
  34490. * @default 10
  34491. */
  34492. this.height = height;
  34493. }
  34494. /**
  34495. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34496. * Changing the power will also change the light's intensity.
  34497. *
  34498. * @type {number}
  34499. */
  34500. get power() {
  34501. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34502. return this.intensity * this.width * this.height * Math.PI;
  34503. }
  34504. set power( power ) {
  34505. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34506. this.intensity = power / ( this.width * this.height * Math.PI );
  34507. }
  34508. copy( source ) {
  34509. super.copy( source );
  34510. this.width = source.width;
  34511. this.height = source.height;
  34512. return this;
  34513. }
  34514. toJSON( meta ) {
  34515. const data = super.toJSON( meta );
  34516. data.object.width = this.width;
  34517. data.object.height = this.height;
  34518. return data;
  34519. }
  34520. }
  34521. /**
  34522. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34523. * to encode lighting information.
  34524. *
  34525. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34526. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34527. */
  34528. class SphericalHarmonics3 {
  34529. /**
  34530. * Constructs a new spherical harmonics.
  34531. */
  34532. constructor() {
  34533. /**
  34534. * This flag can be used for type testing.
  34535. *
  34536. * @type {boolean}
  34537. * @readonly
  34538. * @default true
  34539. */
  34540. this.isSphericalHarmonics3 = true;
  34541. /**
  34542. * An array holding the (9) SH coefficients.
  34543. *
  34544. * @type {Array<Vector3>}
  34545. */
  34546. this.coefficients = [];
  34547. for ( let i = 0; i < 9; i ++ ) {
  34548. this.coefficients.push( new Vector3() );
  34549. }
  34550. }
  34551. /**
  34552. * Sets the given SH coefficients to this instance by copying
  34553. * the values.
  34554. *
  34555. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34556. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34557. */
  34558. set( coefficients ) {
  34559. for ( let i = 0; i < 9; i ++ ) {
  34560. this.coefficients[ i ].copy( coefficients[ i ] );
  34561. }
  34562. return this;
  34563. }
  34564. /**
  34565. * Sets all SH coefficients to `0`.
  34566. *
  34567. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34568. */
  34569. zero() {
  34570. for ( let i = 0; i < 9; i ++ ) {
  34571. this.coefficients[ i ].set( 0, 0, 0 );
  34572. }
  34573. return this;
  34574. }
  34575. /**
  34576. * Returns the radiance in the direction of the given normal.
  34577. *
  34578. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34579. * @param {Vector3} target - The target vector that is used to store the method's result.
  34580. * @return {Vector3} The radiance.
  34581. */
  34582. getAt( normal, target ) {
  34583. // normal is assumed to be unit length
  34584. const x = normal.x, y = normal.y, z = normal.z;
  34585. const coeff = this.coefficients;
  34586. // band 0
  34587. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34588. // band 1
  34589. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34590. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34591. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34592. // band 2
  34593. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34594. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34595. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34596. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34597. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34598. return target;
  34599. }
  34600. /**
  34601. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34602. * direction of the given normal.
  34603. *
  34604. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34605. * @param {Vector3} target - The target vector that is used to store the method's result.
  34606. * @return {Vector3} The irradiance.
  34607. */
  34608. getIrradianceAt( normal, target ) {
  34609. // normal is assumed to be unit length
  34610. const x = normal.x, y = normal.y, z = normal.z;
  34611. const coeff = this.coefficients;
  34612. // band 0
  34613. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34614. // band 1
  34615. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34616. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34617. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34618. // band 2
  34619. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34620. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34621. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34622. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34623. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34624. return target;
  34625. }
  34626. /**
  34627. * Adds the given SH to this instance.
  34628. *
  34629. * @param {SphericalHarmonics3} sh - The SH to add.
  34630. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34631. */
  34632. add( sh ) {
  34633. for ( let i = 0; i < 9; i ++ ) {
  34634. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34635. }
  34636. return this;
  34637. }
  34638. /**
  34639. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34640. * {@link SphericalHarmonics3#scale} at once.
  34641. *
  34642. * @param {SphericalHarmonics3} sh - The SH to add.
  34643. * @param {number} s - The scale factor.
  34644. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34645. */
  34646. addScaledSH( sh, s ) {
  34647. for ( let i = 0; i < 9; i ++ ) {
  34648. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34649. }
  34650. return this;
  34651. }
  34652. /**
  34653. * Scales this SH by the given scale factor.
  34654. *
  34655. * @param {number} s - The scale factor.
  34656. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34657. */
  34658. scale( s ) {
  34659. for ( let i = 0; i < 9; i ++ ) {
  34660. this.coefficients[ i ].multiplyScalar( s );
  34661. }
  34662. return this;
  34663. }
  34664. /**
  34665. * Linear interpolates between the given SH and this instance by the given
  34666. * alpha factor.
  34667. *
  34668. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34669. * @param {number} alpha - The alpha factor.
  34670. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34671. */
  34672. lerp( sh, alpha ) {
  34673. for ( let i = 0; i < 9; i ++ ) {
  34674. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34675. }
  34676. return this;
  34677. }
  34678. /**
  34679. * Returns `true` if this spherical harmonics is equal with the given one.
  34680. *
  34681. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34682. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34683. */
  34684. equals( sh ) {
  34685. for ( let i = 0; i < 9; i ++ ) {
  34686. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34687. return false;
  34688. }
  34689. }
  34690. return true;
  34691. }
  34692. /**
  34693. * Copies the values of the given spherical harmonics to this instance.
  34694. *
  34695. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34696. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34697. */
  34698. copy( sh ) {
  34699. return this.set( sh.coefficients );
  34700. }
  34701. /**
  34702. * Returns a new spherical harmonics with copied values from this instance.
  34703. *
  34704. * @return {SphericalHarmonics3} A clone of this instance.
  34705. */
  34706. clone() {
  34707. return new this.constructor().copy( this );
  34708. }
  34709. /**
  34710. * Sets the SH coefficients of this instance from the given array.
  34711. *
  34712. * @param {Array<number>} array - An array holding the SH coefficients.
  34713. * @param {number} [offset=0] - The array offset where to start copying.
  34714. * @return {SphericalHarmonics3} A clone of this instance.
  34715. */
  34716. fromArray( array, offset = 0 ) {
  34717. const coefficients = this.coefficients;
  34718. for ( let i = 0; i < 9; i ++ ) {
  34719. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34720. }
  34721. return this;
  34722. }
  34723. /**
  34724. * Returns an array with the SH coefficients, or copies them into the provided
  34725. * array. The coefficients are represented as numbers.
  34726. *
  34727. * @param {Array<number>} [array=[]] - The target array.
  34728. * @param {number} [offset=0] - The array offset where to start copying.
  34729. * @return {Array<number>} An array with flat SH coefficients.
  34730. */
  34731. toArray( array = [], offset = 0 ) {
  34732. const coefficients = this.coefficients;
  34733. for ( let i = 0; i < 9; i ++ ) {
  34734. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34735. }
  34736. return array;
  34737. }
  34738. /**
  34739. * Computes the SH basis for the given normal vector.
  34740. *
  34741. * @param {Vector3} normal - The normal.
  34742. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34743. */
  34744. static getBasisAt( normal, shBasis ) {
  34745. // normal is assumed to be unit length
  34746. const x = normal.x, y = normal.y, z = normal.z;
  34747. // band 0
  34748. shBasis[ 0 ] = 0.282095;
  34749. // band 1
  34750. shBasis[ 1 ] = 0.488603 * y;
  34751. shBasis[ 2 ] = 0.488603 * z;
  34752. shBasis[ 3 ] = 0.488603 * x;
  34753. // band 2
  34754. shBasis[ 4 ] = 1.092548 * x * y;
  34755. shBasis[ 5 ] = 1.092548 * y * z;
  34756. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34757. shBasis[ 7 ] = 1.092548 * x * z;
  34758. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34759. }
  34760. }
  34761. /**
  34762. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34763. * classical light sources (e.g. directional, point or spot lights), light
  34764. * probes do not emit light. Instead they store information about light
  34765. * passing through 3D space. During rendering, the light that hits a 3D
  34766. * object is approximated by using the data from the light probe.
  34767. *
  34768. * Light probes are usually created from (radiance) environment maps. The
  34769. * class {@link LightProbeGenerator} can be used to create light probes from
  34770. * cube textures or render targets. However, light estimation data could also
  34771. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34772. * augmented reality content that reacts to real world lighting.
  34773. *
  34774. * The current probe implementation in three.js supports so-called diffuse
  34775. * light probes. This type of light probe is functionally equivalent to an
  34776. * irradiance environment map.
  34777. *
  34778. * @augments Light
  34779. */
  34780. class LightProbe extends Light {
  34781. /**
  34782. * Constructs a new light probe.
  34783. *
  34784. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34785. * @param {number} [intensity=1] - The light's strength/intensity.
  34786. */
  34787. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34788. super( undefined, intensity );
  34789. /**
  34790. * This flag can be used for type testing.
  34791. *
  34792. * @type {boolean}
  34793. * @readonly
  34794. * @default true
  34795. */
  34796. this.isLightProbe = true;
  34797. /**
  34798. * A light probe uses spherical harmonics to encode lighting information.
  34799. *
  34800. * @type {SphericalHarmonics3}
  34801. */
  34802. this.sh = sh;
  34803. }
  34804. copy( source ) {
  34805. super.copy( source );
  34806. this.sh.copy( source.sh );
  34807. return this;
  34808. }
  34809. toJSON( meta ) {
  34810. const data = super.toJSON( meta );
  34811. data.object.sh = this.sh.toArray();
  34812. return data;
  34813. }
  34814. }
  34815. /**
  34816. * Class for loading materials. The files are internally
  34817. * loaded via {@link FileLoader}.
  34818. *
  34819. * ```js
  34820. * const loader = new THREE.MaterialLoader();
  34821. * const material = await loader.loadAsync( 'material.json' );
  34822. * ```
  34823. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34824. *
  34825. * @augments Loader
  34826. */
  34827. class MaterialLoader extends Loader {
  34828. /**
  34829. * Constructs a new material loader.
  34830. *
  34831. * @param {LoadingManager} [manager] - The loading manager.
  34832. */
  34833. constructor( manager ) {
  34834. super( manager );
  34835. /**
  34836. * A dictionary holding textures used by the material.
  34837. *
  34838. * @type {Object<string,Texture>}
  34839. */
  34840. this.textures = {};
  34841. }
  34842. /**
  34843. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34844. *
  34845. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34846. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34847. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34848. * @param {onErrorCallback} onError - Executed when errors occur.
  34849. */
  34850. load( url, onLoad, onProgress, onError ) {
  34851. const scope = this;
  34852. const loader = new FileLoader( scope.manager );
  34853. loader.setPath( scope.path );
  34854. loader.setRequestHeader( scope.requestHeader );
  34855. loader.setWithCredentials( scope.withCredentials );
  34856. loader.load( url, function ( text ) {
  34857. try {
  34858. onLoad( scope.parse( JSON.parse( text ) ) );
  34859. } catch ( e ) {
  34860. if ( onError ) {
  34861. onError( e );
  34862. } else {
  34863. error( e );
  34864. }
  34865. scope.manager.itemError( url );
  34866. }
  34867. }, onProgress, onError );
  34868. }
  34869. /**
  34870. * Parses the given JSON object and returns a material.
  34871. *
  34872. * @param {Object} json - The serialized material.
  34873. * @return {Material} The parsed material.
  34874. */
  34875. parse( json ) {
  34876. const textures = this.textures;
  34877. function getTexture( name ) {
  34878. if ( textures[ name ] === undefined ) {
  34879. warn( 'MaterialLoader: Undefined texture', name );
  34880. }
  34881. return textures[ name ];
  34882. }
  34883. const material = this.createMaterialFromType( json.type );
  34884. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34885. if ( json.name !== undefined ) material.name = json.name;
  34886. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34887. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34888. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34889. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34890. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34891. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34892. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34893. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34894. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34895. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34896. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34897. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34898. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34899. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34900. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34901. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34902. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34903. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34904. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34905. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34906. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34907. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34908. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34909. if ( json.fog !== undefined ) material.fog = json.fog;
  34910. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34911. if ( json.blending !== undefined ) material.blending = json.blending;
  34912. if ( json.combine !== undefined ) material.combine = json.combine;
  34913. if ( json.side !== undefined ) material.side = json.side;
  34914. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34915. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34916. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34917. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34918. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34919. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34920. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34921. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34922. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34923. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34924. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34925. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34926. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34927. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34928. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34929. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34930. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34931. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34932. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34933. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34934. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34935. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34936. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34937. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34938. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34939. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34940. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34941. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34942. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34943. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34944. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34945. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34946. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34947. if ( json.scale !== undefined ) material.scale = json.scale;
  34948. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34949. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34950. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34951. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34952. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34953. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34954. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34955. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34956. if ( json.visible !== undefined ) material.visible = json.visible;
  34957. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34958. if ( json.userData !== undefined ) material.userData = json.userData;
  34959. if ( json.vertexColors !== undefined ) {
  34960. if ( typeof json.vertexColors === 'number' ) {
  34961. material.vertexColors = json.vertexColors > 0;
  34962. } else {
  34963. material.vertexColors = json.vertexColors;
  34964. }
  34965. }
  34966. // Shader Material
  34967. if ( json.uniforms !== undefined ) {
  34968. for ( const name in json.uniforms ) {
  34969. const uniform = json.uniforms[ name ];
  34970. material.uniforms[ name ] = {};
  34971. switch ( uniform.type ) {
  34972. case 't':
  34973. material.uniforms[ name ].value = getTexture( uniform.value );
  34974. break;
  34975. case 'c':
  34976. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34977. break;
  34978. case 'v2':
  34979. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34980. break;
  34981. case 'v3':
  34982. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34983. break;
  34984. case 'v4':
  34985. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34986. break;
  34987. case 'm3':
  34988. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34989. break;
  34990. case 'm4':
  34991. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34992. break;
  34993. default:
  34994. material.uniforms[ name ].value = uniform.value;
  34995. }
  34996. }
  34997. }
  34998. if ( json.defines !== undefined ) material.defines = json.defines;
  34999. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  35000. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  35001. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  35002. if ( json.extensions !== undefined ) {
  35003. for ( const key in json.extensions ) {
  35004. material.extensions[ key ] = json.extensions[ key ];
  35005. }
  35006. }
  35007. if ( json.lights !== undefined ) material.lights = json.lights;
  35008. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  35009. // for PointsMaterial
  35010. if ( json.size !== undefined ) material.size = json.size;
  35011. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  35012. // maps
  35013. if ( json.map !== undefined ) material.map = getTexture( json.map );
  35014. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  35015. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  35016. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  35017. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  35018. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  35019. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  35020. if ( json.normalScale !== undefined ) {
  35021. let normalScale = json.normalScale;
  35022. if ( Array.isArray( normalScale ) === false ) {
  35023. // Blender exporter used to export a scalar. See #7459
  35024. normalScale = [ normalScale, normalScale ];
  35025. }
  35026. material.normalScale = new Vector2().fromArray( normalScale );
  35027. }
  35028. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  35029. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  35030. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  35031. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  35032. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  35033. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  35034. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  35035. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  35036. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  35037. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  35038. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  35039. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  35040. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  35041. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  35042. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  35043. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  35044. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  35045. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  35046. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  35047. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  35048. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  35049. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  35050. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  35051. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  35052. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  35053. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  35054. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  35055. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  35056. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  35057. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  35058. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  35059. return material;
  35060. }
  35061. /**
  35062. * Textures are not embedded in the material JSON so they have
  35063. * to be injected before the loading process starts.
  35064. *
  35065. * @param {Object} value - A dictionary holding textures for material properties.
  35066. * @return {MaterialLoader} A reference to this material loader.
  35067. */
  35068. setTextures( value ) {
  35069. this.textures = value;
  35070. return this;
  35071. }
  35072. /**
  35073. * Creates a material for the given type.
  35074. *
  35075. * @param {string} type - The material type.
  35076. * @return {Material} The new material.
  35077. */
  35078. createMaterialFromType( type ) {
  35079. return MaterialLoader.createMaterialFromType( type );
  35080. }
  35081. /**
  35082. * Creates a material for the given type.
  35083. *
  35084. * @static
  35085. * @param {string} type - The material type.
  35086. * @return {Material} The new material.
  35087. */
  35088. static createMaterialFromType( type ) {
  35089. const materialLib = {
  35090. ShadowMaterial,
  35091. SpriteMaterial,
  35092. RawShaderMaterial,
  35093. ShaderMaterial,
  35094. PointsMaterial,
  35095. MeshPhysicalMaterial,
  35096. MeshStandardMaterial,
  35097. MeshPhongMaterial,
  35098. MeshToonMaterial,
  35099. MeshNormalMaterial,
  35100. MeshLambertMaterial,
  35101. MeshDepthMaterial,
  35102. MeshDistanceMaterial,
  35103. MeshBasicMaterial,
  35104. MeshMatcapMaterial,
  35105. LineDashedMaterial,
  35106. LineBasicMaterial,
  35107. Material
  35108. };
  35109. return new materialLib[ type ]();
  35110. }
  35111. }
  35112. /**
  35113. * A class with loader utility functions.
  35114. */
  35115. class LoaderUtils {
  35116. /**
  35117. * Extracts the base URL from the given URL.
  35118. *
  35119. * @param {string} url -The URL to extract the base URL from.
  35120. * @return {string} The extracted base URL.
  35121. */
  35122. static extractUrlBase( url ) {
  35123. const index = url.lastIndexOf( '/' );
  35124. if ( index === -1 ) return './';
  35125. return url.slice( 0, index + 1 );
  35126. }
  35127. /**
  35128. * Resolves relative URLs against the given path. Absolute paths, data urls,
  35129. * and blob URLs will be returned as is. Invalid URLs will return an empty
  35130. * string.
  35131. *
  35132. * @param {string} url -The URL to resolve.
  35133. * @param {string} path - The base path for relative URLs to be resolved against.
  35134. * @return {string} The resolved URL.
  35135. */
  35136. static resolveURL( url, path ) {
  35137. // Invalid URL
  35138. if ( typeof url !== 'string' || url === '' ) return '';
  35139. // Host Relative URL
  35140. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35141. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35142. }
  35143. // Absolute URL http://,https://,//
  35144. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35145. // Data URI
  35146. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35147. // Blob URL
  35148. if ( /^blob:.*$/i.test( url ) ) return url;
  35149. // Relative URL
  35150. return path + url;
  35151. }
  35152. }
  35153. /**
  35154. * An instanced version of a geometry.
  35155. */
  35156. class InstancedBufferGeometry extends BufferGeometry {
  35157. /**
  35158. * Constructs a new instanced buffer geometry.
  35159. */
  35160. constructor() {
  35161. super();
  35162. /**
  35163. * This flag can be used for type testing.
  35164. *
  35165. * @type {boolean}
  35166. * @readonly
  35167. * @default true
  35168. */
  35169. this.isInstancedBufferGeometry = true;
  35170. this.type = 'InstancedBufferGeometry';
  35171. /**
  35172. * The instance count.
  35173. *
  35174. * @type {number}
  35175. * @default Infinity
  35176. */
  35177. this.instanceCount = Infinity;
  35178. }
  35179. copy( source ) {
  35180. super.copy( source );
  35181. this.instanceCount = source.instanceCount;
  35182. return this;
  35183. }
  35184. toJSON() {
  35185. const data = super.toJSON();
  35186. data.instanceCount = this.instanceCount;
  35187. data.isInstancedBufferGeometry = true;
  35188. return data;
  35189. }
  35190. }
  35191. /**
  35192. * Class for loading geometries. The files are internally
  35193. * loaded via {@link FileLoader}.
  35194. *
  35195. * ```js
  35196. * const loader = new THREE.BufferGeometryLoader();
  35197. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35198. *
  35199. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35200. * const object = new THREE.Mesh( geometry, material );
  35201. * scene.add( object );
  35202. * ```
  35203. *
  35204. * @augments Loader
  35205. */
  35206. class BufferGeometryLoader extends Loader {
  35207. /**
  35208. * Constructs a new geometry loader.
  35209. *
  35210. * @param {LoadingManager} [manager] - The loading manager.
  35211. */
  35212. constructor( manager ) {
  35213. super( manager );
  35214. }
  35215. /**
  35216. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35217. *
  35218. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35219. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35220. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35221. * @param {onErrorCallback} onError - Executed when errors occur.
  35222. */
  35223. load( url, onLoad, onProgress, onError ) {
  35224. const scope = this;
  35225. const loader = new FileLoader( scope.manager );
  35226. loader.setPath( scope.path );
  35227. loader.setRequestHeader( scope.requestHeader );
  35228. loader.setWithCredentials( scope.withCredentials );
  35229. loader.load( url, function ( text ) {
  35230. try {
  35231. onLoad( scope.parse( JSON.parse( text ) ) );
  35232. } catch ( e ) {
  35233. if ( onError ) {
  35234. onError( e );
  35235. } else {
  35236. error( e );
  35237. }
  35238. scope.manager.itemError( url );
  35239. }
  35240. }, onProgress, onError );
  35241. }
  35242. /**
  35243. * Parses the given JSON object and returns a geometry.
  35244. *
  35245. * @param {Object} json - The serialized geometry.
  35246. * @return {BufferGeometry} The parsed geometry.
  35247. */
  35248. parse( json ) {
  35249. const interleavedBufferMap = {};
  35250. const arrayBufferMap = {};
  35251. function getInterleavedBuffer( json, uuid ) {
  35252. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35253. const interleavedBuffers = json.interleavedBuffers;
  35254. const interleavedBuffer = interleavedBuffers[ uuid ];
  35255. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35256. const array = getTypedArray( interleavedBuffer.type, buffer );
  35257. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35258. ib.uuid = interleavedBuffer.uuid;
  35259. interleavedBufferMap[ uuid ] = ib;
  35260. return ib;
  35261. }
  35262. function getArrayBuffer( json, uuid ) {
  35263. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35264. const arrayBuffers = json.arrayBuffers;
  35265. const arrayBuffer = arrayBuffers[ uuid ];
  35266. const ab = new Uint32Array( arrayBuffer ).buffer;
  35267. arrayBufferMap[ uuid ] = ab;
  35268. return ab;
  35269. }
  35270. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35271. const index = json.data.index;
  35272. if ( index !== undefined ) {
  35273. const typedArray = getTypedArray( index.type, index.array );
  35274. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35275. }
  35276. const attributes = json.data.attributes;
  35277. for ( const key in attributes ) {
  35278. const attribute = attributes[ key ];
  35279. let bufferAttribute;
  35280. if ( attribute.isInterleavedBufferAttribute ) {
  35281. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35282. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35283. } else {
  35284. const typedArray = getTypedArray( attribute.type, attribute.array );
  35285. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35286. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35287. }
  35288. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35289. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35290. geometry.setAttribute( key, bufferAttribute );
  35291. }
  35292. const morphAttributes = json.data.morphAttributes;
  35293. if ( morphAttributes ) {
  35294. for ( const key in morphAttributes ) {
  35295. const attributeArray = morphAttributes[ key ];
  35296. const array = [];
  35297. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35298. const attribute = attributeArray[ i ];
  35299. let bufferAttribute;
  35300. if ( attribute.isInterleavedBufferAttribute ) {
  35301. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35302. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35303. } else {
  35304. const typedArray = getTypedArray( attribute.type, attribute.array );
  35305. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35306. }
  35307. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35308. array.push( bufferAttribute );
  35309. }
  35310. geometry.morphAttributes[ key ] = array;
  35311. }
  35312. }
  35313. const morphTargetsRelative = json.data.morphTargetsRelative;
  35314. if ( morphTargetsRelative ) {
  35315. geometry.morphTargetsRelative = true;
  35316. }
  35317. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35318. if ( groups !== undefined ) {
  35319. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35320. const group = groups[ i ];
  35321. geometry.addGroup( group.start, group.count, group.materialIndex );
  35322. }
  35323. }
  35324. const boundingSphere = json.data.boundingSphere;
  35325. if ( boundingSphere !== undefined ) {
  35326. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35327. }
  35328. if ( json.name ) geometry.name = json.name;
  35329. if ( json.userData ) geometry.userData = json.userData;
  35330. return geometry;
  35331. }
  35332. }
  35333. const _customGeometries = {};
  35334. /**
  35335. * 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).
  35336. * The files are internally loaded via {@link FileLoader}.
  35337. *
  35338. * ```js
  35339. * const loader = new THREE.ObjectLoader();
  35340. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35341. * scene.add( obj );
  35342. *
  35343. * // Alternatively, to parse a previously loaded JSON structure
  35344. * const object = await loader.parseAsync( a_json_object );
  35345. * scene.add( object );
  35346. * ```
  35347. *
  35348. * @augments Loader
  35349. */
  35350. class ObjectLoader extends Loader {
  35351. /**
  35352. * Constructs a new object loader.
  35353. *
  35354. * @param {LoadingManager} [manager] - The loading manager.
  35355. */
  35356. constructor( manager ) {
  35357. super( manager );
  35358. }
  35359. /**
  35360. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35361. *
  35362. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35363. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35364. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35365. * @param {onErrorCallback} onError - Executed when errors occur.
  35366. */
  35367. load( url, onLoad, onProgress, onError ) {
  35368. const scope = this;
  35369. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35370. this.resourcePath = this.resourcePath || path;
  35371. const loader = new FileLoader( this.manager );
  35372. loader.setPath( this.path );
  35373. loader.setRequestHeader( this.requestHeader );
  35374. loader.setWithCredentials( this.withCredentials );
  35375. loader.load( url, function ( text ) {
  35376. let json = null;
  35377. try {
  35378. json = JSON.parse( text );
  35379. } catch ( e ) {
  35380. if ( onError !== undefined ) onError( e );
  35381. error( 'ObjectLoader: Can\'t parse ' + url + '.', e.message );
  35382. return;
  35383. }
  35384. const metadata = json.metadata;
  35385. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35386. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35387. error( 'ObjectLoader: Can\'t load ' + url );
  35388. return;
  35389. }
  35390. scope.parse( json, onLoad );
  35391. }, onProgress, onError );
  35392. }
  35393. /**
  35394. * Async version of {@link ObjectLoader#load}.
  35395. *
  35396. * @async
  35397. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35398. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35399. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35400. */
  35401. async loadAsync( url, onProgress ) {
  35402. const scope = this;
  35403. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35404. this.resourcePath = this.resourcePath || path;
  35405. const loader = new FileLoader( this.manager );
  35406. loader.setPath( this.path );
  35407. loader.setRequestHeader( this.requestHeader );
  35408. loader.setWithCredentials( this.withCredentials );
  35409. const text = await loader.loadAsync( url, onProgress );
  35410. let json;
  35411. try {
  35412. json = JSON.parse( text );
  35413. } catch ( e ) {
  35414. throw new Error( 'ObjectLoader: Can\'t parse ' + url + '. ' + e.message );
  35415. }
  35416. const metadata = json.metadata;
  35417. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35418. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35419. }
  35420. return await scope.parseAsync( json );
  35421. }
  35422. /**
  35423. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35424. * but can also be used directly to parse a previously loaded JSON structure.
  35425. *
  35426. * @param {Object} json - The serialized 3D object.
  35427. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35428. * @return {Object3D} The parsed 3D object.
  35429. */
  35430. parse( json, onLoad ) {
  35431. const animations = this.parseAnimations( json.animations );
  35432. const shapes = this.parseShapes( json.shapes );
  35433. const geometries = this.parseGeometries( json.geometries, shapes );
  35434. const images = this.parseImages( json.images, function () {
  35435. if ( onLoad !== undefined ) onLoad( object );
  35436. } );
  35437. const textures = this.parseTextures( json.textures, images );
  35438. const materials = this.parseMaterials( json.materials, textures );
  35439. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35440. const skeletons = this.parseSkeletons( json.skeletons, object );
  35441. this.bindSkeletons( object, skeletons );
  35442. this.bindLightTargets( object );
  35443. //
  35444. if ( onLoad !== undefined ) {
  35445. let hasImages = false;
  35446. for ( const uuid in images ) {
  35447. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35448. hasImages = true;
  35449. break;
  35450. }
  35451. }
  35452. if ( hasImages === false ) onLoad( object );
  35453. }
  35454. return object;
  35455. }
  35456. /**
  35457. * Async version of {@link ObjectLoader#parse}.
  35458. *
  35459. * @param {Object} json - The serialized 3D object.
  35460. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35461. */
  35462. async parseAsync( json ) {
  35463. const animations = this.parseAnimations( json.animations );
  35464. const shapes = this.parseShapes( json.shapes );
  35465. const geometries = this.parseGeometries( json.geometries, shapes );
  35466. const images = await this.parseImagesAsync( json.images );
  35467. const textures = this.parseTextures( json.textures, images );
  35468. const materials = this.parseMaterials( json.materials, textures );
  35469. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35470. const skeletons = this.parseSkeletons( json.skeletons, object );
  35471. this.bindSkeletons( object, skeletons );
  35472. this.bindLightTargets( object );
  35473. return object;
  35474. }
  35475. /**
  35476. * Registers the given geometry at the internal
  35477. * geometry library.
  35478. *
  35479. * @static
  35480. * @param {string} type - The geometry type.
  35481. * @param {BufferGeometry.constructor} geometryClass - The geometry class.
  35482. */
  35483. static registerGeometry( type, geometryClass ) {
  35484. _customGeometries[ type ] = geometryClass;
  35485. }
  35486. // internals
  35487. parseShapes( json ) {
  35488. const shapes = {};
  35489. if ( json !== undefined ) {
  35490. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35491. const shape = new Shape().fromJSON( json[ i ] );
  35492. shapes[ shape.uuid ] = shape;
  35493. }
  35494. }
  35495. return shapes;
  35496. }
  35497. parseSkeletons( json, object ) {
  35498. const skeletons = {};
  35499. const bones = {};
  35500. // generate bone lookup table
  35501. object.traverse( function ( child ) {
  35502. if ( child.isBone ) bones[ child.uuid ] = child;
  35503. } );
  35504. // create skeletons
  35505. if ( json !== undefined ) {
  35506. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35507. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35508. skeletons[ skeleton.uuid ] = skeleton;
  35509. }
  35510. }
  35511. return skeletons;
  35512. }
  35513. parseGeometries( json, shapes ) {
  35514. const geometries = {};
  35515. if ( json !== undefined ) {
  35516. const bufferGeometryLoader = new BufferGeometryLoader();
  35517. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35518. let geometry;
  35519. const data = json[ i ];
  35520. switch ( data.type ) {
  35521. case 'BufferGeometry':
  35522. case 'InstancedBufferGeometry':
  35523. geometry = bufferGeometryLoader.parse( data );
  35524. break;
  35525. default:
  35526. if ( data.type in Geometries ) {
  35527. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35528. } else if ( data.type in _customGeometries ) {
  35529. geometry = _customGeometries[ data.type ].fromJSON( data, shapes );
  35530. } else {
  35531. warn( `ObjectLoader: Unknown geometry type "${ data.type }". Use .registerGeometry() before starting the deserialization process.` );
  35532. }
  35533. }
  35534. geometry.uuid = data.uuid;
  35535. if ( data.name !== undefined ) geometry.name = data.name;
  35536. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35537. geometries[ data.uuid ] = geometry;
  35538. }
  35539. }
  35540. return geometries;
  35541. }
  35542. parseMaterials( json, textures ) {
  35543. const cache = {}; // MultiMaterial
  35544. const materials = {};
  35545. if ( json !== undefined ) {
  35546. const loader = new MaterialLoader();
  35547. loader.setTextures( textures );
  35548. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35549. const data = json[ i ];
  35550. if ( cache[ data.uuid ] === undefined ) {
  35551. cache[ data.uuid ] = loader.parse( data );
  35552. }
  35553. materials[ data.uuid ] = cache[ data.uuid ];
  35554. }
  35555. }
  35556. return materials;
  35557. }
  35558. parseAnimations( json ) {
  35559. const animations = {};
  35560. if ( json !== undefined ) {
  35561. for ( let i = 0; i < json.length; i ++ ) {
  35562. const data = json[ i ];
  35563. const clip = AnimationClip.parse( data );
  35564. animations[ clip.uuid ] = clip;
  35565. }
  35566. }
  35567. return animations;
  35568. }
  35569. parseImages( json, onLoad ) {
  35570. const scope = this;
  35571. const images = {};
  35572. let loader;
  35573. function loadImage( url ) {
  35574. scope.manager.itemStart( url );
  35575. return loader.load( url, function () {
  35576. scope.manager.itemEnd( url );
  35577. }, undefined, function () {
  35578. scope.manager.itemError( url );
  35579. scope.manager.itemEnd( url );
  35580. } );
  35581. }
  35582. function deserializeImage( image ) {
  35583. if ( typeof image === 'string' ) {
  35584. const url = image;
  35585. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35586. return loadImage( path );
  35587. } else {
  35588. if ( image.data ) {
  35589. return {
  35590. data: getTypedArray( image.type, image.data ),
  35591. width: image.width,
  35592. height: image.height
  35593. };
  35594. } else {
  35595. return null;
  35596. }
  35597. }
  35598. }
  35599. if ( json !== undefined && json.length > 0 ) {
  35600. const manager = new LoadingManager( onLoad );
  35601. loader = new ImageLoader( manager );
  35602. loader.setCrossOrigin( this.crossOrigin );
  35603. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35604. const image = json[ i ];
  35605. const url = image.url;
  35606. if ( Array.isArray( url ) ) {
  35607. // load array of images e.g CubeTexture
  35608. const imageArray = [];
  35609. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35610. const currentUrl = url[ j ];
  35611. const deserializedImage = deserializeImage( currentUrl );
  35612. if ( deserializedImage !== null ) {
  35613. if ( deserializedImage instanceof HTMLImageElement ) {
  35614. imageArray.push( deserializedImage );
  35615. } else {
  35616. // special case: handle array of data textures for cube textures
  35617. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35618. }
  35619. }
  35620. }
  35621. images[ image.uuid ] = new Source( imageArray );
  35622. } else {
  35623. // load single image
  35624. const deserializedImage = deserializeImage( image.url );
  35625. images[ image.uuid ] = new Source( deserializedImage );
  35626. }
  35627. }
  35628. }
  35629. return images;
  35630. }
  35631. async parseImagesAsync( json ) {
  35632. const scope = this;
  35633. const images = {};
  35634. let loader;
  35635. async function deserializeImage( image ) {
  35636. if ( typeof image === 'string' ) {
  35637. const url = image;
  35638. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35639. return await loader.loadAsync( path );
  35640. } else {
  35641. if ( image.data ) {
  35642. return {
  35643. data: getTypedArray( image.type, image.data ),
  35644. width: image.width,
  35645. height: image.height
  35646. };
  35647. } else {
  35648. return null;
  35649. }
  35650. }
  35651. }
  35652. if ( json !== undefined && json.length > 0 ) {
  35653. loader = new ImageLoader( this.manager );
  35654. loader.setCrossOrigin( this.crossOrigin );
  35655. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35656. const image = json[ i ];
  35657. const url = image.url;
  35658. if ( Array.isArray( url ) ) {
  35659. // load array of images e.g CubeTexture
  35660. const imageArray = [];
  35661. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35662. const currentUrl = url[ j ];
  35663. const deserializedImage = await deserializeImage( currentUrl );
  35664. if ( deserializedImage !== null ) {
  35665. if ( deserializedImage instanceof HTMLImageElement ) {
  35666. imageArray.push( deserializedImage );
  35667. } else {
  35668. // special case: handle array of data textures for cube textures
  35669. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35670. }
  35671. }
  35672. }
  35673. images[ image.uuid ] = new Source( imageArray );
  35674. } else {
  35675. // load single image
  35676. const deserializedImage = await deserializeImage( image.url );
  35677. images[ image.uuid ] = new Source( deserializedImage );
  35678. }
  35679. }
  35680. }
  35681. return images;
  35682. }
  35683. parseTextures( json, images ) {
  35684. function parseConstant( value, type ) {
  35685. if ( typeof value === 'number' ) return value;
  35686. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35687. return type[ value ];
  35688. }
  35689. const textures = {};
  35690. if ( json !== undefined ) {
  35691. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35692. const data = json[ i ];
  35693. if ( data.image === undefined ) {
  35694. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35695. }
  35696. if ( images[ data.image ] === undefined ) {
  35697. warn( 'ObjectLoader: Undefined image', data.image );
  35698. }
  35699. const source = images[ data.image ];
  35700. const image = source.data;
  35701. let texture;
  35702. if ( Array.isArray( image ) ) {
  35703. texture = new CubeTexture();
  35704. if ( image.length === 6 ) texture.needsUpdate = true;
  35705. } else {
  35706. if ( image && image.data ) {
  35707. texture = new DataTexture();
  35708. } else {
  35709. texture = new Texture();
  35710. }
  35711. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35712. }
  35713. texture.source = source;
  35714. texture.uuid = data.uuid;
  35715. if ( data.name !== undefined ) texture.name = data.name;
  35716. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35717. if ( data.channel !== undefined ) texture.channel = data.channel;
  35718. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35719. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35720. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35721. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35722. if ( data.wrap !== undefined ) {
  35723. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35724. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35725. }
  35726. if ( data.format !== undefined ) texture.format = data.format;
  35727. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35728. if ( data.type !== undefined ) texture.type = data.type;
  35729. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35730. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35731. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35732. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35733. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35734. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35735. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35736. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35737. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35738. if ( data.normalized !== undefined ) texture.normalized = data.normalized;
  35739. if ( data.userData !== undefined ) texture.userData = data.userData;
  35740. textures[ data.uuid ] = texture;
  35741. }
  35742. }
  35743. return textures;
  35744. }
  35745. parseObject( data, geometries, materials, textures, animations ) {
  35746. let object;
  35747. function getGeometry( name ) {
  35748. if ( geometries[ name ] === undefined ) {
  35749. warn( 'ObjectLoader: Undefined geometry', name );
  35750. }
  35751. return geometries[ name ];
  35752. }
  35753. function getMaterial( name ) {
  35754. if ( name === undefined ) return undefined;
  35755. if ( Array.isArray( name ) ) {
  35756. const array = [];
  35757. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35758. const uuid = name[ i ];
  35759. if ( materials[ uuid ] === undefined ) {
  35760. warn( 'ObjectLoader: Undefined material', uuid );
  35761. }
  35762. array.push( materials[ uuid ] );
  35763. }
  35764. return array;
  35765. }
  35766. if ( materials[ name ] === undefined ) {
  35767. warn( 'ObjectLoader: Undefined material', name );
  35768. }
  35769. return materials[ name ];
  35770. }
  35771. function getTexture( uuid ) {
  35772. if ( textures[ uuid ] === undefined ) {
  35773. warn( 'ObjectLoader: Undefined texture', uuid );
  35774. }
  35775. return textures[ uuid ];
  35776. }
  35777. let geometry, material;
  35778. switch ( data.type ) {
  35779. case 'Scene':
  35780. object = new Scene();
  35781. if ( data.background !== undefined ) {
  35782. if ( Number.isInteger( data.background ) ) {
  35783. object.background = new Color( data.background );
  35784. } else {
  35785. object.background = getTexture( data.background );
  35786. }
  35787. }
  35788. if ( data.environment !== undefined ) {
  35789. object.environment = getTexture( data.environment );
  35790. }
  35791. if ( data.fog !== undefined ) {
  35792. if ( data.fog.type === 'Fog' ) {
  35793. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35794. } else if ( data.fog.type === 'FogExp2' ) {
  35795. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35796. }
  35797. if ( data.fog.name !== '' ) {
  35798. object.fog.name = data.fog.name;
  35799. }
  35800. }
  35801. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35802. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35803. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35804. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35805. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35806. break;
  35807. case 'PerspectiveCamera':
  35808. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35809. if ( data.focus !== undefined ) object.focus = data.focus;
  35810. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35811. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35812. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35813. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35814. break;
  35815. case 'OrthographicCamera':
  35816. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35817. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35818. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35819. break;
  35820. case 'AmbientLight':
  35821. object = new AmbientLight( data.color, data.intensity );
  35822. break;
  35823. case 'DirectionalLight':
  35824. object = new DirectionalLight( data.color, data.intensity );
  35825. object.target = data.target || '';
  35826. break;
  35827. case 'PointLight':
  35828. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35829. break;
  35830. case 'RectAreaLight':
  35831. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35832. break;
  35833. case 'SpotLight':
  35834. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35835. object.target = data.target || '';
  35836. break;
  35837. case 'HemisphereLight':
  35838. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35839. break;
  35840. case 'LightProbe':
  35841. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35842. object = new LightProbe( sh, data.intensity );
  35843. break;
  35844. case 'SkinnedMesh':
  35845. geometry = getGeometry( data.geometry );
  35846. material = getMaterial( data.material );
  35847. object = new SkinnedMesh( geometry, material );
  35848. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35849. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35850. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35851. break;
  35852. case 'Mesh':
  35853. geometry = getGeometry( data.geometry );
  35854. material = getMaterial( data.material );
  35855. object = new Mesh( geometry, material );
  35856. break;
  35857. case 'InstancedMesh':
  35858. geometry = getGeometry( data.geometry );
  35859. material = getMaterial( data.material );
  35860. const count = data.count;
  35861. const instanceMatrix = data.instanceMatrix;
  35862. const instanceColor = data.instanceColor;
  35863. object = new InstancedMesh( geometry, material, count );
  35864. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35865. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35866. break;
  35867. case 'BatchedMesh':
  35868. geometry = getGeometry( data.geometry );
  35869. material = getMaterial( data.material );
  35870. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35871. object.geometry = geometry;
  35872. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35873. object.sortObjects = data.sortObjects;
  35874. object._drawRanges = data.drawRanges;
  35875. object._reservedRanges = data.reservedRanges;
  35876. object._geometryInfo = data.geometryInfo.map( info => {
  35877. let box = null;
  35878. let sphere = null;
  35879. if ( info.boundingBox !== undefined ) {
  35880. box = new Box3().fromJSON( info.boundingBox );
  35881. }
  35882. if ( info.boundingSphere !== undefined ) {
  35883. sphere = new Sphere().fromJSON( info.boundingSphere );
  35884. }
  35885. return {
  35886. ...info,
  35887. boundingBox: box,
  35888. boundingSphere: sphere
  35889. };
  35890. } );
  35891. object._instanceInfo = data.instanceInfo;
  35892. object._availableInstanceIds = data._availableInstanceIds;
  35893. object._availableGeometryIds = data._availableGeometryIds;
  35894. object._nextIndexStart = data.nextIndexStart;
  35895. object._nextVertexStart = data.nextVertexStart;
  35896. object._geometryCount = data.geometryCount;
  35897. object._maxInstanceCount = data.maxInstanceCount;
  35898. object._maxVertexCount = data.maxVertexCount;
  35899. object._maxIndexCount = data.maxIndexCount;
  35900. object._geometryInitialized = data.geometryInitialized;
  35901. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35902. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35903. if ( data.colorsTexture !== undefined ) {
  35904. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35905. }
  35906. if ( data.boundingSphere !== undefined ) {
  35907. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35908. }
  35909. if ( data.boundingBox !== undefined ) {
  35910. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35911. }
  35912. break;
  35913. case 'LOD':
  35914. object = new LOD();
  35915. break;
  35916. case 'Line':
  35917. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35918. break;
  35919. case 'LineLoop':
  35920. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35921. break;
  35922. case 'LineSegments':
  35923. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35924. break;
  35925. case 'PointCloud':
  35926. case 'Points':
  35927. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35928. break;
  35929. case 'Sprite':
  35930. object = new Sprite( getMaterial( data.material ) );
  35931. break;
  35932. case 'Group':
  35933. object = new Group();
  35934. break;
  35935. case 'Bone':
  35936. object = new Bone();
  35937. break;
  35938. default:
  35939. object = new Object3D();
  35940. }
  35941. object.uuid = data.uuid;
  35942. if ( data.name !== undefined ) object.name = data.name;
  35943. if ( data.matrix !== undefined ) {
  35944. object.matrix.fromArray( data.matrix );
  35945. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35946. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35947. } else {
  35948. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35949. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35950. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35951. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35952. }
  35953. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35954. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  35955. if ( data.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, data.morphTargetDictionary );
  35956. if ( data.morphTargetInfluences !== undefined ) object.morphTargetInfluences = data.morphTargetInfluences.slice();
  35957. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35958. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35959. if ( data.shadow ) {
  35960. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35961. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35962. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35963. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35964. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35965. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35966. }
  35967. if ( data.visible !== undefined ) object.visible = data.visible;
  35968. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35969. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35970. if ( data.static !== undefined ) object.static = data.static;
  35971. if ( data.userData !== undefined ) object.userData = data.userData;
  35972. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35973. if ( data.children !== undefined ) {
  35974. const children = data.children;
  35975. for ( let i = 0; i < children.length; i ++ ) {
  35976. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35977. }
  35978. }
  35979. if ( data.animations !== undefined ) {
  35980. const objectAnimations = data.animations;
  35981. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35982. const uuid = objectAnimations[ i ];
  35983. object.animations.push( animations[ uuid ] );
  35984. }
  35985. }
  35986. if ( data.type === 'LOD' ) {
  35987. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35988. const levels = data.levels;
  35989. for ( let l = 0; l < levels.length; l ++ ) {
  35990. const level = levels[ l ];
  35991. const child = object.getObjectByProperty( 'uuid', level.object );
  35992. if ( child !== undefined ) {
  35993. object.addLevel( child, level.distance, level.hysteresis );
  35994. }
  35995. }
  35996. }
  35997. return object;
  35998. }
  35999. bindSkeletons( object, skeletons ) {
  36000. if ( Object.keys( skeletons ).length === 0 ) return;
  36001. object.traverse( function ( child ) {
  36002. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  36003. const skeleton = skeletons[ child.skeleton ];
  36004. if ( skeleton === undefined ) {
  36005. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  36006. } else {
  36007. child.bind( skeleton, child.bindMatrix );
  36008. }
  36009. }
  36010. } );
  36011. }
  36012. bindLightTargets( object ) {
  36013. object.traverse( function ( child ) {
  36014. if ( child.isDirectionalLight || child.isSpotLight ) {
  36015. const uuid = child.target;
  36016. const target = object.getObjectByProperty( 'uuid', uuid );
  36017. if ( target !== undefined ) {
  36018. child.target = target;
  36019. } else {
  36020. child.target = new Object3D();
  36021. }
  36022. }
  36023. } );
  36024. }
  36025. }
  36026. const TEXTURE_MAPPING = {
  36027. UVMapping: UVMapping,
  36028. CubeReflectionMapping: CubeReflectionMapping,
  36029. CubeRefractionMapping: CubeRefractionMapping,
  36030. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  36031. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  36032. CubeUVReflectionMapping: CubeUVReflectionMapping
  36033. };
  36034. const TEXTURE_WRAPPING = {
  36035. RepeatWrapping: RepeatWrapping,
  36036. ClampToEdgeWrapping: ClampToEdgeWrapping,
  36037. MirroredRepeatWrapping: MirroredRepeatWrapping
  36038. };
  36039. const TEXTURE_FILTER = {
  36040. NearestFilter: NearestFilter,
  36041. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  36042. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  36043. LinearFilter: LinearFilter,
  36044. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  36045. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  36046. };
  36047. const _errorMap = new WeakMap();
  36048. /**
  36049. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  36050. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  36051. * textures for rendering.
  36052. *
  36053. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  36054. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  36055. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  36056. *
  36057. * To match the default behaviour of {@link Texture}, the following options are needed:
  36058. *
  36059. * ```js
  36060. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  36061. * ```
  36062. *
  36063. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  36064. *
  36065. * ```js
  36066. * const loader = new THREE.ImageBitmapLoader();
  36067. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  36068. * const imageBitmap = await loader.loadAsync( 'image.png' );
  36069. *
  36070. * const texture = new THREE.Texture( imageBitmap );
  36071. * texture.needsUpdate = true;
  36072. * ```
  36073. *
  36074. * @augments Loader
  36075. */
  36076. class ImageBitmapLoader extends Loader {
  36077. /**
  36078. * Constructs a new image bitmap loader.
  36079. *
  36080. * @param {LoadingManager} [manager] - The loading manager.
  36081. */
  36082. constructor( manager ) {
  36083. super( manager );
  36084. /**
  36085. * This flag can be used for type testing.
  36086. *
  36087. * @type {boolean}
  36088. * @readonly
  36089. * @default true
  36090. */
  36091. this.isImageBitmapLoader = true;
  36092. if ( typeof createImageBitmap === 'undefined' ) {
  36093. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  36094. }
  36095. if ( typeof fetch === 'undefined' ) {
  36096. warn( 'ImageBitmapLoader: fetch() not supported.' );
  36097. }
  36098. /**
  36099. * Represents the loader options.
  36100. *
  36101. * @type {Object}
  36102. * @default {premultiplyAlpha:'none'}
  36103. */
  36104. this.options = { premultiplyAlpha: 'none' };
  36105. /**
  36106. * Used for aborting requests.
  36107. *
  36108. * @private
  36109. * @type {AbortController}
  36110. */
  36111. this._abortController = new AbortController();
  36112. }
  36113. /**
  36114. * Sets the given loader options. The structure of the object must match the `options` parameter of
  36115. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  36116. *
  36117. * Note: When caching is enabled, the cache key is based on the URL only. Loading the same URL with
  36118. * different options will return the cached result of the first request.
  36119. *
  36120. * @param {Object} options - The loader options to set.
  36121. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  36122. */
  36123. setOptions( options ) {
  36124. this.options = options;
  36125. return this;
  36126. }
  36127. /**
  36128. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  36129. *
  36130. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36131. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  36132. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  36133. * @param {onErrorCallback} onError - Executed when errors occur.
  36134. */
  36135. load( url, onLoad, onProgress, onError ) {
  36136. if ( url === undefined ) url = '';
  36137. if ( this.path !== undefined ) url = this.path + url;
  36138. url = this.manager.resolveURL( url );
  36139. const scope = this;
  36140. const cached = Cache.get( `image-bitmap:${url}` );
  36141. if ( cached !== undefined ) {
  36142. scope.manager.itemStart( url );
  36143. // If cached is a promise, wait for it to resolve
  36144. if ( cached.then ) {
  36145. cached.then( imageBitmap => {
  36146. // check if there is an error for the cached promise
  36147. if ( _errorMap.has( cached ) === true ) {
  36148. if ( onError ) onError( _errorMap.get( cached ) );
  36149. scope.manager.itemError( url );
  36150. scope.manager.itemEnd( url );
  36151. } else {
  36152. if ( onLoad ) onLoad( imageBitmap );
  36153. scope.manager.itemEnd( url );
  36154. }
  36155. } );
  36156. return;
  36157. }
  36158. // If cached is not a promise (i.e., it's already an imageBitmap)
  36159. setTimeout( function () {
  36160. if ( onLoad ) onLoad( cached );
  36161. scope.manager.itemEnd( url );
  36162. }, 0 );
  36163. return;
  36164. }
  36165. const fetchOptions = {};
  36166. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36167. fetchOptions.headers = this.requestHeader;
  36168. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36169. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36170. return res.blob();
  36171. } ).then( function ( blob ) {
  36172. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36173. } ).then( function ( imageBitmap ) {
  36174. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36175. if ( onLoad ) onLoad( imageBitmap );
  36176. scope.manager.itemEnd( url );
  36177. } ).catch( function ( e ) {
  36178. if ( onError ) onError( e );
  36179. _errorMap.set( promise, e );
  36180. Cache.remove( `image-bitmap:${url}` );
  36181. scope.manager.itemError( url );
  36182. scope.manager.itemEnd( url );
  36183. } );
  36184. Cache.add( `image-bitmap:${url}`, promise );
  36185. scope.manager.itemStart( url );
  36186. }
  36187. /**
  36188. * Aborts ongoing fetch requests.
  36189. *
  36190. * @return {ImageBitmapLoader} A reference to this instance.
  36191. */
  36192. abort() {
  36193. this._abortController.abort();
  36194. this._abortController = new AbortController();
  36195. return this;
  36196. }
  36197. }
  36198. let _context;
  36199. /**
  36200. * Manages the global audio context in the engine.
  36201. *
  36202. * @hideconstructor
  36203. */
  36204. class AudioContext {
  36205. /**
  36206. * Returns the global native audio context.
  36207. *
  36208. * @return {Window.AudioContext} The native audio context.
  36209. */
  36210. static getContext() {
  36211. if ( _context === undefined ) {
  36212. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36213. }
  36214. return _context;
  36215. }
  36216. /**
  36217. * Allows to set the global native audio context from outside.
  36218. *
  36219. * @param {Window.AudioContext} value - The native context to set.
  36220. */
  36221. static setContext( value ) {
  36222. _context = value;
  36223. }
  36224. }
  36225. /**
  36226. * Class for loading audio buffers. Audios are internally
  36227. * loaded via {@link FileLoader}.
  36228. *
  36229. * ```js
  36230. * const audioListener = new THREE.AudioListener();
  36231. * const ambientSound = new THREE.Audio( audioListener );
  36232. *
  36233. * const loader = new THREE.AudioLoader();
  36234. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36235. *
  36236. * ambientSound.setBuffer( audioBuffer );
  36237. * ambientSound.play();
  36238. * ```
  36239. *
  36240. * @augments Loader
  36241. */
  36242. class AudioLoader extends Loader {
  36243. /**
  36244. * Constructs a new audio loader.
  36245. *
  36246. * @param {LoadingManager} [manager] - The loading manager.
  36247. */
  36248. constructor( manager ) {
  36249. super( manager );
  36250. }
  36251. /**
  36252. * Starts loading from the given URL and passes the loaded audio buffer
  36253. * to the `onLoad()` callback.
  36254. *
  36255. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36256. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36257. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36258. * @param {onErrorCallback} onError - Executed when errors occur.
  36259. */
  36260. load( url, onLoad, onProgress, onError ) {
  36261. const scope = this;
  36262. const loader = new FileLoader( this.manager );
  36263. loader.setResponseType( 'arraybuffer' );
  36264. loader.setPath( this.path );
  36265. loader.setRequestHeader( this.requestHeader );
  36266. loader.setWithCredentials( this.withCredentials );
  36267. loader.load( url, function ( buffer ) {
  36268. try {
  36269. // Create a copy of the buffer. The `decodeAudioData` method
  36270. // detaches the buffer when complete, preventing reuse.
  36271. const bufferCopy = buffer.slice( 0 );
  36272. const context = AudioContext.getContext();
  36273. const decodeUrl = url + '#decode';
  36274. scope.manager.itemStart( decodeUrl ); // prevent loading manager from completing too early, see #33378
  36275. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36276. onLoad( audioBuffer );
  36277. scope.manager.itemEnd( decodeUrl );
  36278. } ).catch( function ( e ) {
  36279. handleError( e );
  36280. scope.manager.itemEnd( decodeUrl );
  36281. } );
  36282. } catch ( e ) {
  36283. handleError( e );
  36284. }
  36285. }, onProgress, onError );
  36286. function handleError( e ) {
  36287. if ( onError ) {
  36288. onError( e );
  36289. } else {
  36290. error( e );
  36291. }
  36292. scope.manager.itemError( url );
  36293. }
  36294. }
  36295. }
  36296. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36297. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36298. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36299. /**
  36300. * A special type of camera that uses two perspective cameras with
  36301. * stereoscopic projection. Can be used for rendering stereo effects
  36302. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36303. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36304. */
  36305. class StereoCamera {
  36306. /**
  36307. * Constructs a new stereo camera.
  36308. */
  36309. constructor() {
  36310. /**
  36311. * The type property is used for detecting the object type
  36312. * in context of serialization/deserialization.
  36313. *
  36314. * @type {string}
  36315. * @readonly
  36316. */
  36317. this.type = 'StereoCamera';
  36318. /**
  36319. * The aspect.
  36320. *
  36321. * @type {number}
  36322. * @default 1
  36323. */
  36324. this.aspect = 1;
  36325. /**
  36326. * The eye separation which represents the distance
  36327. * between the left and right camera.
  36328. *
  36329. * @type {number}
  36330. * @default 0.064
  36331. */
  36332. this.eyeSep = 0.064;
  36333. /**
  36334. * The camera representing the left eye. This is added to layer `1` so objects to be
  36335. * rendered by the left camera must also be added to this layer.
  36336. *
  36337. * @type {PerspectiveCamera}
  36338. */
  36339. this.cameraL = new PerspectiveCamera();
  36340. this.cameraL.layers.enable( 1 );
  36341. this.cameraL.matrixAutoUpdate = false;
  36342. /**
  36343. * The camera representing the right eye. This is added to layer `2` so objects to be
  36344. * rendered by the right camera must also be added to this layer.
  36345. *
  36346. * @type {PerspectiveCamera}
  36347. */
  36348. this.cameraR = new PerspectiveCamera();
  36349. this.cameraR.layers.enable( 2 );
  36350. this.cameraR.matrixAutoUpdate = false;
  36351. this._cache = {
  36352. focus: null,
  36353. fov: null,
  36354. aspect: null,
  36355. near: null,
  36356. far: null,
  36357. zoom: null,
  36358. eyeSep: null
  36359. };
  36360. }
  36361. /**
  36362. * Updates the stereo camera based on the given perspective camera.
  36363. *
  36364. * @param {PerspectiveCamera} camera - The perspective camera.
  36365. */
  36366. update( camera ) {
  36367. const cache = this._cache;
  36368. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36369. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36370. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36371. if ( needsUpdate ) {
  36372. cache.focus = camera.focus;
  36373. cache.fov = camera.fov;
  36374. cache.aspect = camera.aspect * this.aspect;
  36375. cache.near = camera.near;
  36376. cache.far = camera.far;
  36377. cache.zoom = camera.zoom;
  36378. cache.eyeSep = this.eyeSep;
  36379. // Off-axis stereoscopic effect based on
  36380. // http://paulbourke.net/stereographics/stereorender/
  36381. _projectionMatrix.copy( camera.projectionMatrix );
  36382. const eyeSepHalf = cache.eyeSep / 2;
  36383. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36384. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36385. let xmin, xmax;
  36386. // translate xOffset
  36387. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36388. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36389. // for left eye
  36390. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36391. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36392. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36393. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36394. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36395. // for right eye
  36396. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36397. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36398. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36399. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36400. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36401. }
  36402. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36403. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36404. }
  36405. }
  36406. const fov = -90; // negative fov is not an error
  36407. const aspect = 1;
  36408. /**
  36409. * A special type of camera that is positioned in 3D space to render its surroundings into a
  36410. * cube render target. The render target can then be used as an environment map for rendering
  36411. * realtime reflections in your scene.
  36412. *
  36413. * ```js
  36414. * // Create cube render target
  36415. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  36416. *
  36417. * // Create cube camera
  36418. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  36419. * scene.add( cubeCamera );
  36420. *
  36421. * // Create car
  36422. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  36423. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  36424. * scene.add( car );
  36425. *
  36426. * // Update the render target cube
  36427. * car.visible = false;
  36428. * cubeCamera.position.copy( car.position );
  36429. * cubeCamera.update( renderer, scene );
  36430. *
  36431. * // Render the scene
  36432. * car.visible = true;
  36433. * renderer.render( scene, camera );
  36434. * ```
  36435. *
  36436. * @augments Object3D
  36437. */
  36438. class CubeCamera extends Object3D {
  36439. /**
  36440. * Constructs a new cube camera.
  36441. *
  36442. * @param {number} near - The camera's near plane.
  36443. * @param {number} far - The camera's far plane.
  36444. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  36445. */
  36446. constructor( near, far, renderTarget ) {
  36447. super();
  36448. this.type = 'CubeCamera';
  36449. /**
  36450. * A reference to the cube render target.
  36451. *
  36452. * @type {WebGLCubeRenderTarget}
  36453. */
  36454. this.renderTarget = renderTarget;
  36455. /**
  36456. * The current active coordinate system.
  36457. *
  36458. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  36459. * @default null
  36460. */
  36461. this.coordinateSystem = null;
  36462. /**
  36463. * The current active mipmap level
  36464. *
  36465. * @type {number}
  36466. * @default 0
  36467. */
  36468. this.activeMipmapLevel = 0;
  36469. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  36470. cameraPX.layers = this.layers;
  36471. this.add( cameraPX );
  36472. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  36473. cameraNX.layers = this.layers;
  36474. this.add( cameraNX );
  36475. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  36476. cameraPY.layers = this.layers;
  36477. this.add( cameraPY );
  36478. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  36479. cameraNY.layers = this.layers;
  36480. this.add( cameraNY );
  36481. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  36482. cameraPZ.layers = this.layers;
  36483. this.add( cameraPZ );
  36484. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  36485. cameraNZ.layers = this.layers;
  36486. this.add( cameraNZ );
  36487. }
  36488. /**
  36489. * Must be called when the coordinate system of the cube camera is changed.
  36490. */
  36491. updateCoordinateSystem() {
  36492. const coordinateSystem = this.coordinateSystem;
  36493. const cameras = this.children.concat();
  36494. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  36495. for ( const camera of cameras ) this.remove( camera );
  36496. if ( coordinateSystem === WebGLCoordinateSystem ) {
  36497. cameraPX.up.set( 0, 1, 0 );
  36498. cameraPX.lookAt( 1, 0, 0 );
  36499. cameraNX.up.set( 0, 1, 0 );
  36500. cameraNX.lookAt( -1, 0, 0 );
  36501. cameraPY.up.set( 0, 0, -1 );
  36502. cameraPY.lookAt( 0, 1, 0 );
  36503. cameraNY.up.set( 0, 0, 1 );
  36504. cameraNY.lookAt( 0, -1, 0 );
  36505. cameraPZ.up.set( 0, 1, 0 );
  36506. cameraPZ.lookAt( 0, 0, 1 );
  36507. cameraNZ.up.set( 0, 1, 0 );
  36508. cameraNZ.lookAt( 0, 0, -1 );
  36509. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  36510. cameraPX.up.set( 0, -1, 0 );
  36511. cameraPX.lookAt( -1, 0, 0 );
  36512. cameraNX.up.set( 0, -1, 0 );
  36513. cameraNX.lookAt( 1, 0, 0 );
  36514. cameraPY.up.set( 0, 0, 1 );
  36515. cameraPY.lookAt( 0, 1, 0 );
  36516. cameraNY.up.set( 0, 0, -1 );
  36517. cameraNY.lookAt( 0, -1, 0 );
  36518. cameraPZ.up.set( 0, -1, 0 );
  36519. cameraPZ.lookAt( 0, 0, 1 );
  36520. cameraNZ.up.set( 0, -1, 0 );
  36521. cameraNZ.lookAt( 0, 0, -1 );
  36522. } else {
  36523. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  36524. }
  36525. for ( const camera of cameras ) {
  36526. this.add( camera );
  36527. camera.updateMatrixWorld();
  36528. }
  36529. }
  36530. /**
  36531. * Calling this method will render the given scene with the given renderer
  36532. * into the cube render target of the camera.
  36533. *
  36534. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  36535. * @param {Scene} scene - The scene to render.
  36536. */
  36537. update( renderer, scene ) {
  36538. if ( this.parent === null ) this.updateMatrixWorld();
  36539. const { renderTarget, activeMipmapLevel } = this;
  36540. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  36541. this.coordinateSystem = renderer.coordinateSystem;
  36542. this.updateCoordinateSystem();
  36543. }
  36544. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  36545. const currentRenderTarget = renderer.getRenderTarget();
  36546. const currentActiveCubeFace = renderer.getActiveCubeFace();
  36547. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  36548. const currentXrEnabled = renderer.xr.enabled;
  36549. renderer.xr.enabled = false;
  36550. const generateMipmaps = renderTarget.texture.generateMipmaps;
  36551. renderTarget.texture.generateMipmaps = false;
  36552. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  36553. let reversedDepthBuffer = false;
  36554. if ( renderer.isWebGLRenderer === true ) {
  36555. reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  36556. } else {
  36557. reversedDepthBuffer = renderer.reversedDepthBuffer;
  36558. }
  36559. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  36560. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36561. renderer.render( scene, cameraPX );
  36562. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  36563. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36564. renderer.render( scene, cameraNX );
  36565. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  36566. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36567. renderer.render( scene, cameraPY );
  36568. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  36569. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36570. renderer.render( scene, cameraNY );
  36571. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  36572. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36573. renderer.render( scene, cameraPZ );
  36574. // mipmaps are generated during the last call of render()
  36575. // at this point, all sides of the cube render target are defined
  36576. renderTarget.texture.generateMipmaps = generateMipmaps;
  36577. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  36578. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36579. renderer.render( scene, cameraNZ );
  36580. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  36581. renderer.xr.enabled = currentXrEnabled;
  36582. renderTarget.texture.needsPMREMUpdate = true;
  36583. }
  36584. }
  36585. /**
  36586. * This type of camera can be used in order to efficiently render a scene with a
  36587. * predefined set of cameras. This is an important performance aspect for
  36588. * rendering VR scenes.
  36589. *
  36590. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36591. * to define for each sub camera the `viewport` property which determines the
  36592. * part of the viewport that is rendered with this camera.
  36593. *
  36594. * @augments PerspectiveCamera
  36595. */
  36596. class ArrayCamera extends PerspectiveCamera {
  36597. /**
  36598. * Constructs a new array camera.
  36599. *
  36600. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36601. */
  36602. constructor( array = [] ) {
  36603. super();
  36604. /**
  36605. * This flag can be used for type testing.
  36606. *
  36607. * @type {boolean}
  36608. * @readonly
  36609. * @default true
  36610. */
  36611. this.isArrayCamera = true;
  36612. /**
  36613. * Whether this camera is used with multiview rendering or not.
  36614. *
  36615. * @type {boolean}
  36616. * @readonly
  36617. * @default false
  36618. */
  36619. this.isMultiViewCamera = false;
  36620. /**
  36621. * An array of perspective sub cameras.
  36622. *
  36623. * @type {Array<PerspectiveCamera>}
  36624. */
  36625. this.cameras = array;
  36626. }
  36627. }
  36628. /**
  36629. * This class is an alternative to {@link Clock} with a different API design and behavior.
  36630. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  36631. *
  36632. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  36633. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  36634. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  36635. * is inactive (e.g. tab switched or browser hidden).
  36636. *
  36637. * ```js
  36638. * const timer = new Timer();
  36639. * timer.connect( document ); // use Page Visibility API
  36640. * ```
  36641. */
  36642. class Timer {
  36643. /**
  36644. * Constructs a new timer.
  36645. */
  36646. constructor() {
  36647. this._previousTime = 0;
  36648. this._currentTime = 0;
  36649. this._startTime = performance.now();
  36650. this._delta = 0;
  36651. this._elapsed = 0;
  36652. this._timescale = 1;
  36653. this._document = null;
  36654. this._pageVisibilityHandler = null;
  36655. }
  36656. /**
  36657. * Connect the timer to the given document.Calling this method is not mandatory to
  36658. * use the timer but enables the usage of the Page Visibility API to avoid large time
  36659. * delta values.
  36660. *
  36661. * @param {Document} document - The document.
  36662. */
  36663. connect( document ) {
  36664. this._document = document;
  36665. // use Page Visibility API to avoid large time delta values
  36666. if ( document.hidden !== undefined ) {
  36667. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  36668. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  36669. }
  36670. }
  36671. /**
  36672. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  36673. */
  36674. disconnect() {
  36675. if ( this._pageVisibilityHandler !== null ) {
  36676. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  36677. this._pageVisibilityHandler = null;
  36678. }
  36679. this._document = null;
  36680. }
  36681. /**
  36682. * Returns the time delta in seconds.
  36683. *
  36684. * @return {number} The time delta in second.
  36685. */
  36686. getDelta() {
  36687. return this._delta / 1000;
  36688. }
  36689. /**
  36690. * Returns the elapsed time in seconds.
  36691. *
  36692. * @return {number} The elapsed time in second.
  36693. */
  36694. getElapsed() {
  36695. return this._elapsed / 1000;
  36696. }
  36697. /**
  36698. * Returns the timescale.
  36699. *
  36700. * @return {number} The timescale.
  36701. */
  36702. getTimescale() {
  36703. return this._timescale;
  36704. }
  36705. /**
  36706. * Sets the given timescale which scale the time delta computation
  36707. * in `update()`.
  36708. *
  36709. * @param {number} timescale - The timescale to set.
  36710. * @return {Timer} A reference to this timer.
  36711. */
  36712. setTimescale( timescale ) {
  36713. this._timescale = timescale;
  36714. return this;
  36715. }
  36716. /**
  36717. * Resets the time computation for the current simulation step.
  36718. *
  36719. * @return {Timer} A reference to this timer.
  36720. */
  36721. reset() {
  36722. this._currentTime = performance.now() - this._startTime;
  36723. return this;
  36724. }
  36725. /**
  36726. * Can be used to free all internal resources. Usually called when
  36727. * the timer instance isn't required anymore.
  36728. */
  36729. dispose() {
  36730. this.disconnect();
  36731. }
  36732. /**
  36733. * Updates the internal state of the timer. This method should be called
  36734. * once per simulation step and before you perform queries against the timer
  36735. * (e.g. via `getDelta()`).
  36736. *
  36737. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  36738. * from the `requestAnimationFrame` callback argument. If not provided, the current
  36739. * time will be determined with `performance.now`.
  36740. * @return {Timer} A reference to this timer.
  36741. */
  36742. update( timestamp ) {
  36743. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  36744. this._delta = 0;
  36745. } else {
  36746. this._previousTime = this._currentTime;
  36747. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  36748. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  36749. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  36750. }
  36751. return this;
  36752. }
  36753. }
  36754. function handleVisibilityChange() {
  36755. if ( this._document.hidden === false ) this.reset();
  36756. }
  36757. const _position$1 = /*@__PURE__*/ new Vector3();
  36758. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36759. const _scale$1 = /*@__PURE__*/ new Vector3();
  36760. const _forward = /*@__PURE__*/ new Vector3();
  36761. const _up = /*@__PURE__*/ new Vector3();
  36762. /**
  36763. * The class represents a virtual listener of the all positional and non-positional audio effects
  36764. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36765. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36766. *
  36767. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36768. * camera represents the 3D transformation of the listener.
  36769. *
  36770. * @augments Object3D
  36771. */
  36772. class AudioListener extends Object3D {
  36773. /**
  36774. * Constructs a new audio listener.
  36775. */
  36776. constructor() {
  36777. super();
  36778. this.type = 'AudioListener';
  36779. /**
  36780. * The native audio context.
  36781. *
  36782. * @type {AudioContext}
  36783. * @readonly
  36784. */
  36785. this.context = AudioContext.getContext();
  36786. /**
  36787. * The gain node used for volume control.
  36788. *
  36789. * @type {GainNode}
  36790. * @readonly
  36791. */
  36792. this.gain = this.context.createGain();
  36793. this.gain.connect( this.context.destination );
  36794. /**
  36795. * An optional filter.
  36796. *
  36797. * Defined via {@link AudioListener#setFilter}.
  36798. *
  36799. * @type {?AudioNode}
  36800. * @default null
  36801. * @readonly
  36802. */
  36803. this.filter = null;
  36804. /**
  36805. * Time delta values required for `linearRampToValueAtTime()` usage.
  36806. *
  36807. * @type {number}
  36808. * @default 0
  36809. * @readonly
  36810. */
  36811. this.timeDelta = 0;
  36812. // private
  36813. this._timer = new Timer();
  36814. }
  36815. /**
  36816. * Returns the listener's input node.
  36817. *
  36818. * This method is used by other audio nodes to connect to this listener.
  36819. *
  36820. * @return {GainNode} The input node.
  36821. */
  36822. getInput() {
  36823. return this.gain;
  36824. }
  36825. /**
  36826. * Removes the current filter from this listener.
  36827. *
  36828. * @return {AudioListener} A reference to this listener.
  36829. */
  36830. removeFilter() {
  36831. if ( this.filter !== null ) {
  36832. this.gain.disconnect( this.filter );
  36833. this.filter.disconnect( this.context.destination );
  36834. this.gain.connect( this.context.destination );
  36835. this.filter = null;
  36836. }
  36837. return this;
  36838. }
  36839. /**
  36840. * Returns the current set filter.
  36841. *
  36842. * @return {?AudioNode} The filter.
  36843. */
  36844. getFilter() {
  36845. return this.filter;
  36846. }
  36847. /**
  36848. * Sets the given filter to this listener.
  36849. *
  36850. * @param {AudioNode} value - The filter to set.
  36851. * @return {AudioListener} A reference to this listener.
  36852. */
  36853. setFilter( value ) {
  36854. if ( this.filter !== null ) {
  36855. this.gain.disconnect( this.filter );
  36856. this.filter.disconnect( this.context.destination );
  36857. } else {
  36858. this.gain.disconnect( this.context.destination );
  36859. }
  36860. this.filter = value;
  36861. this.gain.connect( this.filter );
  36862. this.filter.connect( this.context.destination );
  36863. return this;
  36864. }
  36865. /**
  36866. * Returns the applications master volume.
  36867. *
  36868. * @return {number} The master volume.
  36869. */
  36870. getMasterVolume() {
  36871. return this.gain.gain.value;
  36872. }
  36873. /**
  36874. * Sets the applications master volume. This volume setting affects
  36875. * all audio nodes in the scene.
  36876. *
  36877. * @param {number} value - The master volume to set.
  36878. * @return {AudioListener} A reference to this listener.
  36879. */
  36880. setMasterVolume( value ) {
  36881. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36882. return this;
  36883. }
  36884. updateMatrixWorld( force ) {
  36885. super.updateMatrixWorld( force );
  36886. this._timer.update();
  36887. const listener = this.context.listener;
  36888. this.timeDelta = this._timer.getDelta();
  36889. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36890. // the initial forward and up directions must be orthogonal
  36891. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36892. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36893. if ( listener.positionX ) {
  36894. // code path for Chrome (see #14393)
  36895. const endTime = this.context.currentTime + this.timeDelta;
  36896. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36897. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36898. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36899. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36900. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36901. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36902. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36903. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36904. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36905. } else {
  36906. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36907. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36908. }
  36909. }
  36910. }
  36911. /**
  36912. * Represents a non-positional ( global ) audio object.
  36913. *
  36914. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36915. *
  36916. * ```js
  36917. * // create an AudioListener and add it to the camera
  36918. * const listener = new THREE.AudioListener();
  36919. * camera.add( listener );
  36920. *
  36921. * // create a global audio source
  36922. * const sound = new THREE.Audio( listener );
  36923. *
  36924. * // load a sound and set it as the Audio object's buffer
  36925. * const audioLoader = new THREE.AudioLoader();
  36926. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36927. * sound.setBuffer( buffer );
  36928. * sound.setLoop( true );
  36929. * sound.setVolume( 0.5 );
  36930. * sound.play();
  36931. * });
  36932. * ```
  36933. *
  36934. * @augments Object3D
  36935. */
  36936. class Audio extends Object3D {
  36937. /**
  36938. * Constructs a new audio.
  36939. *
  36940. * @param {AudioListener} listener - The global audio listener.
  36941. */
  36942. constructor( listener ) {
  36943. super();
  36944. this.type = 'Audio';
  36945. /**
  36946. * The global audio listener.
  36947. *
  36948. * @type {AudioListener}
  36949. * @readonly
  36950. */
  36951. this.listener = listener;
  36952. /**
  36953. * The audio context.
  36954. *
  36955. * @type {AudioContext}
  36956. * @readonly
  36957. */
  36958. this.context = listener.context;
  36959. /**
  36960. * The gain node used for volume control.
  36961. *
  36962. * @type {GainNode}
  36963. * @readonly
  36964. */
  36965. this.gain = this.context.createGain();
  36966. this.gain.connect( listener.getInput() );
  36967. /**
  36968. * Whether to start playback automatically or not.
  36969. *
  36970. * @type {boolean}
  36971. * @default false
  36972. */
  36973. this.autoplay = false;
  36974. /**
  36975. * A reference to an audio buffer.
  36976. *
  36977. * Defined via {@link Audio#setBuffer}.
  36978. *
  36979. * @type {?AudioBuffer}
  36980. * @default null
  36981. * @readonly
  36982. */
  36983. this.buffer = null;
  36984. /**
  36985. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36986. * +/- 1200 is an octave.
  36987. *
  36988. * Defined via {@link Audio#setDetune}.
  36989. *
  36990. * @type {number}
  36991. * @default 0
  36992. * @readonly
  36993. */
  36994. this.detune = 0;
  36995. /**
  36996. * Whether the audio should loop or not.
  36997. *
  36998. * Defined via {@link Audio#setLoop}.
  36999. *
  37000. * @type {boolean}
  37001. * @default false
  37002. * @readonly
  37003. */
  37004. this.loop = false;
  37005. /**
  37006. * Defines where in the audio buffer the replay should
  37007. * start, in seconds.
  37008. *
  37009. * @type {number}
  37010. * @default 0
  37011. */
  37012. this.loopStart = 0;
  37013. /**
  37014. * Defines where in the audio buffer the replay should
  37015. * stop, in seconds.
  37016. *
  37017. * @type {number}
  37018. * @default 0
  37019. */
  37020. this.loopEnd = 0;
  37021. /**
  37022. * An offset to the time within the audio buffer the playback
  37023. * should begin, in seconds.
  37024. *
  37025. * @type {number}
  37026. * @default 0
  37027. */
  37028. this.offset = 0;
  37029. /**
  37030. * Overrides the default duration of the audio.
  37031. *
  37032. * @type {undefined|number}
  37033. * @default undefined
  37034. */
  37035. this.duration = undefined;
  37036. /**
  37037. * The playback speed.
  37038. *
  37039. * Defined via {@link Audio#setPlaybackRate}.
  37040. *
  37041. * @type {number}
  37042. * @readonly
  37043. * @default 1
  37044. */
  37045. this.playbackRate = 1;
  37046. /**
  37047. * Indicates whether the audio is playing or not.
  37048. *
  37049. * This flag will be automatically set when using {@link Audio#play},
  37050. * {@link Audio#pause}, {@link Audio#stop}.
  37051. *
  37052. * @type {boolean}
  37053. * @readonly
  37054. * @default false
  37055. */
  37056. this.isPlaying = false;
  37057. /**
  37058. * Indicates whether the audio playback can be controlled
  37059. * with method like {@link Audio#play} or {@link Audio#pause}.
  37060. *
  37061. * This flag will be automatically set when audio sources are
  37062. * defined.
  37063. *
  37064. * @type {boolean}
  37065. * @readonly
  37066. * @default true
  37067. */
  37068. this.hasPlaybackControl = true;
  37069. /**
  37070. * Holds a reference to the current audio source.
  37071. *
  37072. * The property is automatically by one of the `set*()` methods.
  37073. *
  37074. * @type {?AudioNode}
  37075. * @readonly
  37076. * @default null
  37077. */
  37078. this.source = null;
  37079. /**
  37080. * Defines the source type.
  37081. *
  37082. * The property is automatically set by one of the `set*()` methods.
  37083. *
  37084. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  37085. * @readonly
  37086. * @default 'empty'
  37087. */
  37088. this.sourceType = 'empty';
  37089. this._startedAt = 0;
  37090. this._progress = 0;
  37091. this._connected = false;
  37092. /**
  37093. * Can be used to apply a variety of low-order filters to create
  37094. * more complex sound effects e.g. via `BiquadFilterNode`.
  37095. *
  37096. * The property is automatically set by {@link Audio#setFilters}.
  37097. *
  37098. * @type {Array<AudioNode>}
  37099. * @readonly
  37100. */
  37101. this.filters = [];
  37102. }
  37103. /**
  37104. * Returns the output audio node.
  37105. *
  37106. * @return {GainNode} The output node.
  37107. */
  37108. getOutput() {
  37109. return this.gain;
  37110. }
  37111. /**
  37112. * Sets the given audio node as the source of this instance.
  37113. *
  37114. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  37115. *
  37116. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  37117. * @return {Audio} A reference to this instance.
  37118. */
  37119. setNodeSource( audioNode ) {
  37120. this.hasPlaybackControl = false;
  37121. this.sourceType = 'audioNode';
  37122. this.source = audioNode;
  37123. this.connect();
  37124. return this;
  37125. }
  37126. /**
  37127. * Sets the given media element as the source of this instance.
  37128. *
  37129. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  37130. *
  37131. * @param {HTMLMediaElement} mediaElement - The media element.
  37132. * @return {Audio} A reference to this instance.
  37133. */
  37134. setMediaElementSource( mediaElement ) {
  37135. this.hasPlaybackControl = false;
  37136. this.sourceType = 'mediaNode';
  37137. this.source = this.context.createMediaElementSource( mediaElement );
  37138. this.connect();
  37139. return this;
  37140. }
  37141. /**
  37142. * Sets the given media stream as the source of this instance.
  37143. *
  37144. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  37145. *
  37146. * @param {MediaStream} mediaStream - The media stream.
  37147. * @return {Audio} A reference to this instance.
  37148. */
  37149. setMediaStreamSource( mediaStream ) {
  37150. this.hasPlaybackControl = false;
  37151. this.sourceType = 'mediaStreamNode';
  37152. this.source = this.context.createMediaStreamSource( mediaStream );
  37153. this.connect();
  37154. return this;
  37155. }
  37156. /**
  37157. * Sets the given audio buffer as the source of this instance.
  37158. *
  37159. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  37160. *
  37161. * @param {AudioBuffer} audioBuffer - The audio buffer.
  37162. * @return {Audio} A reference to this instance.
  37163. */
  37164. setBuffer( audioBuffer ) {
  37165. this.buffer = audioBuffer;
  37166. this.sourceType = 'buffer';
  37167. if ( this.autoplay ) this.play();
  37168. return this;
  37169. }
  37170. /**
  37171. * Starts the playback of the audio.
  37172. *
  37173. * Can only be used with compatible audio sources that allow playback control.
  37174. *
  37175. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  37176. * @return {Audio|undefined} A reference to this instance.
  37177. */
  37178. play( delay = 0 ) {
  37179. if ( this.isPlaying === true ) {
  37180. warn( 'Audio: Audio is already playing.' );
  37181. return;
  37182. }
  37183. if ( this.hasPlaybackControl === false ) {
  37184. warn( 'Audio: this Audio has no playback control.' );
  37185. return;
  37186. }
  37187. this._startedAt = this.context.currentTime + delay;
  37188. const source = this.context.createBufferSource();
  37189. source.buffer = this.buffer;
  37190. source.loop = this.loop;
  37191. source.loopStart = this.loopStart;
  37192. source.loopEnd = this.loopEnd;
  37193. source.onended = this.onEnded.bind( this );
  37194. source.start( this._startedAt, this._progress + this.offset, this.duration );
  37195. this.isPlaying = true;
  37196. this.source = source;
  37197. this.setDetune( this.detune );
  37198. this.setPlaybackRate( this.playbackRate );
  37199. return this.connect();
  37200. }
  37201. /**
  37202. * Pauses the playback of the audio.
  37203. *
  37204. * Can only be used with compatible audio sources that allow playback control.
  37205. *
  37206. * @return {Audio|undefined} A reference to this instance.
  37207. */
  37208. pause() {
  37209. if ( this.hasPlaybackControl === false ) {
  37210. warn( 'Audio: this Audio has no playback control.' );
  37211. return;
  37212. }
  37213. if ( this.isPlaying === true ) {
  37214. // update current progress
  37215. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  37216. if ( this.loop === true ) {
  37217. // ensure _progress does not exceed duration with looped audios
  37218. this._progress = this._progress % ( this.duration || this.buffer.duration );
  37219. }
  37220. this.source.stop();
  37221. this.source.onended = null;
  37222. this.isPlaying = false;
  37223. }
  37224. return this;
  37225. }
  37226. /**
  37227. * Stops the playback of the audio.
  37228. *
  37229. * Can only be used with compatible audio sources that allow playback control.
  37230. *
  37231. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  37232. * @return {Audio|undefined} A reference to this instance.
  37233. */
  37234. stop( delay = 0 ) {
  37235. if ( this.hasPlaybackControl === false ) {
  37236. warn( 'Audio: this Audio has no playback control.' );
  37237. return;
  37238. }
  37239. this._progress = 0;
  37240. if ( this.source !== null ) {
  37241. this.source.stop( this.context.currentTime + delay );
  37242. this.source.onended = null;
  37243. }
  37244. this.isPlaying = false;
  37245. return this;
  37246. }
  37247. /**
  37248. * Connects to the audio source. This is used internally on
  37249. * initialisation and when setting / removing filters.
  37250. *
  37251. * @return {Audio} A reference to this instance.
  37252. */
  37253. connect() {
  37254. if ( this.filters.length > 0 ) {
  37255. this.source.connect( this.filters[ 0 ] );
  37256. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37257. this.filters[ i - 1 ].connect( this.filters[ i ] );
  37258. }
  37259. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  37260. } else {
  37261. this.source.connect( this.getOutput() );
  37262. }
  37263. this._connected = true;
  37264. return this;
  37265. }
  37266. /**
  37267. * Disconnects to the audio source. This is used internally on
  37268. * initialisation and when setting / removing filters.
  37269. *
  37270. * @return {Audio|undefined} A reference to this instance.
  37271. */
  37272. disconnect() {
  37273. if ( this._connected === false ) {
  37274. return;
  37275. }
  37276. if ( this.filters.length > 0 ) {
  37277. this.source.disconnect( this.filters[ 0 ] );
  37278. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37279. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  37280. }
  37281. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  37282. } else {
  37283. this.source.disconnect( this.getOutput() );
  37284. }
  37285. this._connected = false;
  37286. return this;
  37287. }
  37288. /**
  37289. * Returns the current set filters.
  37290. *
  37291. * @return {Array<AudioNode>} The list of filters.
  37292. */
  37293. getFilters() {
  37294. return this.filters;
  37295. }
  37296. /**
  37297. * Sets an array of filters and connects them with the audio source.
  37298. *
  37299. * @param {Array<AudioNode>} [value] - A list of filters.
  37300. * @return {Audio} A reference to this instance.
  37301. */
  37302. setFilters( value ) {
  37303. if ( ! value ) value = [];
  37304. if ( this._connected === true ) {
  37305. this.disconnect();
  37306. this.filters = value.slice();
  37307. this.connect();
  37308. } else {
  37309. this.filters = value.slice();
  37310. }
  37311. return this;
  37312. }
  37313. /**
  37314. * Defines the detuning of oscillation in cents.
  37315. *
  37316. * @param {number} value - The detuning of oscillation in cents.
  37317. * @return {Audio} A reference to this instance.
  37318. */
  37319. setDetune( value ) {
  37320. this.detune = value;
  37321. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37322. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37323. }
  37324. return this;
  37325. }
  37326. /**
  37327. * Returns the detuning of oscillation in cents.
  37328. *
  37329. * @return {number} The detuning of oscillation in cents.
  37330. */
  37331. getDetune() {
  37332. return this.detune;
  37333. }
  37334. /**
  37335. * Returns the first filter in the list of filters.
  37336. *
  37337. * @return {AudioNode|undefined} The first filter in the list of filters.
  37338. */
  37339. getFilter() {
  37340. return this.getFilters()[ 0 ];
  37341. }
  37342. /**
  37343. * Applies a single filter node to the audio.
  37344. *
  37345. * @param {AudioNode} [filter] - The filter to set.
  37346. * @return {Audio} A reference to this instance.
  37347. */
  37348. setFilter( filter ) {
  37349. return this.setFilters( filter ? [ filter ] : [] );
  37350. }
  37351. /**
  37352. * Sets the playback rate.
  37353. *
  37354. * Can only be used with compatible audio sources that allow playback control.
  37355. *
  37356. * @param {number} [value] - The playback rate to set.
  37357. * @return {Audio|undefined} A reference to this instance.
  37358. */
  37359. setPlaybackRate( value ) {
  37360. if ( this.hasPlaybackControl === false ) {
  37361. warn( 'Audio: this Audio has no playback control.' );
  37362. return;
  37363. }
  37364. this.playbackRate = value;
  37365. if ( this.isPlaying === true ) {
  37366. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37367. }
  37368. return this;
  37369. }
  37370. /**
  37371. * Returns the current playback rate.
  37372. * @return {number} The playback rate.
  37373. */
  37374. getPlaybackRate() {
  37375. return this.playbackRate;
  37376. }
  37377. /**
  37378. * Automatically called when playback finished.
  37379. */
  37380. onEnded() {
  37381. this.isPlaying = false;
  37382. this._progress = 0;
  37383. }
  37384. /**
  37385. * Returns the loop flag.
  37386. *
  37387. * Can only be used with compatible audio sources that allow playback control.
  37388. *
  37389. * @return {boolean} Whether the audio should loop or not.
  37390. */
  37391. getLoop() {
  37392. if ( this.hasPlaybackControl === false ) {
  37393. warn( 'Audio: this Audio has no playback control.' );
  37394. return false;
  37395. }
  37396. return this.loop;
  37397. }
  37398. /**
  37399. * Sets the loop flag.
  37400. *
  37401. * Can only be used with compatible audio sources that allow playback control.
  37402. *
  37403. * @param {boolean} value - Whether the audio should loop or not.
  37404. * @return {Audio|undefined} A reference to this instance.
  37405. */
  37406. setLoop( value ) {
  37407. if ( this.hasPlaybackControl === false ) {
  37408. warn( 'Audio: this Audio has no playback control.' );
  37409. return;
  37410. }
  37411. this.loop = value;
  37412. if ( this.isPlaying === true ) {
  37413. this.source.loop = this.loop;
  37414. }
  37415. return this;
  37416. }
  37417. /**
  37418. * Sets the loop start value which defines where in the audio buffer the replay should
  37419. * start, in seconds.
  37420. *
  37421. * @param {number} value - The loop start value.
  37422. * @return {Audio} A reference to this instance.
  37423. */
  37424. setLoopStart( value ) {
  37425. this.loopStart = value;
  37426. return this;
  37427. }
  37428. /**
  37429. * Sets the loop end value which defines where in the audio buffer the replay should
  37430. * stop, in seconds.
  37431. *
  37432. * @param {number} value - The loop end value.
  37433. * @return {Audio} A reference to this instance.
  37434. */
  37435. setLoopEnd( value ) {
  37436. this.loopEnd = value;
  37437. return this;
  37438. }
  37439. /**
  37440. * Returns the volume.
  37441. *
  37442. * @return {number} The volume.
  37443. */
  37444. getVolume() {
  37445. return this.gain.gain.value;
  37446. }
  37447. /**
  37448. * Sets the volume.
  37449. *
  37450. * @param {number} value - The volume to set.
  37451. * @return {Audio} A reference to this instance.
  37452. */
  37453. setVolume( value ) {
  37454. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37455. return this;
  37456. }
  37457. copy( source, recursive ) {
  37458. super.copy( source, recursive );
  37459. if ( source.sourceType !== 'buffer' ) {
  37460. warn( 'Audio: Audio source type cannot be copied.' );
  37461. return this;
  37462. }
  37463. this.autoplay = source.autoplay;
  37464. this.buffer = source.buffer;
  37465. this.detune = source.detune;
  37466. this.loop = source.loop;
  37467. this.loopStart = source.loopStart;
  37468. this.loopEnd = source.loopEnd;
  37469. this.offset = source.offset;
  37470. this.duration = source.duration;
  37471. this.playbackRate = source.playbackRate;
  37472. this.hasPlaybackControl = source.hasPlaybackControl;
  37473. this.sourceType = source.sourceType;
  37474. this.filters = source.filters.slice();
  37475. return this;
  37476. }
  37477. clone( recursive ) {
  37478. return new this.constructor( this.listener ).copy( this, recursive );
  37479. }
  37480. }
  37481. const _position = /*@__PURE__*/ new Vector3();
  37482. const _quaternion = /*@__PURE__*/ new Quaternion();
  37483. const _scale = /*@__PURE__*/ new Vector3();
  37484. const _orientation = /*@__PURE__*/ new Vector3();
  37485. /**
  37486. * Represents a positional audio object.
  37487. *
  37488. * ```js
  37489. * // create an AudioListener and add it to the camera
  37490. * const listener = new THREE.AudioListener();
  37491. * camera.add( listener );
  37492. *
  37493. * // create the PositionalAudio object (passing in the listener)
  37494. * const sound = new THREE.PositionalAudio( listener );
  37495. *
  37496. * // load a sound and set it as the PositionalAudio object's buffer
  37497. * const audioLoader = new THREE.AudioLoader();
  37498. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37499. * sound.setBuffer( buffer );
  37500. * sound.setRefDistance( 20 );
  37501. * sound.play();
  37502. * });
  37503. *
  37504. * // create an object for the sound to play from
  37505. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37506. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37507. * const mesh = new THREE.Mesh( sphere, material );
  37508. * scene.add( mesh );
  37509. *
  37510. * // finally add the sound to the mesh
  37511. * mesh.add( sound );
  37512. *
  37513. * @augments Audio
  37514. */
  37515. class PositionalAudio extends Audio {
  37516. /**
  37517. * Constructs a positional audio.
  37518. *
  37519. * @param {AudioListener} listener - The global audio listener.
  37520. */
  37521. constructor( listener ) {
  37522. super( listener );
  37523. /**
  37524. * The panner node represents the location, direction, and behavior of an audio
  37525. * source in 3D space.
  37526. *
  37527. * @type {PannerNode}
  37528. * @readonly
  37529. */
  37530. this.panner = this.context.createPanner();
  37531. this.panner.panningModel = 'HRTF';
  37532. this.panner.connect( this.gain );
  37533. }
  37534. connect() {
  37535. super.connect();
  37536. this.panner.connect( this.gain );
  37537. return this;
  37538. }
  37539. disconnect() {
  37540. super.disconnect();
  37541. this.panner.disconnect( this.gain );
  37542. return this;
  37543. }
  37544. getOutput() {
  37545. return this.panner;
  37546. }
  37547. /**
  37548. * Returns the current reference distance.
  37549. *
  37550. * @return {number} The reference distance.
  37551. */
  37552. getRefDistance() {
  37553. return this.panner.refDistance;
  37554. }
  37555. /**
  37556. * Defines the reference distance for reducing volume as the audio source moves
  37557. * further from the listener – i.e. the distance at which the volume reduction
  37558. * starts taking effect.
  37559. *
  37560. * @param {number} value - The reference distance to set.
  37561. * @return {PositionalAudio} A reference to this instance.
  37562. */
  37563. setRefDistance( value ) {
  37564. this.panner.refDistance = value;
  37565. return this;
  37566. }
  37567. /**
  37568. * Returns the current rolloff factor.
  37569. *
  37570. * @return {number} The rolloff factor.
  37571. */
  37572. getRolloffFactor() {
  37573. return this.panner.rolloffFactor;
  37574. }
  37575. /**
  37576. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37577. *
  37578. * @param {number} value - The rolloff factor.
  37579. * @return {PositionalAudio} A reference to this instance.
  37580. */
  37581. setRolloffFactor( value ) {
  37582. this.panner.rolloffFactor = value;
  37583. return this;
  37584. }
  37585. /**
  37586. * Returns the current distance model.
  37587. *
  37588. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37589. */
  37590. getDistanceModel() {
  37591. return this.panner.distanceModel;
  37592. }
  37593. /**
  37594. * Defines which algorithm to use to reduce the volume of the audio source
  37595. * as it moves away from the listener.
  37596. *
  37597. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37598. * for more details.
  37599. *
  37600. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37601. * @return {PositionalAudio} A reference to this instance.
  37602. */
  37603. setDistanceModel( value ) {
  37604. this.panner.distanceModel = value;
  37605. return this;
  37606. }
  37607. /**
  37608. * Returns the current max distance.
  37609. *
  37610. * @return {number} The max distance.
  37611. */
  37612. getMaxDistance() {
  37613. return this.panner.maxDistance;
  37614. }
  37615. /**
  37616. * Defines the maximum distance between the audio source and the listener,
  37617. * after which the volume is not reduced any further.
  37618. *
  37619. * This value is used only by the `linear` distance model.
  37620. *
  37621. * @param {number} value - The max distance.
  37622. * @return {PositionalAudio} A reference to this instance.
  37623. */
  37624. setMaxDistance( value ) {
  37625. this.panner.maxDistance = value;
  37626. return this;
  37627. }
  37628. /**
  37629. * Sets the directional cone in which the audio can be listened.
  37630. *
  37631. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37632. * @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.
  37633. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37634. * @return {PositionalAudio} A reference to this instance.
  37635. */
  37636. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37637. this.panner.coneInnerAngle = coneInnerAngle;
  37638. this.panner.coneOuterAngle = coneOuterAngle;
  37639. this.panner.coneOuterGain = coneOuterGain;
  37640. return this;
  37641. }
  37642. updateMatrixWorld( force ) {
  37643. super.updateMatrixWorld( force );
  37644. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37645. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37646. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37647. const panner = this.panner;
  37648. if ( panner.positionX ) {
  37649. // code path for Chrome and Firefox (see #14393)
  37650. const endTime = this.context.currentTime + this.listener.timeDelta;
  37651. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37652. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37653. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37654. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37655. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37656. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37657. } else {
  37658. panner.setPosition( _position.x, _position.y, _position.z );
  37659. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37660. }
  37661. }
  37662. }
  37663. /**
  37664. * This class can be used to analyse audio data.
  37665. *
  37666. * ```js
  37667. * // create an AudioListener and add it to the camera
  37668. * const listener = new THREE.AudioListener();
  37669. * camera.add( listener );
  37670. *
  37671. * // create an Audio source
  37672. * const sound = new THREE.Audio( listener );
  37673. *
  37674. * // load a sound and set it as the Audio object's buffer
  37675. * const audioLoader = new THREE.AudioLoader();
  37676. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37677. * sound.setBuffer( buffer );
  37678. * sound.setLoop(true);
  37679. * sound.setVolume(0.5);
  37680. * sound.play();
  37681. * });
  37682. *
  37683. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37684. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37685. *
  37686. * // get the average frequency of the sound
  37687. * const data = analyser.getAverageFrequency();
  37688. * ```
  37689. */
  37690. class AudioAnalyser {
  37691. /**
  37692. * Constructs a new audio analyzer.
  37693. *
  37694. * @param {Audio} audio - The audio to analyze.
  37695. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37696. */
  37697. constructor( audio, fftSize = 2048 ) {
  37698. /**
  37699. * The global audio listener.
  37700. *
  37701. * @type {AnalyserNode}
  37702. */
  37703. this.analyser = audio.context.createAnalyser();
  37704. this.analyser.fftSize = fftSize;
  37705. /**
  37706. * Holds the analyzed data.
  37707. *
  37708. * @type {Uint8Array}
  37709. */
  37710. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37711. audio.getOutput().connect( this.analyser );
  37712. }
  37713. /**
  37714. * Returns an array with frequency data of the audio.
  37715. *
  37716. * Each item in the array represents the decibel value for a specific frequency.
  37717. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37718. * For example, for 48000 sample rate, the last item of the array will represent
  37719. * the decibel value for 24000 Hz.
  37720. *
  37721. * @return {Uint8Array} The frequency data.
  37722. */
  37723. getFrequencyData() {
  37724. this.analyser.getByteFrequencyData( this.data );
  37725. return this.data;
  37726. }
  37727. /**
  37728. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37729. *
  37730. * @return {number} The average frequency.
  37731. */
  37732. getAverageFrequency() {
  37733. let value = 0;
  37734. const data = this.getFrequencyData();
  37735. for ( let i = 0; i < data.length; i ++ ) {
  37736. value += data[ i ];
  37737. }
  37738. return value / data.length;
  37739. }
  37740. }
  37741. /**
  37742. * Buffered scene graph property that allows weighted accumulation; used internally.
  37743. */
  37744. class PropertyMixer {
  37745. /**
  37746. * Constructs a new property mixer.
  37747. *
  37748. * @param {PropertyBinding} binding - The property binding.
  37749. * @param {string} typeName - The keyframe track type name.
  37750. * @param {number} valueSize - The keyframe track value size.
  37751. */
  37752. constructor( binding, typeName, valueSize ) {
  37753. /**
  37754. * The property binding.
  37755. *
  37756. * @type {PropertyBinding}
  37757. */
  37758. this.binding = binding;
  37759. /**
  37760. * The keyframe track value size.
  37761. *
  37762. * @type {number}
  37763. */
  37764. this.valueSize = valueSize;
  37765. let mixFunction,
  37766. mixFunctionAdditive,
  37767. setIdentity;
  37768. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37769. //
  37770. // interpolators can use .buffer as their .result
  37771. // the data then goes to 'incoming'
  37772. //
  37773. // 'accu0' and 'accu1' are used frame-interleaved for
  37774. // the cumulative result and are compared to detect
  37775. // changes
  37776. //
  37777. // 'orig' stores the original state of the property
  37778. //
  37779. // 'add' is used for additive cumulative results
  37780. //
  37781. // 'work' is optional and is only present for quaternion types. It is used
  37782. // to store intermediate quaternion multiplication results
  37783. switch ( typeName ) {
  37784. case 'quaternion':
  37785. mixFunction = this._slerp;
  37786. mixFunctionAdditive = this._slerpAdditive;
  37787. setIdentity = this._setAdditiveIdentityQuaternion;
  37788. this.buffer = new Float64Array( valueSize * 6 );
  37789. this._workIndex = 5;
  37790. break;
  37791. case 'string':
  37792. case 'bool':
  37793. mixFunction = this._select;
  37794. // Use the regular mix function and for additive on these types,
  37795. // additive is not relevant for non-numeric types
  37796. mixFunctionAdditive = this._select;
  37797. setIdentity = this._setAdditiveIdentityOther;
  37798. this.buffer = new Array( valueSize * 5 );
  37799. break;
  37800. default:
  37801. mixFunction = this._lerp;
  37802. mixFunctionAdditive = this._lerpAdditive;
  37803. setIdentity = this._setAdditiveIdentityNumeric;
  37804. this.buffer = new Float64Array( valueSize * 5 );
  37805. }
  37806. this._mixBufferRegion = mixFunction;
  37807. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37808. this._setIdentity = setIdentity;
  37809. this._origIndex = 3;
  37810. this._addIndex = 4;
  37811. /**
  37812. * Accumulated weight of the property binding.
  37813. *
  37814. * @type {number}
  37815. * @default 0
  37816. */
  37817. this.cumulativeWeight = 0;
  37818. /**
  37819. * Accumulated additive weight of the property binding.
  37820. *
  37821. * @type {number}
  37822. * @default 0
  37823. */
  37824. this.cumulativeWeightAdditive = 0;
  37825. /**
  37826. * Number of active keyframe tracks currently using this property binding.
  37827. *
  37828. * @type {number}
  37829. * @default 0
  37830. */
  37831. this.useCount = 0;
  37832. /**
  37833. * Number of keyframe tracks referencing this property binding.
  37834. *
  37835. * @type {number}
  37836. * @default 0
  37837. */
  37838. this.referenceCount = 0;
  37839. }
  37840. /**
  37841. * Accumulates data in the `incoming` region into `accu<i>`.
  37842. *
  37843. * @param {number} accuIndex - The accumulation index.
  37844. * @param {number} weight - The weight.
  37845. */
  37846. accumulate( accuIndex, weight ) {
  37847. // note: happily accumulating nothing when weight = 0, the caller knows
  37848. // the weight and shouldn't have made the call in the first place
  37849. const buffer = this.buffer,
  37850. stride = this.valueSize,
  37851. offset = accuIndex * stride + stride;
  37852. let currentWeight = this.cumulativeWeight;
  37853. if ( currentWeight === 0 ) {
  37854. // accuN := incoming * weight
  37855. for ( let i = 0; i !== stride; ++ i ) {
  37856. buffer[ offset + i ] = buffer[ i ];
  37857. }
  37858. currentWeight = weight;
  37859. } else {
  37860. // accuN := accuN + incoming * weight
  37861. currentWeight += weight;
  37862. const mix = weight / currentWeight;
  37863. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37864. }
  37865. this.cumulativeWeight = currentWeight;
  37866. }
  37867. /**
  37868. * Accumulates data in the `incoming` region into `add`.
  37869. *
  37870. * @param {number} weight - The weight.
  37871. */
  37872. accumulateAdditive( weight ) {
  37873. const buffer = this.buffer,
  37874. stride = this.valueSize,
  37875. offset = stride * this._addIndex;
  37876. if ( this.cumulativeWeightAdditive === 0 ) {
  37877. // add = identity
  37878. this._setIdentity();
  37879. }
  37880. // add := add + incoming * weight
  37881. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37882. this.cumulativeWeightAdditive += weight;
  37883. }
  37884. /**
  37885. * Applies the state of `accu<i>` to the binding when accus differ.
  37886. *
  37887. * @param {number} accuIndex - The accumulation index.
  37888. */
  37889. apply( accuIndex ) {
  37890. const stride = this.valueSize,
  37891. buffer = this.buffer,
  37892. offset = accuIndex * stride + stride,
  37893. weight = this.cumulativeWeight,
  37894. weightAdditive = this.cumulativeWeightAdditive,
  37895. binding = this.binding;
  37896. this.cumulativeWeight = 0;
  37897. this.cumulativeWeightAdditive = 0;
  37898. if ( weight < 1 ) {
  37899. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37900. const originalValueOffset = stride * this._origIndex;
  37901. this._mixBufferRegion(
  37902. buffer, offset, originalValueOffset, 1 - weight, stride );
  37903. }
  37904. if ( weightAdditive > 0 ) {
  37905. // accuN := accuN + additive accuN
  37906. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37907. }
  37908. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37909. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37910. // value has changed -> update scene graph
  37911. binding.setValue( buffer, offset );
  37912. break;
  37913. }
  37914. }
  37915. }
  37916. /**
  37917. * Remembers the state of the bound property and copy it to both accus.
  37918. */
  37919. saveOriginalState() {
  37920. const binding = this.binding;
  37921. const buffer = this.buffer,
  37922. stride = this.valueSize,
  37923. originalValueOffset = stride * this._origIndex;
  37924. binding.getValue( buffer, originalValueOffset );
  37925. // accu[0..1] := orig -- initially detect changes against the original
  37926. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37927. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37928. }
  37929. // Add to identity for additive
  37930. this._setIdentity();
  37931. this.cumulativeWeight = 0;
  37932. this.cumulativeWeightAdditive = 0;
  37933. }
  37934. /**
  37935. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37936. */
  37937. restoreOriginalState() {
  37938. const originalValueOffset = this.valueSize * 3;
  37939. this.binding.setValue( this.buffer, originalValueOffset );
  37940. }
  37941. // internals
  37942. _setAdditiveIdentityNumeric() {
  37943. const startIndex = this._addIndex * this.valueSize;
  37944. const endIndex = startIndex + this.valueSize;
  37945. for ( let i = startIndex; i < endIndex; i ++ ) {
  37946. this.buffer[ i ] = 0;
  37947. }
  37948. }
  37949. _setAdditiveIdentityQuaternion() {
  37950. this._setAdditiveIdentityNumeric();
  37951. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37952. }
  37953. _setAdditiveIdentityOther() {
  37954. const startIndex = this._origIndex * this.valueSize;
  37955. const targetIndex = this._addIndex * this.valueSize;
  37956. for ( let i = 0; i < this.valueSize; i ++ ) {
  37957. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37958. }
  37959. }
  37960. // mix functions
  37961. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37962. if ( t >= 0.5 ) {
  37963. for ( let i = 0; i !== stride; ++ i ) {
  37964. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37965. }
  37966. }
  37967. }
  37968. _slerp( buffer, dstOffset, srcOffset, t ) {
  37969. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37970. }
  37971. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37972. const workOffset = this._workIndex * stride;
  37973. // Store result in intermediate buffer offset
  37974. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37975. // Slerp to the intermediate result
  37976. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37977. }
  37978. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37979. const s = 1 - t;
  37980. for ( let i = 0; i !== stride; ++ i ) {
  37981. const j = dstOffset + i;
  37982. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37983. }
  37984. }
  37985. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37986. for ( let i = 0; i !== stride; ++ i ) {
  37987. const j = dstOffset + i;
  37988. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37989. }
  37990. }
  37991. }
  37992. // Characters [].:/ are reserved for track binding syntax.
  37993. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37994. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37995. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37996. // only latin characters, and the unicode \p{L} is not yet supported. So
  37997. // instead, we exclude reserved characters and match everything else.
  37998. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37999. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  38000. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  38001. // be matched to parse the rest of the track name.
  38002. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  38003. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  38004. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  38005. // Object on target node, and accessor. May not contain reserved
  38006. // characters. Accessor may contain any character except closing bracket.
  38007. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  38008. // Property and accessor. May not contain reserved characters. Accessor may
  38009. // contain any non-bracket characters.
  38010. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  38011. const _trackRe = new RegExp( ''
  38012. + '^'
  38013. + _directoryRe
  38014. + _nodeRe
  38015. + _objectRe
  38016. + _propertyRe
  38017. + '$'
  38018. );
  38019. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  38020. class Composite {
  38021. constructor( targetGroup, path, optionalParsedPath ) {
  38022. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  38023. this._targetGroup = targetGroup;
  38024. this._bindings = targetGroup.subscribe_( path, parsedPath );
  38025. }
  38026. getValue( array, offset ) {
  38027. this.bind(); // bind all binding
  38028. const firstValidIndex = this._targetGroup.nCachedObjects_,
  38029. binding = this._bindings[ firstValidIndex ];
  38030. // and only call .getValue on the first
  38031. if ( binding !== undefined ) binding.getValue( array, offset );
  38032. }
  38033. setValue( array, offset ) {
  38034. const bindings = this._bindings;
  38035. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38036. bindings[ i ].setValue( array, offset );
  38037. }
  38038. }
  38039. bind() {
  38040. const bindings = this._bindings;
  38041. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38042. bindings[ i ].bind();
  38043. }
  38044. }
  38045. unbind() {
  38046. const bindings = this._bindings;
  38047. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38048. bindings[ i ].unbind();
  38049. }
  38050. }
  38051. }
  38052. // Note: This class uses a State pattern on a per-method basis:
  38053. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  38054. // prototype version of these methods with one that represents
  38055. // the bound state. When the property is not found, the methods
  38056. // become no-ops.
  38057. /**
  38058. * This holds a reference to a real property in the scene graph; used internally.
  38059. */
  38060. class PropertyBinding {
  38061. /**
  38062. * Constructs a new property binding.
  38063. *
  38064. * @param {Object} rootNode - The root node.
  38065. * @param {string} path - The path.
  38066. * @param {?Object} [parsedPath] - The parsed path.
  38067. */
  38068. constructor( rootNode, path, parsedPath ) {
  38069. /**
  38070. * The object path to the animated property.
  38071. *
  38072. * @type {string}
  38073. */
  38074. this.path = path;
  38075. /**
  38076. * An object holding information about the path.
  38077. *
  38078. * @type {Object}
  38079. */
  38080. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  38081. /**
  38082. * The object owns the animated property.
  38083. *
  38084. * @type {?Object}
  38085. */
  38086. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  38087. /**
  38088. * The root node.
  38089. *
  38090. * @type {Object3D|Skeleton}
  38091. */
  38092. this.rootNode = rootNode;
  38093. // initial state of these methods that calls 'bind'
  38094. this.getValue = this._getValue_unbound;
  38095. this.setValue = this._setValue_unbound;
  38096. }
  38097. /**
  38098. * Factory method for creating a property binding from the given parameters.
  38099. *
  38100. * @static
  38101. * @param {Object} root - The root node.
  38102. * @param {string} path - The path.
  38103. * @param {?Object} [parsedPath] - The parsed path.
  38104. * @return {PropertyBinding|Composite} The created property binding or composite.
  38105. */
  38106. static create( root, path, parsedPath ) {
  38107. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  38108. return new PropertyBinding( root, path, parsedPath );
  38109. } else {
  38110. return new PropertyBinding.Composite( root, path, parsedPath );
  38111. }
  38112. }
  38113. /**
  38114. * Replaces spaces with underscores and removes unsupported characters from
  38115. * node names, to ensure compatibility with parseTrackName().
  38116. *
  38117. * @param {string} name - Node name to be sanitized.
  38118. * @return {string} The sanitized node name.
  38119. */
  38120. static sanitizeNodeName( name ) {
  38121. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  38122. }
  38123. /**
  38124. * Parses the given track name (an object path to an animated property) and
  38125. * returns an object with information about the path. Matches strings in the following forms:
  38126. *
  38127. * - nodeName.property
  38128. * - nodeName.property[accessor]
  38129. * - nodeName.material.property[accessor]
  38130. * - uuid.property[accessor]
  38131. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  38132. * - parentName/nodeName.property
  38133. * - parentName/parentName/nodeName.property[index]
  38134. * - .bone[Armature.DEF_cog].position
  38135. * - scene:helium_balloon_model:helium_balloon_model.position
  38136. *
  38137. * @static
  38138. * @param {string} trackName - The track name to parse.
  38139. * @return {Object} The parsed track name as an object.
  38140. */
  38141. static parseTrackName( trackName ) {
  38142. const matches = _trackRe.exec( trackName );
  38143. if ( matches === null ) {
  38144. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  38145. }
  38146. const results = {
  38147. // directoryName: matches[ 1 ], // (tschw) currently unused
  38148. nodeName: matches[ 2 ],
  38149. objectName: matches[ 3 ],
  38150. objectIndex: matches[ 4 ],
  38151. propertyName: matches[ 5 ], // required
  38152. propertyIndex: matches[ 6 ]
  38153. };
  38154. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  38155. if ( lastDot !== undefined && lastDot !== -1 ) {
  38156. const objectName = results.nodeName.substring( lastDot + 1 );
  38157. // Object names must be checked against an allowlist. Otherwise, there
  38158. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  38159. // 'bar' could be the objectName, or part of a nodeName (which can
  38160. // include '.' characters).
  38161. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  38162. results.nodeName = results.nodeName.substring( 0, lastDot );
  38163. results.objectName = objectName;
  38164. }
  38165. }
  38166. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  38167. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  38168. }
  38169. return results;
  38170. }
  38171. /**
  38172. * Searches for a node in the hierarchy of the given root object by the given
  38173. * node name.
  38174. *
  38175. * @static
  38176. * @param {Object} root - The root object.
  38177. * @param {string|number} nodeName - The name of the node.
  38178. * @return {?Object} The found node. Returns `null` if no object was found.
  38179. */
  38180. static findNode( root, nodeName ) {
  38181. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  38182. return root;
  38183. }
  38184. // search into skeleton bones.
  38185. if ( root.skeleton ) {
  38186. const bone = root.skeleton.getBoneByName( nodeName );
  38187. if ( bone !== undefined ) {
  38188. return bone;
  38189. }
  38190. }
  38191. // search into node subtree.
  38192. if ( root.children ) {
  38193. const searchNodeSubtree = function ( children ) {
  38194. for ( let i = 0; i < children.length; i ++ ) {
  38195. const childNode = children[ i ];
  38196. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  38197. return childNode;
  38198. }
  38199. const result = searchNodeSubtree( childNode.children );
  38200. if ( result ) return result;
  38201. }
  38202. return null;
  38203. };
  38204. const subTreeNode = searchNodeSubtree( root.children );
  38205. if ( subTreeNode ) {
  38206. return subTreeNode;
  38207. }
  38208. }
  38209. return null;
  38210. }
  38211. // these are used to "bind" a nonexistent property
  38212. _getValue_unavailable() {}
  38213. _setValue_unavailable() {}
  38214. // Getters
  38215. _getValue_direct( buffer, offset ) {
  38216. buffer[ offset ] = this.targetObject[ this.propertyName ];
  38217. }
  38218. _getValue_array( buffer, offset ) {
  38219. const source = this.resolvedProperty;
  38220. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  38221. buffer[ offset ++ ] = source[ i ];
  38222. }
  38223. }
  38224. _getValue_arrayElement( buffer, offset ) {
  38225. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  38226. }
  38227. _getValue_toArray( buffer, offset ) {
  38228. this.resolvedProperty.toArray( buffer, offset );
  38229. }
  38230. // Direct
  38231. _setValue_direct( buffer, offset ) {
  38232. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38233. }
  38234. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  38235. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38236. this.targetObject.needsUpdate = true;
  38237. }
  38238. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38239. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38240. this.targetObject.matrixWorldNeedsUpdate = true;
  38241. }
  38242. // EntireArray
  38243. _setValue_array( buffer, offset ) {
  38244. const dest = this.resolvedProperty;
  38245. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38246. dest[ i ] = buffer[ offset ++ ];
  38247. }
  38248. }
  38249. _setValue_array_setNeedsUpdate( buffer, offset ) {
  38250. const dest = this.resolvedProperty;
  38251. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38252. dest[ i ] = buffer[ offset ++ ];
  38253. }
  38254. this.targetObject.needsUpdate = true;
  38255. }
  38256. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38257. const dest = this.resolvedProperty;
  38258. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38259. dest[ i ] = buffer[ offset ++ ];
  38260. }
  38261. this.targetObject.matrixWorldNeedsUpdate = true;
  38262. }
  38263. // ArrayElement
  38264. _setValue_arrayElement( buffer, offset ) {
  38265. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38266. }
  38267. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  38268. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38269. this.targetObject.needsUpdate = true;
  38270. }
  38271. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38272. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38273. this.targetObject.matrixWorldNeedsUpdate = true;
  38274. }
  38275. // HasToFromArray
  38276. _setValue_fromArray( buffer, offset ) {
  38277. this.resolvedProperty.fromArray( buffer, offset );
  38278. }
  38279. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  38280. this.resolvedProperty.fromArray( buffer, offset );
  38281. this.targetObject.needsUpdate = true;
  38282. }
  38283. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38284. this.resolvedProperty.fromArray( buffer, offset );
  38285. this.targetObject.matrixWorldNeedsUpdate = true;
  38286. }
  38287. _getValue_unbound( targetArray, offset ) {
  38288. this.bind();
  38289. this.getValue( targetArray, offset );
  38290. }
  38291. _setValue_unbound( sourceArray, offset ) {
  38292. this.bind();
  38293. this.setValue( sourceArray, offset );
  38294. }
  38295. /**
  38296. * Creates a getter / setter pair for the property tracked by this binding.
  38297. */
  38298. bind() {
  38299. let targetObject = this.node;
  38300. const parsedPath = this.parsedPath;
  38301. const objectName = parsedPath.objectName;
  38302. const propertyName = parsedPath.propertyName;
  38303. let propertyIndex = parsedPath.propertyIndex;
  38304. if ( ! targetObject ) {
  38305. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38306. this.node = targetObject;
  38307. }
  38308. // set fail state so we can just 'return' on error
  38309. this.getValue = this._getValue_unavailable;
  38310. this.setValue = this._setValue_unavailable;
  38311. // ensure there is a value node
  38312. if ( ! targetObject ) {
  38313. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38314. return;
  38315. }
  38316. if ( objectName ) {
  38317. let objectIndex = parsedPath.objectIndex;
  38318. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38319. switch ( objectName ) {
  38320. case 'materials':
  38321. if ( ! targetObject.material ) {
  38322. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38323. return;
  38324. }
  38325. if ( ! targetObject.material.materials ) {
  38326. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38327. return;
  38328. }
  38329. targetObject = targetObject.material.materials;
  38330. break;
  38331. case 'bones':
  38332. if ( ! targetObject.skeleton ) {
  38333. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38334. return;
  38335. }
  38336. // potential future optimization: skip this if propertyIndex is already an integer
  38337. // and convert the integer string to a true integer.
  38338. targetObject = targetObject.skeleton.bones;
  38339. // support resolving morphTarget names into indices.
  38340. for ( let i = 0; i < targetObject.length; i ++ ) {
  38341. if ( targetObject[ i ].name === objectIndex ) {
  38342. objectIndex = i;
  38343. break;
  38344. }
  38345. }
  38346. break;
  38347. case 'map':
  38348. if ( 'map' in targetObject ) {
  38349. targetObject = targetObject.map;
  38350. break;
  38351. }
  38352. if ( ! targetObject.material ) {
  38353. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38354. return;
  38355. }
  38356. if ( ! targetObject.material.map ) {
  38357. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38358. return;
  38359. }
  38360. targetObject = targetObject.material.map;
  38361. break;
  38362. default:
  38363. if ( targetObject[ objectName ] === undefined ) {
  38364. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38365. return;
  38366. }
  38367. targetObject = targetObject[ objectName ];
  38368. }
  38369. if ( objectIndex !== undefined ) {
  38370. if ( targetObject[ objectIndex ] === undefined ) {
  38371. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38372. return;
  38373. }
  38374. targetObject = targetObject[ objectIndex ];
  38375. }
  38376. }
  38377. // resolve property
  38378. const nodeProperty = targetObject[ propertyName ];
  38379. if ( nodeProperty === undefined ) {
  38380. const nodeName = parsedPath.nodeName;
  38381. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38382. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38383. return;
  38384. }
  38385. // determine versioning scheme
  38386. let versioning = this.Versioning.None;
  38387. this.targetObject = targetObject;
  38388. if ( targetObject.isMaterial === true ) {
  38389. versioning = this.Versioning.NeedsUpdate;
  38390. } else if ( targetObject.isObject3D === true ) {
  38391. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38392. }
  38393. // determine how the property gets bound
  38394. let bindingType = this.BindingType.Direct;
  38395. if ( propertyIndex !== undefined ) {
  38396. // access a sub element of the property array (only primitives are supported right now)
  38397. if ( propertyName === 'morphTargetInfluences' ) {
  38398. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38399. // support resolving morphTarget names into indices.
  38400. if ( ! targetObject.geometry ) {
  38401. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38402. return;
  38403. }
  38404. if ( ! targetObject.geometry.morphAttributes ) {
  38405. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38406. return;
  38407. }
  38408. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38409. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38410. }
  38411. }
  38412. bindingType = this.BindingType.ArrayElement;
  38413. this.resolvedProperty = nodeProperty;
  38414. this.propertyIndex = propertyIndex;
  38415. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38416. // must use copy for Object3D.Euler/Quaternion
  38417. bindingType = this.BindingType.HasFromToArray;
  38418. this.resolvedProperty = nodeProperty;
  38419. } else if ( Array.isArray( nodeProperty ) ) {
  38420. bindingType = this.BindingType.EntireArray;
  38421. this.resolvedProperty = nodeProperty;
  38422. } else {
  38423. this.propertyName = propertyName;
  38424. }
  38425. // select getter / setter
  38426. this.getValue = this.GetterByBindingType[ bindingType ];
  38427. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38428. }
  38429. /**
  38430. * Unbinds the property.
  38431. */
  38432. unbind() {
  38433. this.node = null;
  38434. // back to the prototype version of getValue / setValue
  38435. // note: avoiding to mutate the shape of 'this' via 'delete'
  38436. this.getValue = this._getValue_unbound;
  38437. this.setValue = this._setValue_unbound;
  38438. }
  38439. }
  38440. PropertyBinding.Composite = Composite;
  38441. PropertyBinding.prototype.BindingType = {
  38442. Direct: 0,
  38443. EntireArray: 1,
  38444. ArrayElement: 2,
  38445. HasFromToArray: 3
  38446. };
  38447. PropertyBinding.prototype.Versioning = {
  38448. None: 0,
  38449. NeedsUpdate: 1,
  38450. MatrixWorldNeedsUpdate: 2
  38451. };
  38452. PropertyBinding.prototype.GetterByBindingType = [
  38453. PropertyBinding.prototype._getValue_direct,
  38454. PropertyBinding.prototype._getValue_array,
  38455. PropertyBinding.prototype._getValue_arrayElement,
  38456. PropertyBinding.prototype._getValue_toArray,
  38457. ];
  38458. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38459. [
  38460. // Direct
  38461. PropertyBinding.prototype._setValue_direct,
  38462. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38463. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38464. ], [
  38465. // EntireArray
  38466. PropertyBinding.prototype._setValue_array,
  38467. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38468. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38469. ], [
  38470. // ArrayElement
  38471. PropertyBinding.prototype._setValue_arrayElement,
  38472. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38473. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38474. ], [
  38475. // HasToFromArray
  38476. PropertyBinding.prototype._setValue_fromArray,
  38477. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38478. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38479. ]
  38480. ];
  38481. /**
  38482. * A group of objects that receives a shared animation state.
  38483. *
  38484. * Usage:
  38485. *
  38486. * - Add objects you would otherwise pass as 'root' to the
  38487. * constructor or the .clipAction method of AnimationMixer.
  38488. * - Instead pass this object as 'root'.
  38489. * - You can also add and remove objects later when the mixer is running.
  38490. *
  38491. * Note:
  38492. *
  38493. * - Objects of this class appear as one object to the mixer,
  38494. * so cache control of the individual objects must be done on the group.
  38495. *
  38496. * Limitation:
  38497. *
  38498. * - The animated properties must be compatible among the all objects in the group.
  38499. * - A single property can either be controlled through a target group or directly, but not both.
  38500. */
  38501. class AnimationObjectGroup {
  38502. /**
  38503. * Constructs a new animation group.
  38504. *
  38505. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38506. */
  38507. constructor() {
  38508. /**
  38509. * This flag can be used for type testing.
  38510. *
  38511. * @type {boolean}
  38512. * @readonly
  38513. * @default true
  38514. */
  38515. this.isAnimationObjectGroup = true;
  38516. /**
  38517. * The UUID of the 3D object.
  38518. *
  38519. * @type {string}
  38520. * @readonly
  38521. */
  38522. this.uuid = generateUUID();
  38523. // cached objects followed by the active ones
  38524. this._objects = Array.prototype.slice.call( arguments );
  38525. this.nCachedObjects_ = 0; // threshold
  38526. // note: read by PropertyBinding.Composite
  38527. const indices = {};
  38528. this._indicesByUUID = indices; // for bookkeeping
  38529. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38530. indices[ arguments[ i ].uuid ] = i;
  38531. }
  38532. this._paths = []; // inside: string
  38533. this._parsedPaths = []; // inside: { we don't care, here }
  38534. this._bindings = []; // inside: Array< PropertyBinding >
  38535. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38536. const scope = this;
  38537. this.stats = {
  38538. objects: {
  38539. get total() {
  38540. return scope._objects.length;
  38541. },
  38542. get inUse() {
  38543. return this.total - scope.nCachedObjects_;
  38544. }
  38545. },
  38546. get bindingsPerObject() {
  38547. return scope._bindings.length;
  38548. }
  38549. };
  38550. }
  38551. /**
  38552. * Adds an arbitrary number of objects to this animation group.
  38553. *
  38554. * @param {...Object3D} arguments - The 3D objects to add.
  38555. */
  38556. add() {
  38557. const objects = this._objects,
  38558. indicesByUUID = this._indicesByUUID,
  38559. paths = this._paths,
  38560. parsedPaths = this._parsedPaths,
  38561. bindings = this._bindings,
  38562. nBindings = bindings.length;
  38563. let knownObject = undefined,
  38564. nObjects = objects.length,
  38565. nCachedObjects = this.nCachedObjects_;
  38566. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38567. const object = arguments[ i ],
  38568. uuid = object.uuid;
  38569. let index = indicesByUUID[ uuid ];
  38570. if ( index === undefined ) {
  38571. // unknown object -> add it to the ACTIVE region
  38572. index = nObjects ++;
  38573. indicesByUUID[ uuid ] = index;
  38574. objects.push( object );
  38575. // accounting is done, now do the same for all bindings
  38576. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38577. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38578. }
  38579. } else if ( index < nCachedObjects ) {
  38580. knownObject = objects[ index ];
  38581. // move existing object to the ACTIVE region
  38582. const firstActiveIndex = -- nCachedObjects,
  38583. lastCachedObject = objects[ firstActiveIndex ];
  38584. indicesByUUID[ lastCachedObject.uuid ] = index;
  38585. objects[ index ] = lastCachedObject;
  38586. indicesByUUID[ uuid ] = firstActiveIndex;
  38587. objects[ firstActiveIndex ] = object;
  38588. // accounting is done, now do the same for all bindings
  38589. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38590. const bindingsForPath = bindings[ j ],
  38591. lastCached = bindingsForPath[ firstActiveIndex ];
  38592. let binding = bindingsForPath[ index ];
  38593. bindingsForPath[ index ] = lastCached;
  38594. if ( binding === undefined ) {
  38595. // since we do not bother to create new bindings
  38596. // for objects that are cached, the binding may
  38597. // or may not exist
  38598. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38599. }
  38600. bindingsForPath[ firstActiveIndex ] = binding;
  38601. }
  38602. } else if ( objects[ index ] !== knownObject ) {
  38603. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38604. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38605. } // else the object is already where we want it to be
  38606. } // for arguments
  38607. this.nCachedObjects_ = nCachedObjects;
  38608. }
  38609. /**
  38610. * Removes an arbitrary number of objects to this animation group
  38611. *
  38612. * @param {...Object3D} arguments - The 3D objects to remove.
  38613. */
  38614. remove() {
  38615. const objects = this._objects,
  38616. indicesByUUID = this._indicesByUUID,
  38617. bindings = this._bindings,
  38618. nBindings = bindings.length;
  38619. let nCachedObjects = this.nCachedObjects_;
  38620. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38621. const object = arguments[ i ],
  38622. uuid = object.uuid,
  38623. index = indicesByUUID[ uuid ];
  38624. if ( index !== undefined && index >= nCachedObjects ) {
  38625. // move existing object into the CACHED region
  38626. const lastCachedIndex = nCachedObjects ++,
  38627. firstActiveObject = objects[ lastCachedIndex ];
  38628. indicesByUUID[ firstActiveObject.uuid ] = index;
  38629. objects[ index ] = firstActiveObject;
  38630. indicesByUUID[ uuid ] = lastCachedIndex;
  38631. objects[ lastCachedIndex ] = object;
  38632. // accounting is done, now do the same for all bindings
  38633. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38634. const bindingsForPath = bindings[ j ],
  38635. firstActive = bindingsForPath[ lastCachedIndex ],
  38636. binding = bindingsForPath[ index ];
  38637. bindingsForPath[ index ] = firstActive;
  38638. bindingsForPath[ lastCachedIndex ] = binding;
  38639. }
  38640. }
  38641. } // for arguments
  38642. this.nCachedObjects_ = nCachedObjects;
  38643. }
  38644. /**
  38645. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38646. *
  38647. * @param {...Object3D} arguments - The 3D objects to uncache.
  38648. */
  38649. uncache() {
  38650. const objects = this._objects,
  38651. indicesByUUID = this._indicesByUUID,
  38652. bindings = this._bindings,
  38653. nBindings = bindings.length;
  38654. let nCachedObjects = this.nCachedObjects_,
  38655. nObjects = objects.length;
  38656. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38657. const object = arguments[ i ],
  38658. uuid = object.uuid,
  38659. index = indicesByUUID[ uuid ];
  38660. if ( index !== undefined ) {
  38661. delete indicesByUUID[ uuid ];
  38662. if ( index < nCachedObjects ) {
  38663. // object is cached, shrink the CACHED region
  38664. const firstActiveIndex = -- nCachedObjects,
  38665. lastCachedObject = objects[ firstActiveIndex ],
  38666. lastIndex = -- nObjects,
  38667. lastObject = objects[ lastIndex ];
  38668. // last cached object takes this object's place
  38669. indicesByUUID[ lastCachedObject.uuid ] = index;
  38670. objects[ index ] = lastCachedObject;
  38671. // last object goes to the activated slot and pop
  38672. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38673. objects[ firstActiveIndex ] = lastObject;
  38674. objects.pop();
  38675. // accounting is done, now do the same for all bindings
  38676. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38677. const bindingsForPath = bindings[ j ],
  38678. lastCached = bindingsForPath[ firstActiveIndex ],
  38679. last = bindingsForPath[ lastIndex ];
  38680. bindingsForPath[ index ] = lastCached;
  38681. bindingsForPath[ firstActiveIndex ] = last;
  38682. bindingsForPath.pop();
  38683. }
  38684. } else {
  38685. // object is active, just swap with the last and pop
  38686. const lastIndex = -- nObjects,
  38687. lastObject = objects[ lastIndex ];
  38688. if ( lastIndex > 0 ) {
  38689. indicesByUUID[ lastObject.uuid ] = index;
  38690. }
  38691. objects[ index ] = lastObject;
  38692. objects.pop();
  38693. // accounting is done, now do the same for all bindings
  38694. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38695. const bindingsForPath = bindings[ j ];
  38696. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38697. bindingsForPath.pop();
  38698. }
  38699. } // cached or active
  38700. } // if object is known
  38701. } // for arguments
  38702. this.nCachedObjects_ = nCachedObjects;
  38703. }
  38704. // Internal interface used by befriended PropertyBinding.Composite:
  38705. subscribe_( path, parsedPath ) {
  38706. // returns an array of bindings for the given path that is changed
  38707. // according to the contained objects in the group
  38708. const indicesByPath = this._bindingsIndicesByPath;
  38709. let index = indicesByPath[ path ];
  38710. const bindings = this._bindings;
  38711. if ( index !== undefined ) return bindings[ index ];
  38712. const paths = this._paths,
  38713. parsedPaths = this._parsedPaths,
  38714. objects = this._objects,
  38715. nObjects = objects.length,
  38716. nCachedObjects = this.nCachedObjects_,
  38717. bindingsForPath = new Array( nObjects );
  38718. index = bindings.length;
  38719. indicesByPath[ path ] = index;
  38720. paths.push( path );
  38721. parsedPaths.push( parsedPath );
  38722. bindings.push( bindingsForPath );
  38723. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38724. const object = objects[ i ];
  38725. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38726. }
  38727. return bindingsForPath;
  38728. }
  38729. unsubscribe_( path ) {
  38730. // tells the group to forget about a property path and no longer
  38731. // update the array previously obtained with 'subscribe_'
  38732. const indicesByPath = this._bindingsIndicesByPath,
  38733. index = indicesByPath[ path ];
  38734. if ( index !== undefined ) {
  38735. const paths = this._paths,
  38736. parsedPaths = this._parsedPaths,
  38737. bindings = this._bindings,
  38738. lastBindingsIndex = bindings.length - 1,
  38739. lastBindings = bindings[ lastBindingsIndex ],
  38740. lastBindingsPath = path[ lastBindingsIndex ];
  38741. indicesByPath[ lastBindingsPath ] = index;
  38742. bindings[ index ] = lastBindings;
  38743. bindings.pop();
  38744. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38745. parsedPaths.pop();
  38746. paths[ index ] = paths[ lastBindingsIndex ];
  38747. paths.pop();
  38748. }
  38749. }
  38750. }
  38751. /**
  38752. * An instance of `AnimationAction` schedules the playback of an animation which is
  38753. * stored in {@link AnimationClip}.
  38754. */
  38755. class AnimationAction {
  38756. /**
  38757. * Constructs a new animation action.
  38758. *
  38759. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38760. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38761. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38762. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38763. */
  38764. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38765. this._mixer = mixer;
  38766. this._clip = clip;
  38767. this._localRoot = localRoot;
  38768. /**
  38769. * Defines how the animation is blended/combined when two or more animations
  38770. * are simultaneously played.
  38771. *
  38772. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38773. */
  38774. this.blendMode = blendMode;
  38775. const tracks = clip.tracks,
  38776. nTracks = tracks.length,
  38777. interpolants = new Array( nTracks );
  38778. const interpolantSettings = {
  38779. endingStart: ZeroCurvatureEnding,
  38780. endingEnd: ZeroCurvatureEnding
  38781. };
  38782. for ( let i = 0; i !== nTracks; ++ i ) {
  38783. const interpolant = tracks[ i ].createInterpolant( null );
  38784. interpolants[ i ] = interpolant;
  38785. // preserve interpolant settings (like tangent data from BezierInterpolant)
  38786. if ( interpolant.settings ) {
  38787. Object.assign( interpolantSettings, interpolant.settings );
  38788. }
  38789. interpolant.settings = interpolantSettings;
  38790. }
  38791. this._interpolantSettings = interpolantSettings;
  38792. this._interpolants = interpolants; // bound by the mixer
  38793. // inside: PropertyMixer (managed by the mixer)
  38794. this._propertyBindings = new Array( nTracks );
  38795. this._cacheIndex = null; // for the memory manager
  38796. this._byClipCacheIndex = null; // for the memory manager
  38797. this._timeScaleInterpolant = null;
  38798. this._weightInterpolant = null;
  38799. /**
  38800. * The loop mode, set via {@link AnimationAction#setLoop}.
  38801. *
  38802. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38803. * @default LoopRepeat
  38804. */
  38805. this.loop = LoopRepeat;
  38806. this._loopCount = -1;
  38807. // global mixer time when the action is to be started
  38808. // it's set back to 'null' upon start of the action
  38809. this._startTime = null;
  38810. /**
  38811. * The local time of this action (in seconds, starting with `0`).
  38812. *
  38813. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38814. * loop state).
  38815. *
  38816. * @type {number}
  38817. * @default Infinity
  38818. */
  38819. this.time = 0;
  38820. /**
  38821. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38822. * animation to pause. Negative values cause the animation to play backwards.
  38823. *
  38824. * @type {number}
  38825. * @default 1
  38826. */
  38827. this.timeScale = 1;
  38828. this._effectiveTimeScale = 1;
  38829. /**
  38830. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38831. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38832. * several actions.
  38833. *
  38834. * @type {number}
  38835. * @default 1
  38836. */
  38837. this.weight = 1;
  38838. this._effectiveWeight = 1;
  38839. /**
  38840. * The number of repetitions of the performed clip over the course of this action.
  38841. * Can be set via {@link AnimationAction#setLoop}.
  38842. *
  38843. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38844. * `THREE:LoopOnce`.
  38845. *
  38846. * @type {number}
  38847. * @default Infinity
  38848. */
  38849. this.repetitions = Infinity;
  38850. /**
  38851. * If set to `true`, the playback of the action is paused.
  38852. *
  38853. * @type {boolean}
  38854. * @default false
  38855. */
  38856. this.paused = false;
  38857. /**
  38858. * If set to `false`, the action is disabled so it has no impact.
  38859. *
  38860. * When the action is re-enabled, the animation continues from its current
  38861. * time (setting `enabled` to `false` doesn't reset the action).
  38862. *
  38863. * @type {boolean}
  38864. * @default true
  38865. */
  38866. this.enabled = true;
  38867. /**
  38868. * If set to true the animation will automatically be paused on its last frame.
  38869. *
  38870. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38871. * to `false` when the last loop of the action has finished, so that this action has
  38872. * no further impact.
  38873. *
  38874. * Note: This member has no impact if the action is interrupted (it
  38875. * has only an effect if its last loop has really finished).
  38876. *
  38877. * @type {boolean}
  38878. * @default false
  38879. */
  38880. this.clampWhenFinished = false;
  38881. /**
  38882. * Enables smooth interpolation without separate clips for start, loop and end.
  38883. *
  38884. * @type {boolean}
  38885. * @default true
  38886. */
  38887. this.zeroSlopeAtStart = true;
  38888. /**
  38889. * Enables smooth interpolation without separate clips for start, loop and end.
  38890. *
  38891. * @type {boolean}
  38892. * @default true
  38893. */
  38894. this.zeroSlopeAtEnd = true;
  38895. }
  38896. /**
  38897. * Starts the playback of the animation.
  38898. *
  38899. * @return {AnimationAction} A reference to this animation action.
  38900. */
  38901. play() {
  38902. this._mixer._activateAction( this );
  38903. return this;
  38904. }
  38905. /**
  38906. * Stops the playback of the animation.
  38907. *
  38908. * @return {AnimationAction} A reference to this animation action.
  38909. */
  38910. stop() {
  38911. this._mixer._deactivateAction( this );
  38912. return this.reset();
  38913. }
  38914. /**
  38915. * Resets the playback of the animation.
  38916. *
  38917. * @return {AnimationAction} A reference to this animation action.
  38918. */
  38919. reset() {
  38920. this.paused = false;
  38921. this.enabled = true;
  38922. this.time = 0; // restart clip
  38923. this._loopCount = -1;// forget previous loops
  38924. this._startTime = null;// forget scheduling
  38925. return this.stopFading().stopWarping();
  38926. }
  38927. /**
  38928. * Returns `true` if the animation is running.
  38929. *
  38930. * @return {boolean} Whether the animation is running or not.
  38931. */
  38932. isRunning() {
  38933. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38934. this._startTime === null && this._mixer._isActiveAction( this );
  38935. }
  38936. /**
  38937. * Returns `true` when {@link AnimationAction#play} has been called.
  38938. *
  38939. * @return {boolean} Whether the animation is scheduled or not.
  38940. */
  38941. isScheduled() {
  38942. return this._mixer._isActiveAction( this );
  38943. }
  38944. /**
  38945. * Defines the time when the animation should start.
  38946. *
  38947. * @param {number} time - The start time in seconds.
  38948. * @return {AnimationAction} A reference to this animation action.
  38949. */
  38950. startAt( time ) {
  38951. this._startTime = time;
  38952. return this;
  38953. }
  38954. /**
  38955. * Configures the loop settings for this action.
  38956. *
  38957. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38958. * @param {number} repetitions - The number of repetitions.
  38959. * @return {AnimationAction} A reference to this animation action.
  38960. */
  38961. setLoop( mode, repetitions ) {
  38962. this.loop = mode;
  38963. this.repetitions = repetitions;
  38964. return this;
  38965. }
  38966. /**
  38967. * Sets the effective weight of this action.
  38968. *
  38969. * An action has no effect and thus an effective weight of zero when the
  38970. * action is disabled.
  38971. *
  38972. * @param {number} weight - The weight to set.
  38973. * @return {AnimationAction} A reference to this animation action.
  38974. */
  38975. setEffectiveWeight( weight ) {
  38976. this.weight = weight;
  38977. // note: same logic as when updated at runtime
  38978. this._effectiveWeight = this.enabled ? weight : 0;
  38979. return this.stopFading();
  38980. }
  38981. /**
  38982. * Returns the effective weight of this action.
  38983. *
  38984. * @return {number} The effective weight.
  38985. */
  38986. getEffectiveWeight() {
  38987. return this._effectiveWeight;
  38988. }
  38989. /**
  38990. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38991. * within the passed time interval.
  38992. *
  38993. * @param {number} duration - The duration of the fade.
  38994. * @return {AnimationAction} A reference to this animation action.
  38995. */
  38996. fadeIn( duration ) {
  38997. return this._scheduleFading( duration, 0, 1 );
  38998. }
  38999. /**
  39000. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  39001. * within the passed time interval.
  39002. *
  39003. * @param {number} duration - The duration of the fade.
  39004. * @return {AnimationAction} A reference to this animation action.
  39005. */
  39006. fadeOut( duration ) {
  39007. return this._scheduleFading( duration, 1, 0 );
  39008. }
  39009. /**
  39010. * Causes this action to fade in and the given action to fade out,
  39011. * within the passed time interval.
  39012. *
  39013. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  39014. * @param {number} duration - The duration of the fade.
  39015. * @param {boolean} [warp=false] - Whether warping should be used or not.
  39016. * @return {AnimationAction} A reference to this animation action.
  39017. */
  39018. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  39019. fadeOutAction.fadeOut( duration );
  39020. this.fadeIn( duration );
  39021. if ( warp === true ) {
  39022. const fadeInDuration = this._clip.duration,
  39023. fadeOutDuration = fadeOutAction._clip.duration,
  39024. startEndRatio = fadeOutDuration / fadeInDuration,
  39025. endStartRatio = fadeInDuration / fadeOutDuration;
  39026. fadeOutAction.warp( 1.0, startEndRatio, duration );
  39027. this.warp( endStartRatio, 1.0, duration );
  39028. }
  39029. return this;
  39030. }
  39031. /**
  39032. * Causes this action to fade out and the given action to fade in,
  39033. * within the passed time interval.
  39034. *
  39035. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  39036. * @param {number} duration - The duration of the fade.
  39037. * @param {boolean} [warp=false] - Whether warping should be used or not.
  39038. * @return {AnimationAction} A reference to this animation action.
  39039. */
  39040. crossFadeTo( fadeInAction, duration, warp = false ) {
  39041. return fadeInAction.crossFadeFrom( this, duration, warp );
  39042. }
  39043. /**
  39044. * Stops any fading which is applied to this action.
  39045. *
  39046. * @return {AnimationAction} A reference to this animation action.
  39047. */
  39048. stopFading() {
  39049. const weightInterpolant = this._weightInterpolant;
  39050. if ( weightInterpolant !== null ) {
  39051. this._weightInterpolant = null;
  39052. this._mixer._takeBackControlInterpolant( weightInterpolant );
  39053. }
  39054. return this;
  39055. }
  39056. /**
  39057. * Sets the effective time scale of this action.
  39058. *
  39059. * An action has no effect and thus an effective time scale of zero when the
  39060. * action is paused.
  39061. *
  39062. * @param {number} timeScale - The time scale to set.
  39063. * @return {AnimationAction} A reference to this animation action.
  39064. */
  39065. setEffectiveTimeScale( timeScale ) {
  39066. this.timeScale = timeScale;
  39067. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  39068. return this.stopWarping();
  39069. }
  39070. /**
  39071. * Returns the effective time scale of this action.
  39072. *
  39073. * @return {number} The effective time scale.
  39074. */
  39075. getEffectiveTimeScale() {
  39076. return this._effectiveTimeScale;
  39077. }
  39078. /**
  39079. * Sets the duration for a single loop of this action.
  39080. *
  39081. * @param {number} duration - The duration to set.
  39082. * @return {AnimationAction} A reference to this animation action.
  39083. */
  39084. setDuration( duration ) {
  39085. this.timeScale = this._clip.duration / duration;
  39086. return this.stopWarping();
  39087. }
  39088. /**
  39089. * Synchronizes this action with the passed other action.
  39090. *
  39091. * @param {AnimationAction} action - The action to sync with.
  39092. * @return {AnimationAction} A reference to this animation action.
  39093. */
  39094. syncWith( action ) {
  39095. this.time = action.time;
  39096. this.timeScale = action.timeScale;
  39097. return this.stopWarping();
  39098. }
  39099. /**
  39100. * Decelerates this animation's speed to `0` within the passed time interval.
  39101. *
  39102. * @param {number} duration - The duration.
  39103. * @return {AnimationAction} A reference to this animation action.
  39104. */
  39105. halt( duration ) {
  39106. return this.warp( this._effectiveTimeScale, 0, duration );
  39107. }
  39108. /**
  39109. * Changes the playback speed, within the passed time interval, by modifying
  39110. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  39111. * `endTimeScale`.
  39112. *
  39113. * @param {number} startTimeScale - The start time scale.
  39114. * @param {number} endTimeScale - The end time scale.
  39115. * @param {number} duration - The duration.
  39116. * @return {AnimationAction} A reference to this animation action.
  39117. */
  39118. warp( startTimeScale, endTimeScale, duration ) {
  39119. const mixer = this._mixer,
  39120. now = mixer.time,
  39121. timeScale = this.timeScale;
  39122. let interpolant = this._timeScaleInterpolant;
  39123. if ( interpolant === null ) {
  39124. interpolant = mixer._lendControlInterpolant();
  39125. this._timeScaleInterpolant = interpolant;
  39126. }
  39127. const times = interpolant.parameterPositions,
  39128. values = interpolant.sampleValues;
  39129. times[ 0 ] = now;
  39130. times[ 1 ] = now + duration;
  39131. values[ 0 ] = startTimeScale / timeScale;
  39132. values[ 1 ] = endTimeScale / timeScale;
  39133. return this;
  39134. }
  39135. /**
  39136. * Stops any scheduled warping which is applied to this action.
  39137. *
  39138. * @return {AnimationAction} A reference to this animation action.
  39139. */
  39140. stopWarping() {
  39141. const timeScaleInterpolant = this._timeScaleInterpolant;
  39142. if ( timeScaleInterpolant !== null ) {
  39143. this._timeScaleInterpolant = null;
  39144. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  39145. }
  39146. return this;
  39147. }
  39148. /**
  39149. * Returns the animation mixer of this animation action.
  39150. *
  39151. * @return {AnimationMixer} The animation mixer.
  39152. */
  39153. getMixer() {
  39154. return this._mixer;
  39155. }
  39156. /**
  39157. * Returns the animation clip of this animation action.
  39158. *
  39159. * @return {AnimationClip} The animation clip.
  39160. */
  39161. getClip() {
  39162. return this._clip;
  39163. }
  39164. /**
  39165. * Returns the root object of this animation action.
  39166. *
  39167. * @return {Object3D} The root object.
  39168. */
  39169. getRoot() {
  39170. return this._localRoot || this._mixer._root;
  39171. }
  39172. // Internal
  39173. _update( time, deltaTime, timeDirection, accuIndex ) {
  39174. // called by the mixer
  39175. if ( ! this.enabled ) {
  39176. // call ._updateWeight() to update ._effectiveWeight
  39177. this._updateWeight( time );
  39178. return;
  39179. }
  39180. const startTime = this._startTime;
  39181. if ( startTime !== null ) {
  39182. // check for scheduled start of action
  39183. const timeRunning = ( time - startTime ) * timeDirection;
  39184. if ( timeRunning < 0 || timeDirection === 0 ) {
  39185. deltaTime = 0;
  39186. } else {
  39187. this._startTime = null; // unschedule
  39188. deltaTime = timeDirection * timeRunning;
  39189. }
  39190. }
  39191. // apply time scale and advance time
  39192. deltaTime *= this._updateTimeScale( time );
  39193. const clipTime = this._updateTime( deltaTime );
  39194. // note: _updateTime may disable the action resulting in
  39195. // an effective weight of 0
  39196. const weight = this._updateWeight( time );
  39197. if ( weight > 0 ) {
  39198. const interpolants = this._interpolants;
  39199. const propertyMixers = this._propertyBindings;
  39200. switch ( this.blendMode ) {
  39201. case AdditiveAnimationBlendMode:
  39202. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39203. interpolants[ j ].evaluate( clipTime );
  39204. propertyMixers[ j ].accumulateAdditive( weight );
  39205. }
  39206. break;
  39207. case NormalAnimationBlendMode:
  39208. default:
  39209. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39210. interpolants[ j ].evaluate( clipTime );
  39211. propertyMixers[ j ].accumulate( accuIndex, weight );
  39212. }
  39213. }
  39214. }
  39215. }
  39216. _updateWeight( time ) {
  39217. let weight = 0;
  39218. if ( this.enabled ) {
  39219. weight = this.weight;
  39220. const interpolant = this._weightInterpolant;
  39221. if ( interpolant !== null ) {
  39222. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39223. weight *= interpolantValue;
  39224. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39225. this.stopFading();
  39226. if ( interpolantValue === 0 ) {
  39227. // faded out, disable
  39228. this.enabled = false;
  39229. }
  39230. }
  39231. }
  39232. }
  39233. this._effectiveWeight = weight;
  39234. return weight;
  39235. }
  39236. _updateTimeScale( time ) {
  39237. let timeScale = 0;
  39238. if ( ! this.paused ) {
  39239. timeScale = this.timeScale;
  39240. const interpolant = this._timeScaleInterpolant;
  39241. if ( interpolant !== null ) {
  39242. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39243. timeScale *= interpolantValue;
  39244. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39245. this.stopWarping();
  39246. if ( timeScale === 0 ) {
  39247. // motion has halted, pause
  39248. this.paused = true;
  39249. } else {
  39250. // warp done - apply final time scale
  39251. this.timeScale = timeScale;
  39252. }
  39253. }
  39254. }
  39255. }
  39256. this._effectiveTimeScale = timeScale;
  39257. return timeScale;
  39258. }
  39259. _updateTime( deltaTime ) {
  39260. const duration = this._clip.duration;
  39261. const loop = this.loop;
  39262. let time = this.time + deltaTime;
  39263. let loopCount = this._loopCount;
  39264. const pingPong = ( loop === LoopPingPong );
  39265. if ( deltaTime === 0 ) {
  39266. if ( loopCount === -1 ) return time;
  39267. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  39268. }
  39269. if ( loop === LoopOnce ) {
  39270. if ( loopCount === -1 ) {
  39271. // just started
  39272. this._loopCount = 0;
  39273. this._setEndings( true, true, false );
  39274. }
  39275. handle_stop: {
  39276. if ( time >= duration ) {
  39277. time = duration;
  39278. } else if ( time < 0 ) {
  39279. time = 0;
  39280. } else {
  39281. this.time = time;
  39282. break handle_stop;
  39283. }
  39284. if ( this.clampWhenFinished ) this.paused = true;
  39285. else this.enabled = false;
  39286. this.time = time;
  39287. this._mixer.dispatchEvent( {
  39288. type: 'finished', action: this,
  39289. direction: deltaTime < 0 ? -1 : 1
  39290. } );
  39291. }
  39292. } else { // repetitive Repeat or PingPong
  39293. if ( loopCount === -1 ) {
  39294. // just started
  39295. if ( deltaTime >= 0 ) {
  39296. loopCount = 0;
  39297. this._setEndings( true, this.repetitions === 0, pingPong );
  39298. } else {
  39299. // when looping in reverse direction, the initial
  39300. // transition through zero counts as a repetition,
  39301. // so leave loopCount at -1
  39302. this._setEndings( this.repetitions === 0, true, pingPong );
  39303. }
  39304. }
  39305. if ( time >= duration || time < 0 ) {
  39306. // wrap around
  39307. const loopDelta = Math.floor( time / duration ); // signed
  39308. time -= duration * loopDelta;
  39309. loopCount += Math.abs( loopDelta );
  39310. const pending = this.repetitions - loopCount;
  39311. if ( pending <= 0 ) {
  39312. // have to stop (switch state, clamp time, fire event)
  39313. if ( this.clampWhenFinished ) this.paused = true;
  39314. else this.enabled = false;
  39315. time = deltaTime > 0 ? duration : 0;
  39316. this.time = time;
  39317. this._mixer.dispatchEvent( {
  39318. type: 'finished', action: this,
  39319. direction: deltaTime > 0 ? 1 : -1
  39320. } );
  39321. } else {
  39322. // keep running
  39323. if ( pending === 1 ) {
  39324. // entering the last round
  39325. const atStart = deltaTime < 0;
  39326. this._setEndings( atStart, ! atStart, pingPong );
  39327. } else {
  39328. this._setEndings( false, false, pingPong );
  39329. }
  39330. this._loopCount = loopCount;
  39331. this.time = time;
  39332. this._mixer.dispatchEvent( {
  39333. type: 'loop', action: this, loopDelta: loopDelta
  39334. } );
  39335. }
  39336. } else {
  39337. this._loopCount = loopCount;
  39338. this.time = time;
  39339. }
  39340. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39341. // invert time for the "pong round"
  39342. return duration - time;
  39343. }
  39344. }
  39345. return time;
  39346. }
  39347. _setEndings( atStart, atEnd, pingPong ) {
  39348. const settings = this._interpolantSettings;
  39349. if ( pingPong ) {
  39350. settings.endingStart = ZeroSlopeEnding;
  39351. settings.endingEnd = ZeroSlopeEnding;
  39352. } else {
  39353. // assuming for LoopOnce atStart == atEnd == true
  39354. if ( atStart ) {
  39355. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39356. } else {
  39357. settings.endingStart = WrapAroundEnding;
  39358. }
  39359. if ( atEnd ) {
  39360. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39361. } else {
  39362. settings.endingEnd = WrapAroundEnding;
  39363. }
  39364. }
  39365. }
  39366. _scheduleFading( duration, weightNow, weightThen ) {
  39367. const mixer = this._mixer, now = mixer.time;
  39368. let interpolant = this._weightInterpolant;
  39369. if ( interpolant === null ) {
  39370. interpolant = mixer._lendControlInterpolant();
  39371. this._weightInterpolant = interpolant;
  39372. }
  39373. const times = interpolant.parameterPositions,
  39374. values = interpolant.sampleValues;
  39375. times[ 0 ] = now;
  39376. values[ 0 ] = weightNow;
  39377. times[ 1 ] = now + duration;
  39378. values[ 1 ] = weightThen;
  39379. return this;
  39380. }
  39381. }
  39382. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39383. /**
  39384. * `AnimationMixer` is a player for animations on a particular object in
  39385. * the scene. When multiple objects in the scene are animated independently,
  39386. * one `AnimationMixer` may be used for each object.
  39387. */
  39388. class AnimationMixer extends EventDispatcher {
  39389. /**
  39390. * Constructs a new animation mixer.
  39391. *
  39392. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39393. */
  39394. constructor( root ) {
  39395. super();
  39396. this._root = root;
  39397. this._initMemoryManager();
  39398. this._accuIndex = 0;
  39399. /**
  39400. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39401. *
  39402. * @type {number}
  39403. * @default 0
  39404. */
  39405. this.time = 0;
  39406. /**
  39407. * A scaling factor for the global time.
  39408. *
  39409. * Note: Setting this member to `0` and later back to `1` is a
  39410. * possibility to pause/unpause all actions that are controlled by this
  39411. * mixer.
  39412. *
  39413. * @type {number}
  39414. * @default 1
  39415. */
  39416. this.timeScale = 1.0;
  39417. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39418. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39419. }
  39420. }
  39421. _bindAction( action, prototypeAction ) {
  39422. const root = action._localRoot || this._root,
  39423. tracks = action._clip.tracks,
  39424. nTracks = tracks.length,
  39425. bindings = action._propertyBindings,
  39426. interpolants = action._interpolants,
  39427. rootUuid = root.uuid,
  39428. bindingsByRoot = this._bindingsByRootAndName;
  39429. let bindingsByName = bindingsByRoot[ rootUuid ];
  39430. if ( bindingsByName === undefined ) {
  39431. bindingsByName = {};
  39432. bindingsByRoot[ rootUuid ] = bindingsByName;
  39433. }
  39434. for ( let i = 0; i !== nTracks; ++ i ) {
  39435. const track = tracks[ i ],
  39436. trackName = track.name;
  39437. let binding = bindingsByName[ trackName ];
  39438. if ( binding !== undefined ) {
  39439. ++ binding.referenceCount;
  39440. bindings[ i ] = binding;
  39441. } else {
  39442. binding = bindings[ i ];
  39443. if ( binding !== undefined ) {
  39444. // existing binding, make sure the cache knows
  39445. if ( binding._cacheIndex === null ) {
  39446. ++ binding.referenceCount;
  39447. this._addInactiveBinding( binding, rootUuid, trackName );
  39448. }
  39449. continue;
  39450. }
  39451. const path = prototypeAction && prototypeAction.
  39452. _propertyBindings[ i ].binding.parsedPath;
  39453. binding = new PropertyMixer(
  39454. PropertyBinding.create( root, trackName, path ),
  39455. track.ValueTypeName, track.getValueSize() );
  39456. ++ binding.referenceCount;
  39457. this._addInactiveBinding( binding, rootUuid, trackName );
  39458. bindings[ i ] = binding;
  39459. }
  39460. interpolants[ i ].resultBuffer = binding.buffer;
  39461. }
  39462. }
  39463. _activateAction( action ) {
  39464. if ( ! this._isActiveAction( action ) ) {
  39465. if ( action._cacheIndex === null ) {
  39466. // this action has been forgotten by the cache, but the user
  39467. // appears to be still using it -> rebind
  39468. const rootUuid = ( action._localRoot || this._root ).uuid,
  39469. clipUuid = action._clip.uuid,
  39470. actionsForClip = this._actionsByClip[ clipUuid ];
  39471. this._bindAction( action,
  39472. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39473. this._addInactiveAction( action, clipUuid, rootUuid );
  39474. }
  39475. const bindings = action._propertyBindings;
  39476. // increment reference counts / sort out state
  39477. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39478. const binding = bindings[ i ];
  39479. if ( binding.useCount ++ === 0 ) {
  39480. this._lendBinding( binding );
  39481. binding.saveOriginalState();
  39482. }
  39483. }
  39484. this._lendAction( action );
  39485. }
  39486. }
  39487. _deactivateAction( action ) {
  39488. if ( this._isActiveAction( action ) ) {
  39489. const bindings = action._propertyBindings;
  39490. // decrement reference counts / sort out state
  39491. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39492. const binding = bindings[ i ];
  39493. if ( -- binding.useCount === 0 ) {
  39494. binding.restoreOriginalState();
  39495. this._takeBackBinding( binding );
  39496. }
  39497. }
  39498. this._takeBackAction( action );
  39499. }
  39500. }
  39501. // Memory manager
  39502. _initMemoryManager() {
  39503. this._actions = []; // 'nActiveActions' followed by inactive ones
  39504. this._nActiveActions = 0;
  39505. this._actionsByClip = {};
  39506. // inside:
  39507. // {
  39508. // knownActions: Array< AnimationAction > - used as prototypes
  39509. // actionByRoot: AnimationAction - lookup
  39510. // }
  39511. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39512. this._nActiveBindings = 0;
  39513. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39514. this._controlInterpolants = []; // same game as above
  39515. this._nActiveControlInterpolants = 0;
  39516. const scope = this;
  39517. this.stats = {
  39518. actions: {
  39519. get total() {
  39520. return scope._actions.length;
  39521. },
  39522. get inUse() {
  39523. return scope._nActiveActions;
  39524. }
  39525. },
  39526. bindings: {
  39527. get total() {
  39528. return scope._bindings.length;
  39529. },
  39530. get inUse() {
  39531. return scope._nActiveBindings;
  39532. }
  39533. },
  39534. controlInterpolants: {
  39535. get total() {
  39536. return scope._controlInterpolants.length;
  39537. },
  39538. get inUse() {
  39539. return scope._nActiveControlInterpolants;
  39540. }
  39541. }
  39542. };
  39543. }
  39544. // Memory management for AnimationAction objects
  39545. _isActiveAction( action ) {
  39546. const index = action._cacheIndex;
  39547. return index !== null && index < this._nActiveActions;
  39548. }
  39549. _addInactiveAction( action, clipUuid, rootUuid ) {
  39550. const actions = this._actions,
  39551. actionsByClip = this._actionsByClip;
  39552. let actionsForClip = actionsByClip[ clipUuid ];
  39553. if ( actionsForClip === undefined ) {
  39554. actionsForClip = {
  39555. knownActions: [ action ],
  39556. actionByRoot: {}
  39557. };
  39558. action._byClipCacheIndex = 0;
  39559. actionsByClip[ clipUuid ] = actionsForClip;
  39560. } else {
  39561. const knownActions = actionsForClip.knownActions;
  39562. action._byClipCacheIndex = knownActions.length;
  39563. knownActions.push( action );
  39564. }
  39565. action._cacheIndex = actions.length;
  39566. actions.push( action );
  39567. actionsForClip.actionByRoot[ rootUuid ] = action;
  39568. }
  39569. _removeInactiveAction( action ) {
  39570. const actions = this._actions,
  39571. lastInactiveAction = actions[ actions.length - 1 ],
  39572. cacheIndex = action._cacheIndex;
  39573. lastInactiveAction._cacheIndex = cacheIndex;
  39574. actions[ cacheIndex ] = lastInactiveAction;
  39575. actions.pop();
  39576. action._cacheIndex = null;
  39577. const clipUuid = action._clip.uuid,
  39578. actionsByClip = this._actionsByClip,
  39579. actionsForClip = actionsByClip[ clipUuid ],
  39580. knownActionsForClip = actionsForClip.knownActions,
  39581. lastKnownAction =
  39582. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39583. byClipCacheIndex = action._byClipCacheIndex;
  39584. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39585. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39586. knownActionsForClip.pop();
  39587. action._byClipCacheIndex = null;
  39588. const actionByRoot = actionsForClip.actionByRoot,
  39589. rootUuid = ( action._localRoot || this._root ).uuid;
  39590. delete actionByRoot[ rootUuid ];
  39591. if ( knownActionsForClip.length === 0 ) {
  39592. delete actionsByClip[ clipUuid ];
  39593. }
  39594. this._removeInactiveBindingsForAction( action );
  39595. }
  39596. _removeInactiveBindingsForAction( action ) {
  39597. const bindings = action._propertyBindings;
  39598. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39599. const binding = bindings[ i ];
  39600. if ( -- binding.referenceCount === 0 ) {
  39601. this._removeInactiveBinding( binding );
  39602. }
  39603. }
  39604. }
  39605. _lendAction( action ) {
  39606. // [ active actions | inactive actions ]
  39607. // [ active actions >| inactive actions ]
  39608. // s a
  39609. // <-swap->
  39610. // a s
  39611. const actions = this._actions,
  39612. prevIndex = action._cacheIndex,
  39613. lastActiveIndex = this._nActiveActions ++,
  39614. firstInactiveAction = actions[ lastActiveIndex ];
  39615. action._cacheIndex = lastActiveIndex;
  39616. actions[ lastActiveIndex ] = action;
  39617. firstInactiveAction._cacheIndex = prevIndex;
  39618. actions[ prevIndex ] = firstInactiveAction;
  39619. }
  39620. _takeBackAction( action ) {
  39621. // [ active actions | inactive actions ]
  39622. // [ active actions |< inactive actions ]
  39623. // a s
  39624. // <-swap->
  39625. // s a
  39626. const actions = this._actions,
  39627. prevIndex = action._cacheIndex,
  39628. firstInactiveIndex = -- this._nActiveActions,
  39629. lastActiveAction = actions[ firstInactiveIndex ];
  39630. action._cacheIndex = firstInactiveIndex;
  39631. actions[ firstInactiveIndex ] = action;
  39632. lastActiveAction._cacheIndex = prevIndex;
  39633. actions[ prevIndex ] = lastActiveAction;
  39634. }
  39635. // Memory management for PropertyMixer objects
  39636. _addInactiveBinding( binding, rootUuid, trackName ) {
  39637. const bindingsByRoot = this._bindingsByRootAndName,
  39638. bindings = this._bindings;
  39639. let bindingByName = bindingsByRoot[ rootUuid ];
  39640. if ( bindingByName === undefined ) {
  39641. bindingByName = {};
  39642. bindingsByRoot[ rootUuid ] = bindingByName;
  39643. }
  39644. bindingByName[ trackName ] = binding;
  39645. binding._cacheIndex = bindings.length;
  39646. bindings.push( binding );
  39647. }
  39648. _removeInactiveBinding( binding ) {
  39649. const bindings = this._bindings,
  39650. propBinding = binding.binding,
  39651. rootUuid = propBinding.rootNode.uuid,
  39652. trackName = propBinding.path,
  39653. bindingsByRoot = this._bindingsByRootAndName,
  39654. bindingByName = bindingsByRoot[ rootUuid ],
  39655. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39656. cacheIndex = binding._cacheIndex;
  39657. lastInactiveBinding._cacheIndex = cacheIndex;
  39658. bindings[ cacheIndex ] = lastInactiveBinding;
  39659. bindings.pop();
  39660. delete bindingByName[ trackName ];
  39661. if ( Object.keys( bindingByName ).length === 0 ) {
  39662. delete bindingsByRoot[ rootUuid ];
  39663. }
  39664. }
  39665. _lendBinding( binding ) {
  39666. const bindings = this._bindings,
  39667. prevIndex = binding._cacheIndex,
  39668. lastActiveIndex = this._nActiveBindings ++,
  39669. firstInactiveBinding = bindings[ lastActiveIndex ];
  39670. binding._cacheIndex = lastActiveIndex;
  39671. bindings[ lastActiveIndex ] = binding;
  39672. firstInactiveBinding._cacheIndex = prevIndex;
  39673. bindings[ prevIndex ] = firstInactiveBinding;
  39674. }
  39675. _takeBackBinding( binding ) {
  39676. const bindings = this._bindings,
  39677. prevIndex = binding._cacheIndex,
  39678. firstInactiveIndex = -- this._nActiveBindings,
  39679. lastActiveBinding = bindings[ firstInactiveIndex ];
  39680. binding._cacheIndex = firstInactiveIndex;
  39681. bindings[ firstInactiveIndex ] = binding;
  39682. lastActiveBinding._cacheIndex = prevIndex;
  39683. bindings[ prevIndex ] = lastActiveBinding;
  39684. }
  39685. // Memory management of Interpolants for weight and time scale
  39686. _lendControlInterpolant() {
  39687. const interpolants = this._controlInterpolants,
  39688. lastActiveIndex = this._nActiveControlInterpolants ++;
  39689. let interpolant = interpolants[ lastActiveIndex ];
  39690. if ( interpolant === undefined ) {
  39691. interpolant = new LinearInterpolant(
  39692. new Float32Array( 2 ), new Float32Array( 2 ),
  39693. 1, _controlInterpolantsResultBuffer );
  39694. interpolant.__cacheIndex = lastActiveIndex;
  39695. interpolants[ lastActiveIndex ] = interpolant;
  39696. }
  39697. return interpolant;
  39698. }
  39699. _takeBackControlInterpolant( interpolant ) {
  39700. const interpolants = this._controlInterpolants,
  39701. prevIndex = interpolant.__cacheIndex,
  39702. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39703. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39704. interpolant.__cacheIndex = firstInactiveIndex;
  39705. interpolants[ firstInactiveIndex ] = interpolant;
  39706. lastActiveInterpolant.__cacheIndex = prevIndex;
  39707. interpolants[ prevIndex ] = lastActiveInterpolant;
  39708. }
  39709. /**
  39710. * Returns an instance of {@link AnimationAction} for the passed clip.
  39711. *
  39712. * If an action fitting the clip and root parameters doesn't yet exist, it
  39713. * will be created by this method. Calling this method several times with the
  39714. * same clip and root parameters always returns the same action.
  39715. *
  39716. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39717. * @param {Object3D} [optionalRoot] - An alternative root object.
  39718. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39719. * @return {?AnimationAction} The animation action.
  39720. */
  39721. clipAction( clip, optionalRoot, blendMode ) {
  39722. const root = optionalRoot || this._root,
  39723. rootUuid = root.uuid;
  39724. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39725. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39726. const actionsForClip = this._actionsByClip[ clipUuid ];
  39727. let prototypeAction = null;
  39728. if ( blendMode === undefined ) {
  39729. if ( clipObject !== null ) {
  39730. blendMode = clipObject.blendMode;
  39731. } else {
  39732. blendMode = NormalAnimationBlendMode;
  39733. }
  39734. }
  39735. if ( actionsForClip !== undefined ) {
  39736. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39737. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39738. return existingAction;
  39739. }
  39740. // we know the clip, so we don't have to parse all
  39741. // the bindings again but can just copy
  39742. prototypeAction = actionsForClip.knownActions[ 0 ];
  39743. // also, take the clip from the prototype action
  39744. if ( clipObject === null )
  39745. clipObject = prototypeAction._clip;
  39746. }
  39747. // clip must be known when specified via string
  39748. if ( clipObject === null ) return null;
  39749. // allocate all resources required to run it
  39750. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39751. this._bindAction( newAction, prototypeAction );
  39752. // and make the action known to the memory manager
  39753. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39754. return newAction;
  39755. }
  39756. /**
  39757. * Returns an existing animation action for the passed clip.
  39758. *
  39759. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39760. * @param {Object3D} [optionalRoot] - An alternative root object.
  39761. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39762. */
  39763. existingAction( clip, optionalRoot ) {
  39764. const root = optionalRoot || this._root,
  39765. rootUuid = root.uuid,
  39766. clipObject = typeof clip === 'string' ?
  39767. AnimationClip.findByName( root, clip ) : clip,
  39768. clipUuid = clipObject ? clipObject.uuid : clip,
  39769. actionsForClip = this._actionsByClip[ clipUuid ];
  39770. if ( actionsForClip !== undefined ) {
  39771. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39772. }
  39773. return null;
  39774. }
  39775. /**
  39776. * Deactivates all previously scheduled actions on this mixer.
  39777. *
  39778. * @return {AnimationMixer} A reference to this animation mixer.
  39779. */
  39780. stopAllAction() {
  39781. const actions = this._actions,
  39782. nActions = this._nActiveActions;
  39783. for ( let i = nActions - 1; i >= 0; -- i ) {
  39784. actions[ i ].stop();
  39785. }
  39786. return this;
  39787. }
  39788. /**
  39789. * Advances the global mixer time and updates the animation.
  39790. *
  39791. * This is usually done in the render loop by passing the delta
  39792. * time from {@link Clock} or {@link Timer}.
  39793. *
  39794. * @param {number} deltaTime - The delta time in seconds.
  39795. * @return {AnimationMixer} A reference to this animation mixer.
  39796. */
  39797. update( deltaTime ) {
  39798. deltaTime *= this.timeScale;
  39799. const actions = this._actions,
  39800. nActions = this._nActiveActions,
  39801. time = this.time += deltaTime,
  39802. timeDirection = Math.sign( deltaTime ),
  39803. accuIndex = this._accuIndex ^= 1;
  39804. // run active actions
  39805. for ( let i = 0; i !== nActions; ++ i ) {
  39806. const action = actions[ i ];
  39807. action._update( time, deltaTime, timeDirection, accuIndex );
  39808. }
  39809. // update scene graph
  39810. const bindings = this._bindings,
  39811. nBindings = this._nActiveBindings;
  39812. for ( let i = 0; i !== nBindings; ++ i ) {
  39813. bindings[ i ].apply( accuIndex );
  39814. }
  39815. return this;
  39816. }
  39817. /**
  39818. * Sets the global mixer to a specific time and updates the animation accordingly.
  39819. *
  39820. * This is useful when you need to jump to an exact time in an animation. The
  39821. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39822. *
  39823. * @param {number} time - The time to set in seconds.
  39824. * @return {AnimationMixer} A reference to this animation mixer.
  39825. */
  39826. setTime( time ) {
  39827. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39828. for ( let i = 0; i < this._actions.length; i ++ ) {
  39829. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39830. }
  39831. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39832. }
  39833. /**
  39834. * Returns this mixer's root object.
  39835. *
  39836. * @return {Object3D} The mixer's root object.
  39837. */
  39838. getRoot() {
  39839. return this._root;
  39840. }
  39841. /**
  39842. * Deallocates all memory resources for a clip. Before using this method make
  39843. * sure to call {@link AnimationAction#stop} for all related actions.
  39844. *
  39845. * @param {AnimationClip} clip - The clip to uncache.
  39846. */
  39847. uncacheClip( clip ) {
  39848. const actions = this._actions,
  39849. clipUuid = clip.uuid,
  39850. actionsByClip = this._actionsByClip,
  39851. actionsForClip = actionsByClip[ clipUuid ];
  39852. if ( actionsForClip !== undefined ) {
  39853. // note: just calling _removeInactiveAction would mess up the
  39854. // iteration state and also require updating the state we can
  39855. // just throw away
  39856. const actionsToRemove = actionsForClip.knownActions;
  39857. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39858. const action = actionsToRemove[ i ];
  39859. this._deactivateAction( action );
  39860. const cacheIndex = action._cacheIndex,
  39861. lastInactiveAction = actions[ actions.length - 1 ];
  39862. action._cacheIndex = null;
  39863. action._byClipCacheIndex = null;
  39864. lastInactiveAction._cacheIndex = cacheIndex;
  39865. actions[ cacheIndex ] = lastInactiveAction;
  39866. actions.pop();
  39867. this._removeInactiveBindingsForAction( action );
  39868. }
  39869. delete actionsByClip[ clipUuid ];
  39870. }
  39871. }
  39872. /**
  39873. * Deallocates all memory resources for a root object. Before using this
  39874. * method make sure to call {@link AnimationAction#stop} for all related
  39875. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39876. * mixer operates on a single root.
  39877. *
  39878. * @param {Object3D} root - The root object to uncache.
  39879. */
  39880. uncacheRoot( root ) {
  39881. const rootUuid = root.uuid,
  39882. actionsByClip = this._actionsByClip;
  39883. for ( const clipUuid in actionsByClip ) {
  39884. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39885. action = actionByRoot[ rootUuid ];
  39886. if ( action !== undefined ) {
  39887. this._deactivateAction( action );
  39888. this._removeInactiveAction( action );
  39889. }
  39890. }
  39891. const bindingsByRoot = this._bindingsByRootAndName,
  39892. bindingByName = bindingsByRoot[ rootUuid ];
  39893. if ( bindingByName !== undefined ) {
  39894. for ( const trackName in bindingByName ) {
  39895. const binding = bindingByName[ trackName ];
  39896. binding.restoreOriginalState();
  39897. this._removeInactiveBinding( binding );
  39898. }
  39899. }
  39900. }
  39901. /**
  39902. * Deallocates all memory resources for an action. The action is identified by the
  39903. * given clip and an optional root object. Before using this method make
  39904. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39905. *
  39906. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39907. * @param {Object3D} [optionalRoot] - An alternative root object.
  39908. */
  39909. uncacheAction( clip, optionalRoot ) {
  39910. const action = this.existingAction( clip, optionalRoot );
  39911. if ( action !== null ) {
  39912. this._deactivateAction( action );
  39913. this._removeInactiveAction( action );
  39914. }
  39915. }
  39916. }
  39917. /**
  39918. * Represents a 3D render target.
  39919. *
  39920. * @augments RenderTarget
  39921. */
  39922. class RenderTarget3D extends RenderTarget {
  39923. /**
  39924. * Constructs a new 3D render target.
  39925. *
  39926. * @param {number} [width=1] - The width of the render target.
  39927. * @param {number} [height=1] - The height of the render target.
  39928. * @param {number} [depth=1] - The height of the render target.
  39929. * @param {RenderTarget~Options} [options] - The configuration object.
  39930. */
  39931. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39932. super( width, height, options );
  39933. /**
  39934. * This flag can be used for type testing.
  39935. *
  39936. * @type {boolean}
  39937. * @readonly
  39938. * @default true
  39939. */
  39940. this.isRenderTarget3D = true;
  39941. this.depth = depth;
  39942. /**
  39943. * Overwritten with a different texture type.
  39944. *
  39945. * @type {Data3DTexture}
  39946. */
  39947. this.texture = new Data3DTexture( null, width, height, depth );
  39948. this._setTextureOptions( options );
  39949. this.texture.isRenderTargetTexture = true;
  39950. }
  39951. }
  39952. /**
  39953. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39954. *
  39955. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39956. * ```js
  39957. * uniforms: {
  39958. * time: { value: 1.0 },
  39959. * resolution: new Uniform( new Vector2() )
  39960. * };
  39961. * ```
  39962. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39963. * in {@link WebGLRenderer}.
  39964. */
  39965. class Uniform {
  39966. /**
  39967. * Constructs a new uniform.
  39968. *
  39969. * @param {any} value - The uniform value.
  39970. */
  39971. constructor( value ) {
  39972. /**
  39973. * The uniform value.
  39974. *
  39975. * @type {any}
  39976. */
  39977. this.value = value;
  39978. }
  39979. /**
  39980. * Returns a new uniform with copied values from this instance.
  39981. * If the value has a `clone()` method, the value is cloned as well.
  39982. *
  39983. * @return {Uniform} A clone of this instance.
  39984. */
  39985. clone() {
  39986. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39987. }
  39988. }
  39989. let _id = 0;
  39990. /**
  39991. * A class for managing multiple uniforms in a single group. The renderer will process
  39992. * such a definition as a single UBO.
  39993. *
  39994. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39995. * in {@link WebGLRenderer}.
  39996. *
  39997. * @augments EventDispatcher
  39998. */
  39999. class UniformsGroup extends EventDispatcher {
  40000. /**
  40001. * Constructs a new uniforms group.
  40002. */
  40003. constructor() {
  40004. super();
  40005. /**
  40006. * This flag can be used for type testing.
  40007. *
  40008. * @type {boolean}
  40009. * @readonly
  40010. * @default true
  40011. */
  40012. this.isUniformsGroup = true;
  40013. /**
  40014. * The ID of the 3D object.
  40015. *
  40016. * @name UniformsGroup#id
  40017. * @type {number}
  40018. * @readonly
  40019. */
  40020. Object.defineProperty( this, 'id', { value: _id ++ } );
  40021. /**
  40022. * The name of the uniforms group.
  40023. *
  40024. * @type {string}
  40025. */
  40026. this.name = '';
  40027. /**
  40028. * The buffer usage.
  40029. *
  40030. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  40031. * @default StaticDrawUsage
  40032. */
  40033. this.usage = StaticDrawUsage;
  40034. /**
  40035. * An array holding the uniforms.
  40036. *
  40037. * @type {Array<Uniform>}
  40038. */
  40039. this.uniforms = [];
  40040. }
  40041. /**
  40042. * Adds the given uniform to this uniforms group.
  40043. *
  40044. * @param {Uniform} uniform - The uniform to add.
  40045. * @return {UniformsGroup} A reference to this uniforms group.
  40046. */
  40047. add( uniform ) {
  40048. this.uniforms.push( uniform );
  40049. return this;
  40050. }
  40051. /**
  40052. * Removes the given uniform from this uniforms group.
  40053. *
  40054. * @param {Uniform} uniform - The uniform to remove.
  40055. * @return {UniformsGroup} A reference to this uniforms group.
  40056. */
  40057. remove( uniform ) {
  40058. const index = this.uniforms.indexOf( uniform );
  40059. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  40060. return this;
  40061. }
  40062. /**
  40063. * Sets the name of this uniforms group.
  40064. *
  40065. * @param {string} name - The name to set.
  40066. * @return {UniformsGroup} A reference to this uniforms group.
  40067. */
  40068. setName( name ) {
  40069. this.name = name;
  40070. return this;
  40071. }
  40072. /**
  40073. * Sets the usage of this uniforms group.
  40074. *
  40075. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  40076. * @return {UniformsGroup} A reference to this uniforms group.
  40077. */
  40078. setUsage( value ) {
  40079. this.usage = value;
  40080. return this;
  40081. }
  40082. /**
  40083. * Frees the GPU-related resources allocated by this instance. Call this
  40084. * method whenever this instance is no longer used in your app.
  40085. *
  40086. * @fires Texture#dispose
  40087. */
  40088. dispose() {
  40089. this.dispatchEvent( { type: 'dispose' } );
  40090. }
  40091. /**
  40092. * Copies the values of the given uniforms group to this instance.
  40093. *
  40094. * @param {UniformsGroup} source - The uniforms group to copy.
  40095. * @return {UniformsGroup} A reference to this uniforms group.
  40096. */
  40097. copy( source ) {
  40098. this.name = source.name;
  40099. this.usage = source.usage;
  40100. const uniformsSource = source.uniforms;
  40101. this.uniforms.length = 0;
  40102. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  40103. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  40104. for ( let j = 0; j < uniforms.length; j ++ ) {
  40105. this.uniforms.push( uniforms[ j ].clone() );
  40106. }
  40107. }
  40108. return this;
  40109. }
  40110. /**
  40111. * Returns a new uniforms group with copied values from this instance.
  40112. *
  40113. * @return {UniformsGroup} A clone of this instance.
  40114. */
  40115. clone() {
  40116. return new this.constructor().copy( this );
  40117. }
  40118. }
  40119. /**
  40120. * An instanced version of an interleaved buffer.
  40121. *
  40122. * @augments InterleavedBuffer
  40123. */
  40124. class InstancedInterleavedBuffer extends InterleavedBuffer {
  40125. /**
  40126. * Constructs a new instanced interleaved buffer.
  40127. *
  40128. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  40129. * @param {number} stride - The number of typed-array elements per vertex.
  40130. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  40131. */
  40132. constructor( array, stride, meshPerAttribute = 1 ) {
  40133. super( array, stride );
  40134. /**
  40135. * This flag can be used for type testing.
  40136. *
  40137. * @type {boolean}
  40138. * @readonly
  40139. * @default true
  40140. */
  40141. this.isInstancedInterleavedBuffer = true;
  40142. /**
  40143. * Defines how often a value of this buffer attribute should be repeated,
  40144. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  40145. *
  40146. * @type {number}
  40147. * @default 1
  40148. */
  40149. this.meshPerAttribute = meshPerAttribute;
  40150. }
  40151. copy( source ) {
  40152. super.copy( source );
  40153. this.meshPerAttribute = source.meshPerAttribute;
  40154. return this;
  40155. }
  40156. clone( data ) {
  40157. const ib = super.clone( data );
  40158. ib.meshPerAttribute = this.meshPerAttribute;
  40159. return ib;
  40160. }
  40161. toJSON( data ) {
  40162. const json = super.toJSON( data );
  40163. json.isInstancedInterleavedBuffer = true;
  40164. json.meshPerAttribute = this.meshPerAttribute;
  40165. return json;
  40166. }
  40167. }
  40168. /**
  40169. * An alternative version of a buffer attribute with more control over the VBO.
  40170. *
  40171. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  40172. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  40173. *
  40174. * The most common use case for this class is when some kind of GPGPU calculation interferes
  40175. * or even produces the VBOs in question.
  40176. *
  40177. * Notice that this class can only be used with {@link WebGLRenderer}.
  40178. */
  40179. class GLBufferAttribute {
  40180. /**
  40181. * Constructs a new GL buffer attribute.
  40182. *
  40183. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  40184. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40185. * @param {number} itemSize - The item size.
  40186. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40187. * @param {number} count - The expected number of vertices in VBO.
  40188. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  40189. */
  40190. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  40191. /**
  40192. * This flag can be used for type testing.
  40193. *
  40194. * @type {boolean}
  40195. * @readonly
  40196. * @default true
  40197. */
  40198. this.isGLBufferAttribute = true;
  40199. /**
  40200. * The name of the buffer attribute.
  40201. *
  40202. * @type {string}
  40203. */
  40204. this.name = '';
  40205. /**
  40206. * The native WebGL buffer.
  40207. *
  40208. * @type {WebGLBuffer}
  40209. */
  40210. this.buffer = buffer;
  40211. /**
  40212. * The native data type.
  40213. *
  40214. * @type {number}
  40215. */
  40216. this.type = type;
  40217. /**
  40218. * The item size, see {@link BufferAttribute#itemSize}.
  40219. *
  40220. * @type {number}
  40221. */
  40222. this.itemSize = itemSize;
  40223. /**
  40224. * The corresponding size (in bytes) for the given `type` parameter.
  40225. *
  40226. * @type {number}
  40227. */
  40228. this.elementSize = elementSize;
  40229. /**
  40230. * The expected number of vertices in VBO.
  40231. *
  40232. * @type {number}
  40233. */
  40234. this.count = count;
  40235. /**
  40236. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  40237. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  40238. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  40239. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  40240. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  40241. *
  40242. * @type {boolean}
  40243. */
  40244. this.normalized = normalized;
  40245. /**
  40246. * A version number, incremented every time the `needsUpdate` is set to `true`.
  40247. *
  40248. * @type {number}
  40249. */
  40250. this.version = 0;
  40251. }
  40252. /**
  40253. * Flag to indicate that this attribute has changed and should be re-sent to
  40254. * the GPU. Set this to `true` when you modify the value of the array.
  40255. *
  40256. * @type {number}
  40257. * @default false
  40258. * @param {boolean} value
  40259. */
  40260. set needsUpdate( value ) {
  40261. if ( value === true ) this.version ++;
  40262. }
  40263. /**
  40264. * Sets the given native WebGL buffer.
  40265. *
  40266. * @param {WebGLBuffer} buffer - The buffer to set.
  40267. * @return {BufferAttribute} A reference to this instance.
  40268. */
  40269. setBuffer( buffer ) {
  40270. this.buffer = buffer;
  40271. return this;
  40272. }
  40273. /**
  40274. * Sets the given native data type and element size.
  40275. *
  40276. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40277. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40278. * @return {BufferAttribute} A reference to this instance.
  40279. */
  40280. setType( type, elementSize ) {
  40281. this.type = type;
  40282. this.elementSize = elementSize;
  40283. return this;
  40284. }
  40285. /**
  40286. * Sets the item size.
  40287. *
  40288. * @param {number} itemSize - The item size.
  40289. * @return {BufferAttribute} A reference to this instance.
  40290. */
  40291. setItemSize( itemSize ) {
  40292. this.itemSize = itemSize;
  40293. return this;
  40294. }
  40295. /**
  40296. * Sets the count (the expected number of vertices in VBO).
  40297. *
  40298. * @param {number} count - The count.
  40299. * @return {BufferAttribute} A reference to this instance.
  40300. */
  40301. setCount( count ) {
  40302. this.count = count;
  40303. return this;
  40304. }
  40305. }
  40306. const _matrix = /*@__PURE__*/ new Matrix4();
  40307. /**
  40308. * This class is designed to assist with raycasting. Raycasting is used for
  40309. * mouse picking (working out what objects in the 3d space the mouse is over)
  40310. * amongst other things.
  40311. */
  40312. class Raycaster {
  40313. /**
  40314. * Constructs a new raycaster.
  40315. *
  40316. * @param {Vector3} origin - The origin vector where the ray casts from.
  40317. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40318. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40319. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40320. */
  40321. constructor( origin, direction, near = 0, far = Infinity ) {
  40322. /**
  40323. * The ray used for raycasting.
  40324. *
  40325. * @type {Ray}
  40326. */
  40327. this.ray = new Ray( origin, direction );
  40328. /**
  40329. * All results returned are further away than near. Near can't be negative.
  40330. *
  40331. * @type {number}
  40332. * @default 0
  40333. */
  40334. this.near = near;
  40335. /**
  40336. * All results returned are closer than far. Far can't be lower than near.
  40337. *
  40338. * @type {number}
  40339. * @default Infinity
  40340. */
  40341. this.far = far;
  40342. /**
  40343. * The camera to use when raycasting against view-dependent objects such as
  40344. * billboarded objects like sprites. This field can be set manually or
  40345. * is set when calling `setFromCamera()`.
  40346. *
  40347. * @type {?Camera}
  40348. * @default null
  40349. */
  40350. this.camera = null;
  40351. /**
  40352. * Allows to selectively ignore 3D objects when performing intersection tests.
  40353. * The following code example ensures that only 3D objects on layer `1` will be
  40354. * honored by raycaster.
  40355. * ```js
  40356. * raycaster.layers.set( 1 );
  40357. * object.layers.enable( 1 );
  40358. * ```
  40359. *
  40360. * @type {Layers}
  40361. */
  40362. this.layers = new Layers();
  40363. /**
  40364. * A parameter object that configures the raycasting. It has the structure:
  40365. *
  40366. * ```
  40367. * {
  40368. * Mesh: {},
  40369. * Line: { threshold: 1 },
  40370. * LOD: {},
  40371. * Points: { threshold: 1 },
  40372. * Sprite: {}
  40373. * }
  40374. * ```
  40375. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40376. *
  40377. * @type {Object}
  40378. */
  40379. this.params = {
  40380. Mesh: {},
  40381. Line: { threshold: 1 },
  40382. LOD: {},
  40383. Points: { threshold: 1 },
  40384. Sprite: {}
  40385. };
  40386. }
  40387. /**
  40388. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40389. *
  40390. * @param {Vector3} origin - The origin vector where the ray casts from.
  40391. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40392. */
  40393. set( origin, direction ) {
  40394. // direction is assumed to be normalized (for accurate distance calculations)
  40395. this.ray.set( origin, direction );
  40396. }
  40397. /**
  40398. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40399. *
  40400. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40401. * X and Y components should be between `-1` and `1`.
  40402. * @param {Camera} camera - The camera from which the ray should originate.
  40403. */
  40404. setFromCamera( coords, camera ) {
  40405. if ( camera.isPerspectiveCamera ) {
  40406. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40407. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40408. this.camera = camera;
  40409. } else if ( camera.isOrthographicCamera ) {
  40410. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  40411. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40412. this.camera = camera;
  40413. } else {
  40414. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40415. }
  40416. }
  40417. /**
  40418. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40419. *
  40420. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40421. * @return {Raycaster} A reference to this raycaster.
  40422. */
  40423. setFromXRController( controller ) {
  40424. _matrix.identity().extractRotation( controller.matrixWorld );
  40425. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40426. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40427. return this;
  40428. }
  40429. /**
  40430. * The intersection point of a raycaster intersection test.
  40431. * @typedef {Object} Raycaster~Intersection
  40432. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40433. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40434. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40435. * @property {Vector3} point - The intersection point, in world coordinates.
  40436. * @property {Object} face - The face that has been intersected.
  40437. * @property {number} faceIndex - The face index.
  40438. * @property {Object3D} object - The 3D object that has been intersected.
  40439. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40440. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40441. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40442. * @property {number} instanceId - The index number of the instance where the ray
  40443. * intersects the {@link InstancedMesh}.
  40444. */
  40445. /**
  40446. * Checks all intersection between the ray and the object with or without the
  40447. * descendants. Intersections are returned sorted by distance, closest first.
  40448. *
  40449. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40450. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40451. * differently to ray casting than lines or points.
  40452. *
  40453. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40454. * to be detected; intersections of the ray passing through the back of a face will not
  40455. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40456. * to `THREE.DoubleSide`.
  40457. *
  40458. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40459. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40460. * Otherwise it only checks intersection with the object.
  40461. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40462. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40463. */
  40464. intersectObject( object, recursive = true, intersects = [] ) {
  40465. intersect( object, this, intersects, recursive );
  40466. intersects.sort( ascSort );
  40467. return intersects;
  40468. }
  40469. /**
  40470. * Checks all intersection between the ray and the objects with or without
  40471. * the descendants. Intersections are returned sorted by distance, closest first.
  40472. *
  40473. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40474. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40475. * Otherwise it only checks intersection with the object.
  40476. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40477. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40478. */
  40479. intersectObjects( objects, recursive = true, intersects = [] ) {
  40480. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40481. intersect( objects[ i ], this, intersects, recursive );
  40482. }
  40483. intersects.sort( ascSort );
  40484. return intersects;
  40485. }
  40486. }
  40487. function ascSort( a, b ) {
  40488. return a.distance - b.distance;
  40489. }
  40490. function intersect( object, raycaster, intersects, recursive ) {
  40491. let propagate = true;
  40492. if ( object.layers.test( raycaster.layers ) ) {
  40493. const result = object.raycast( raycaster, intersects );
  40494. if ( result === false ) propagate = false;
  40495. }
  40496. if ( propagate === true && recursive === true ) {
  40497. const children = object.children;
  40498. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40499. intersect( children[ i ], raycaster, intersects, true );
  40500. }
  40501. }
  40502. }
  40503. /**
  40504. * Class for keeping track of time.
  40505. *
  40506. * @deprecated since r183.
  40507. */
  40508. class Clock {
  40509. /**
  40510. * Constructs a new clock.
  40511. *
  40512. * @deprecated since 183.
  40513. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  40514. * `getDelta()` is called for the first time.
  40515. */
  40516. constructor( autoStart = true ) {
  40517. /**
  40518. * If set to `true`, the clock starts automatically when `getDelta()` is called
  40519. * for the first time.
  40520. *
  40521. * @type {boolean}
  40522. * @default true
  40523. */
  40524. this.autoStart = autoStart;
  40525. /**
  40526. * Holds the time at which the clock's `start()` method was last called.
  40527. *
  40528. * @type {number}
  40529. * @default 0
  40530. */
  40531. this.startTime = 0;
  40532. /**
  40533. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  40534. * `getDelta()` methods were last called.
  40535. *
  40536. * @type {number}
  40537. * @default 0
  40538. */
  40539. this.oldTime = 0;
  40540. /**
  40541. * Keeps track of the total time that the clock has been running.
  40542. *
  40543. * @type {number}
  40544. * @default 0
  40545. */
  40546. this.elapsedTime = 0;
  40547. /**
  40548. * Whether the clock is running or not.
  40549. *
  40550. * @type {boolean}
  40551. * @default true
  40552. */
  40553. this.running = false;
  40554. warn( 'Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183
  40555. }
  40556. /**
  40557. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  40558. * called by the class.
  40559. */
  40560. start() {
  40561. this.startTime = performance.now();
  40562. this.oldTime = this.startTime;
  40563. this.elapsedTime = 0;
  40564. this.running = true;
  40565. }
  40566. /**
  40567. * Stops the clock.
  40568. */
  40569. stop() {
  40570. this.getElapsedTime();
  40571. this.running = false;
  40572. this.autoStart = false;
  40573. }
  40574. /**
  40575. * Returns the elapsed time in seconds.
  40576. *
  40577. * @return {number} The elapsed time.
  40578. */
  40579. getElapsedTime() {
  40580. this.getDelta();
  40581. return this.elapsedTime;
  40582. }
  40583. /**
  40584. * Returns the delta time in seconds.
  40585. *
  40586. * @return {number} The delta time.
  40587. */
  40588. getDelta() {
  40589. let diff = 0;
  40590. if ( this.autoStart && ! this.running ) {
  40591. this.start();
  40592. return 0;
  40593. }
  40594. if ( this.running ) {
  40595. const newTime = performance.now();
  40596. diff = ( newTime - this.oldTime ) / 1000;
  40597. this.oldTime = newTime;
  40598. this.elapsedTime += diff;
  40599. }
  40600. return diff;
  40601. }
  40602. }
  40603. /**
  40604. * This class can be used to represent points in 3D space as
  40605. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40606. */
  40607. class Spherical {
  40608. /**
  40609. * Constructs a new spherical.
  40610. *
  40611. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40612. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40613. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40614. */
  40615. constructor( radius = 1, phi = 0, theta = 0 ) {
  40616. /**
  40617. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40618. *
  40619. * @type {number}
  40620. * @default 1
  40621. */
  40622. this.radius = radius;
  40623. /**
  40624. * The polar angle in radians from the y (up) axis.
  40625. *
  40626. * @type {number}
  40627. * @default 0
  40628. */
  40629. this.phi = phi;
  40630. /**
  40631. * The equator/azimuthal angle in radians around the y (up) axis.
  40632. *
  40633. * @type {number}
  40634. * @default 0
  40635. */
  40636. this.theta = theta;
  40637. }
  40638. /**
  40639. * Sets the spherical components by copying the given values.
  40640. *
  40641. * @param {number} radius - The radius.
  40642. * @param {number} phi - The polar angle.
  40643. * @param {number} theta - The azimuthal angle.
  40644. * @return {Spherical} A reference to this spherical.
  40645. */
  40646. set( radius, phi, theta ) {
  40647. this.radius = radius;
  40648. this.phi = phi;
  40649. this.theta = theta;
  40650. return this;
  40651. }
  40652. /**
  40653. * Copies the values of the given spherical to this instance.
  40654. *
  40655. * @param {Spherical} other - The spherical to copy.
  40656. * @return {Spherical} A reference to this spherical.
  40657. */
  40658. copy( other ) {
  40659. this.radius = other.radius;
  40660. this.phi = other.phi;
  40661. this.theta = other.theta;
  40662. return this;
  40663. }
  40664. /**
  40665. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40666. * `0.000001`.
  40667. *
  40668. * @return {Spherical} A reference to this spherical.
  40669. */
  40670. makeSafe() {
  40671. const EPS = 0.000001;
  40672. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40673. return this;
  40674. }
  40675. /**
  40676. * Sets the spherical components from the given vector which is assumed to hold
  40677. * Cartesian coordinates.
  40678. *
  40679. * @param {Vector3} v - The vector to set.
  40680. * @return {Spherical} A reference to this spherical.
  40681. */
  40682. setFromVector3( v ) {
  40683. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40684. }
  40685. /**
  40686. * Sets the spherical components from the given Cartesian coordinates.
  40687. *
  40688. * @param {number} x - The x value.
  40689. * @param {number} y - The y value.
  40690. * @param {number} z - The z value.
  40691. * @return {Spherical} A reference to this spherical.
  40692. */
  40693. setFromCartesianCoords( x, y, z ) {
  40694. this.radius = Math.sqrt( x * x + y * y + z * z );
  40695. if ( this.radius === 0 ) {
  40696. this.theta = 0;
  40697. this.phi = 0;
  40698. } else {
  40699. this.theta = Math.atan2( x, z );
  40700. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40701. }
  40702. return this;
  40703. }
  40704. /**
  40705. * Returns a new spherical with copied values from this instance.
  40706. *
  40707. * @return {Spherical} A clone of this instance.
  40708. */
  40709. clone() {
  40710. return new this.constructor().copy( this );
  40711. }
  40712. }
  40713. /**
  40714. * This class can be used to represent points in 3D space as
  40715. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40716. */
  40717. class Cylindrical {
  40718. /**
  40719. * Constructs a new cylindrical.
  40720. *
  40721. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40722. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40723. * @param {number} [y=0] - The height above the x-z plane.
  40724. */
  40725. constructor( radius = 1, theta = 0, y = 0 ) {
  40726. /**
  40727. * The distance from the origin to a point in the x-z plane.
  40728. *
  40729. * @type {number}
  40730. * @default 1
  40731. */
  40732. this.radius = radius;
  40733. /**
  40734. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40735. *
  40736. * @type {number}
  40737. * @default 0
  40738. */
  40739. this.theta = theta;
  40740. /**
  40741. * The height above the x-z plane.
  40742. *
  40743. * @type {number}
  40744. * @default 0
  40745. */
  40746. this.y = y;
  40747. }
  40748. /**
  40749. * Sets the cylindrical components by copying the given values.
  40750. *
  40751. * @param {number} radius - The radius.
  40752. * @param {number} theta - The theta angle.
  40753. * @param {number} y - The height value.
  40754. * @return {Cylindrical} A reference to this cylindrical.
  40755. */
  40756. set( radius, theta, y ) {
  40757. this.radius = radius;
  40758. this.theta = theta;
  40759. this.y = y;
  40760. return this;
  40761. }
  40762. /**
  40763. * Copies the values of the given cylindrical to this instance.
  40764. *
  40765. * @param {Cylindrical} other - The cylindrical to copy.
  40766. * @return {Cylindrical} A reference to this cylindrical.
  40767. */
  40768. copy( other ) {
  40769. this.radius = other.radius;
  40770. this.theta = other.theta;
  40771. this.y = other.y;
  40772. return this;
  40773. }
  40774. /**
  40775. * Sets the cylindrical components from the given vector which is assumed to hold
  40776. * Cartesian coordinates.
  40777. *
  40778. * @param {Vector3} v - The vector to set.
  40779. * @return {Cylindrical} A reference to this cylindrical.
  40780. */
  40781. setFromVector3( v ) {
  40782. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40783. }
  40784. /**
  40785. * Sets the cylindrical components from the given Cartesian coordinates.
  40786. *
  40787. * @param {number} x - The x value.
  40788. * @param {number} y - The x value.
  40789. * @param {number} z - The x value.
  40790. * @return {Cylindrical} A reference to this cylindrical.
  40791. */
  40792. setFromCartesianCoords( x, y, z ) {
  40793. this.radius = Math.sqrt( x * x + z * z );
  40794. this.theta = Math.atan2( x, z );
  40795. this.y = y;
  40796. return this;
  40797. }
  40798. /**
  40799. * Returns a new cylindrical with copied values from this instance.
  40800. *
  40801. * @return {Cylindrical} A clone of this instance.
  40802. */
  40803. clone() {
  40804. return new this.constructor().copy( this );
  40805. }
  40806. }
  40807. /**
  40808. * Represents a 2x2 matrix.
  40809. *
  40810. * A Note on Row-Major and Column-Major Ordering:
  40811. *
  40812. * The constructor and {@link Matrix2#set} method take arguments in
  40813. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40814. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40815. * This means that calling:
  40816. * ```js
  40817. * const m = new THREE.Matrix2();
  40818. * m.set( 11, 12,
  40819. * 21, 22 );
  40820. * ```
  40821. * will result in the elements array containing:
  40822. * ```js
  40823. * m.elements = [ 11, 21,
  40824. * 12, 22 ];
  40825. * ```
  40826. * and internally all calculations are performed using column-major ordering.
  40827. * However, as the actual ordering makes no difference mathematically and
  40828. * most people are used to thinking about matrices in row-major order, the
  40829. * three.js documentation shows matrices in row-major order. Just bear in
  40830. * mind that if you are reading the source code, you'll have to take the
  40831. * transpose of any matrices outlined here to make sense of the calculations.
  40832. */
  40833. class Matrix2 {
  40834. static {
  40835. /**
  40836. * This flag can be used for type testing.
  40837. *
  40838. * @type {boolean}
  40839. * @readonly
  40840. * @default true
  40841. */
  40842. Matrix2.prototype.isMatrix2 = true;
  40843. }
  40844. /**
  40845. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40846. * in row-major order. If no arguments are provided, the constructor
  40847. * initializes the matrix as an identity matrix.
  40848. *
  40849. * @param {number} [n11] - 1-1 matrix element.
  40850. * @param {number} [n12] - 1-2 matrix element.
  40851. * @param {number} [n21] - 2-1 matrix element.
  40852. * @param {number} [n22] - 2-2 matrix element.
  40853. */
  40854. constructor( n11, n12, n21, n22 ) {
  40855. /**
  40856. * A column-major list of matrix values.
  40857. *
  40858. * @type {Array<number>}
  40859. */
  40860. this.elements = [
  40861. 1, 0,
  40862. 0, 1,
  40863. ];
  40864. if ( n11 !== undefined ) {
  40865. this.set( n11, n12, n21, n22 );
  40866. }
  40867. }
  40868. /**
  40869. * Sets this matrix to the 2x2 identity matrix.
  40870. *
  40871. * @return {Matrix2} A reference to this matrix.
  40872. */
  40873. identity() {
  40874. this.set(
  40875. 1, 0,
  40876. 0, 1,
  40877. );
  40878. return this;
  40879. }
  40880. /**
  40881. * Sets the elements of the matrix from the given array.
  40882. *
  40883. * @param {Array<number>} array - The matrix elements in column-major order.
  40884. * @param {number} [offset=0] - Index of the first element in the array.
  40885. * @return {Matrix2} A reference to this matrix.
  40886. */
  40887. fromArray( array, offset = 0 ) {
  40888. for ( let i = 0; i < 4; i ++ ) {
  40889. this.elements[ i ] = array[ i + offset ];
  40890. }
  40891. return this;
  40892. }
  40893. /**
  40894. * Sets the elements of the matrix.The arguments are supposed to be
  40895. * in row-major order.
  40896. *
  40897. * @param {number} n11 - 1-1 matrix element.
  40898. * @param {number} n12 - 1-2 matrix element.
  40899. * @param {number} n21 - 2-1 matrix element.
  40900. * @param {number} n22 - 2-2 matrix element.
  40901. * @return {Matrix2} A reference to this matrix.
  40902. */
  40903. set( n11, n12, n21, n22 ) {
  40904. const te = this.elements;
  40905. te[ 0 ] = n11; te[ 2 ] = n12;
  40906. te[ 1 ] = n21; te[ 3 ] = n22;
  40907. return this;
  40908. }
  40909. }
  40910. const _vector$4 = /*@__PURE__*/ new Vector2();
  40911. /**
  40912. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40913. */
  40914. class Box2 {
  40915. /**
  40916. * Constructs a new bounding box.
  40917. *
  40918. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40919. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40920. */
  40921. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40922. /**
  40923. * This flag can be used for type testing.
  40924. *
  40925. * @type {boolean}
  40926. * @readonly
  40927. * @default true
  40928. */
  40929. this.isBox2 = true;
  40930. /**
  40931. * The lower boundary of the box.
  40932. *
  40933. * @type {Vector2}
  40934. */
  40935. this.min = min;
  40936. /**
  40937. * The upper boundary of the box.
  40938. *
  40939. * @type {Vector2}
  40940. */
  40941. this.max = max;
  40942. }
  40943. /**
  40944. * Sets the lower and upper boundaries of this box.
  40945. * Please note that this method only copies the values from the given objects.
  40946. *
  40947. * @param {Vector2} min - The lower boundary of the box.
  40948. * @param {Vector2} max - The upper boundary of the box.
  40949. * @return {Box2} A reference to this bounding box.
  40950. */
  40951. set( min, max ) {
  40952. this.min.copy( min );
  40953. this.max.copy( max );
  40954. return this;
  40955. }
  40956. /**
  40957. * Sets the upper and lower bounds of this box so it encloses the position data
  40958. * in the given array.
  40959. *
  40960. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40961. * @return {Box2} A reference to this bounding box.
  40962. */
  40963. setFromPoints( points ) {
  40964. this.makeEmpty();
  40965. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40966. this.expandByPoint( points[ i ] );
  40967. }
  40968. return this;
  40969. }
  40970. /**
  40971. * Centers this box on the given center vector and sets this box's width, height and
  40972. * depth to the given size values.
  40973. *
  40974. * @param {Vector2} center - The center of the box.
  40975. * @param {Vector2} size - The x and y dimensions of the box.
  40976. * @return {Box2} A reference to this bounding box.
  40977. */
  40978. setFromCenterAndSize( center, size ) {
  40979. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40980. this.min.copy( center ).sub( halfSize );
  40981. this.max.copy( center ).add( halfSize );
  40982. return this;
  40983. }
  40984. /**
  40985. * Returns a new box with copied values from this instance.
  40986. *
  40987. * @return {Box2} A clone of this instance.
  40988. */
  40989. clone() {
  40990. return new this.constructor().copy( this );
  40991. }
  40992. /**
  40993. * Copies the values of the given box to this instance.
  40994. *
  40995. * @param {Box2} box - The box to copy.
  40996. * @return {Box2} A reference to this bounding box.
  40997. */
  40998. copy( box ) {
  40999. this.min.copy( box.min );
  41000. this.max.copy( box.max );
  41001. return this;
  41002. }
  41003. /**
  41004. * Makes this box empty which means in encloses a zero space in 2D.
  41005. *
  41006. * @return {Box2} A reference to this bounding box.
  41007. */
  41008. makeEmpty() {
  41009. this.min.x = this.min.y = + Infinity;
  41010. this.max.x = this.max.y = - Infinity;
  41011. return this;
  41012. }
  41013. /**
  41014. * Returns true if this box includes zero points within its bounds.
  41015. * Note that a box with equal lower and upper bounds still includes one
  41016. * point, the one both bounds share.
  41017. *
  41018. * @return {boolean} Whether this box is empty or not.
  41019. */
  41020. isEmpty() {
  41021. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  41022. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  41023. }
  41024. /**
  41025. * Returns the center point of this box.
  41026. *
  41027. * @param {Vector2} target - The target vector that is used to store the method's result.
  41028. * @return {Vector2} The center point.
  41029. */
  41030. getCenter( target ) {
  41031. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  41032. }
  41033. /**
  41034. * Returns the dimensions of this box.
  41035. *
  41036. * @param {Vector2} target - The target vector that is used to store the method's result.
  41037. * @return {Vector2} The size.
  41038. */
  41039. getSize( target ) {
  41040. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  41041. }
  41042. /**
  41043. * Expands the boundaries of this box to include the given point.
  41044. *
  41045. * @param {Vector2} point - The point that should be included by the bounding box.
  41046. * @return {Box2} A reference to this bounding box.
  41047. */
  41048. expandByPoint( point ) {
  41049. this.min.min( point );
  41050. this.max.max( point );
  41051. return this;
  41052. }
  41053. /**
  41054. * Expands this box equilaterally by the given vector. The width of this
  41055. * box will be expanded by the x component of the vector in both
  41056. * directions. The height of this box will be expanded by the y component of
  41057. * the vector in both directions.
  41058. *
  41059. * @param {Vector2} vector - The vector that should expand the bounding box.
  41060. * @return {Box2} A reference to this bounding box.
  41061. */
  41062. expandByVector( vector ) {
  41063. this.min.sub( vector );
  41064. this.max.add( vector );
  41065. return this;
  41066. }
  41067. /**
  41068. * Expands each dimension of the box by the given scalar. If negative, the
  41069. * dimensions of the box will be contracted.
  41070. *
  41071. * @param {number} scalar - The scalar value that should expand the bounding box.
  41072. * @return {Box2} A reference to this bounding box.
  41073. */
  41074. expandByScalar( scalar ) {
  41075. this.min.addScalar( - scalar );
  41076. this.max.addScalar( scalar );
  41077. return this;
  41078. }
  41079. /**
  41080. * Returns `true` if the given point lies within or on the boundaries of this box.
  41081. *
  41082. * @param {Vector2} point - The point to test.
  41083. * @return {boolean} Whether the bounding box contains the given point or not.
  41084. */
  41085. containsPoint( point ) {
  41086. return point.x >= this.min.x && point.x <= this.max.x &&
  41087. point.y >= this.min.y && point.y <= this.max.y;
  41088. }
  41089. /**
  41090. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  41091. * If this box and the given one are identical, this function also returns `true`.
  41092. *
  41093. * @param {Box2} box - The bounding box to test.
  41094. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  41095. */
  41096. containsBox( box ) {
  41097. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  41098. this.min.y <= box.min.y && box.max.y <= this.max.y;
  41099. }
  41100. /**
  41101. * Returns a point as a proportion of this box's width and height.
  41102. *
  41103. * @param {Vector2} point - A point in 2D space.
  41104. * @param {Vector2} target - The target vector that is used to store the method's result.
  41105. * @return {Vector2} A point as a proportion of this box's width and height.
  41106. */
  41107. getParameter( point, target ) {
  41108. // This can potentially have a divide by zero if the box
  41109. // has a size dimension of 0.
  41110. return target.set(
  41111. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  41112. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  41113. );
  41114. }
  41115. /**
  41116. * Returns `true` if the given bounding box intersects with this bounding box.
  41117. *
  41118. * @param {Box2} box - The bounding box to test.
  41119. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  41120. */
  41121. intersectsBox( box ) {
  41122. // using 4 splitting planes to rule out intersections
  41123. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  41124. box.max.y >= this.min.y && box.min.y <= this.max.y;
  41125. }
  41126. /**
  41127. * Clamps the given point within the bounds of this box.
  41128. *
  41129. * @param {Vector2} point - The point to clamp.
  41130. * @param {Vector2} target - The target vector that is used to store the method's result.
  41131. * @return {Vector2} The clamped point.
  41132. */
  41133. clampPoint( point, target ) {
  41134. return target.copy( point ).clamp( this.min, this.max );
  41135. }
  41136. /**
  41137. * Returns the euclidean distance from any edge of this box to the specified point. If
  41138. * the given point lies inside of this box, the distance will be `0`.
  41139. *
  41140. * @param {Vector2} point - The point to compute the distance to.
  41141. * @return {number} The euclidean distance.
  41142. */
  41143. distanceToPoint( point ) {
  41144. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  41145. }
  41146. /**
  41147. * Computes the intersection of this bounding box and the given one, setting the upper
  41148. * bound of this box to the lesser of the two boxes' upper bounds and the
  41149. * lower bound of this box to the greater of the two boxes' lower bounds. If
  41150. * there's no overlap, makes this box empty.
  41151. *
  41152. * @param {Box2} box - The bounding box to intersect with.
  41153. * @return {Box2} A reference to this bounding box.
  41154. */
  41155. intersect( box ) {
  41156. this.min.max( box.min );
  41157. this.max.min( box.max );
  41158. if ( this.isEmpty() ) this.makeEmpty();
  41159. return this;
  41160. }
  41161. /**
  41162. * Computes the union of this box and another and the given one, setting the upper
  41163. * bound of this box to the greater of the two boxes' upper bounds and the
  41164. * lower bound of this box to the lesser of the two boxes' lower bounds.
  41165. *
  41166. * @param {Box2} box - The bounding box that will be unioned with this instance.
  41167. * @return {Box2} A reference to this bounding box.
  41168. */
  41169. union( box ) {
  41170. this.min.min( box.min );
  41171. this.max.max( box.max );
  41172. return this;
  41173. }
  41174. /**
  41175. * Adds the given offset to both the upper and lower bounds of this bounding box,
  41176. * effectively moving it in 2D space.
  41177. *
  41178. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  41179. * @return {Box2} A reference to this bounding box.
  41180. */
  41181. translate( offset ) {
  41182. this.min.add( offset );
  41183. this.max.add( offset );
  41184. return this;
  41185. }
  41186. /**
  41187. * Returns `true` if this bounding box is equal with the given one.
  41188. *
  41189. * @param {Box2} box - The box to test for equality.
  41190. * @return {boolean} Whether this bounding box is equal with the given one.
  41191. */
  41192. equals( box ) {
  41193. return box.min.equals( this.min ) && box.max.equals( this.max );
  41194. }
  41195. }
  41196. const _startP = /*@__PURE__*/ new Vector3();
  41197. const _startEnd = /*@__PURE__*/ new Vector3();
  41198. const _d1 = /*@__PURE__*/ new Vector3();
  41199. const _d2 = /*@__PURE__*/ new Vector3();
  41200. const _r = /*@__PURE__*/ new Vector3();
  41201. const _c1 = /*@__PURE__*/ new Vector3();
  41202. const _c2 = /*@__PURE__*/ new Vector3();
  41203. /**
  41204. * An analytical line segment in 3D space represented by a start and end point.
  41205. */
  41206. class Line3 {
  41207. /**
  41208. * Constructs a new line segment.
  41209. *
  41210. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  41211. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  41212. */
  41213. constructor( start = new Vector3(), end = new Vector3() ) {
  41214. /**
  41215. * Start of the line segment.
  41216. *
  41217. * @type {Vector3}
  41218. */
  41219. this.start = start;
  41220. /**
  41221. * End of the line segment.
  41222. *
  41223. * @type {Vector3}
  41224. */
  41225. this.end = end;
  41226. }
  41227. /**
  41228. * Sets the start and end values by copying the given vectors.
  41229. *
  41230. * @param {Vector3} start - The start point.
  41231. * @param {Vector3} end - The end point.
  41232. * @return {Line3} A reference to this line segment.
  41233. */
  41234. set( start, end ) {
  41235. this.start.copy( start );
  41236. this.end.copy( end );
  41237. return this;
  41238. }
  41239. /**
  41240. * Copies the values of the given line segment to this instance.
  41241. *
  41242. * @param {Line3} line - The line segment to copy.
  41243. * @return {Line3} A reference to this line segment.
  41244. */
  41245. copy( line ) {
  41246. this.start.copy( line.start );
  41247. this.end.copy( line.end );
  41248. return this;
  41249. }
  41250. /**
  41251. * Returns the center of the line segment.
  41252. *
  41253. * @param {Vector3} target - The target vector that is used to store the method's result.
  41254. * @return {Vector3} The center point.
  41255. */
  41256. getCenter( target ) {
  41257. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  41258. }
  41259. /**
  41260. * Returns the delta vector of the line segment's start and end point.
  41261. *
  41262. * @param {Vector3} target - The target vector that is used to store the method's result.
  41263. * @return {Vector3} The delta vector.
  41264. */
  41265. delta( target ) {
  41266. return target.subVectors( this.end, this.start );
  41267. }
  41268. /**
  41269. * Returns the squared Euclidean distance between the line' start and end point.
  41270. *
  41271. * @return {number} The squared Euclidean distance.
  41272. */
  41273. distanceSq() {
  41274. return this.start.distanceToSquared( this.end );
  41275. }
  41276. /**
  41277. * Returns the Euclidean distance between the line' start and end point.
  41278. *
  41279. * @return {number} The Euclidean distance.
  41280. */
  41281. distance() {
  41282. return this.start.distanceTo( this.end );
  41283. }
  41284. /**
  41285. * Returns a vector at a certain position along the line segment.
  41286. *
  41287. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41288. * @param {Vector3} target - The target vector that is used to store the method's result.
  41289. * @return {Vector3} The delta vector.
  41290. */
  41291. at( t, target ) {
  41292. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41293. }
  41294. /**
  41295. * Returns a point parameter based on the closest point as projected on the line segment.
  41296. *
  41297. * @param {Vector3} point - The point for which to return a point parameter.
  41298. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41299. * @return {number} The point parameter.
  41300. */
  41301. closestPointToPointParameter( point, clampToLine ) {
  41302. _startP.subVectors( point, this.start );
  41303. _startEnd.subVectors( this.end, this.start );
  41304. const startEnd2 = _startEnd.dot( _startEnd );
  41305. if ( startEnd2 === 0 ) return 0;
  41306. const startEnd_startP = _startEnd.dot( _startP );
  41307. let t = startEnd_startP / startEnd2;
  41308. if ( clampToLine ) {
  41309. t = clamp( t, 0, 1 );
  41310. }
  41311. return t;
  41312. }
  41313. /**
  41314. * Returns the closest point on the line for a given point.
  41315. *
  41316. * @param {Vector3} point - The point to compute the closest point on the line for.
  41317. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41318. * @param {Vector3} target - The target vector that is used to store the method's result.
  41319. * @return {Vector3} The closest point on the line.
  41320. */
  41321. closestPointToPoint( point, clampToLine, target ) {
  41322. const t = this.closestPointToPointParameter( point, clampToLine );
  41323. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41324. }
  41325. /**
  41326. * Returns the closest squared distance between this line segment and the given one.
  41327. *
  41328. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41329. * @param {Vector3} [c1] - The closest point on this line segment.
  41330. * @param {Vector3} [c2] - The closest point on the given line segment.
  41331. * @return {number} The squared distance between this line segment and the given one.
  41332. */
  41333. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41334. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41335. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41336. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41337. // distance between between S1(s) and S2(t)
  41338. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41339. let s, t;
  41340. const p1 = this.start;
  41341. const p2 = line.start;
  41342. const q1 = this.end;
  41343. const q2 = line.end;
  41344. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41345. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41346. _r.subVectors( p1, p2 );
  41347. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41348. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41349. const f = _d2.dot( _r );
  41350. // Check if either or both segments degenerate into points
  41351. if ( a <= EPSILON && e <= EPSILON ) {
  41352. // Both segments degenerate into points
  41353. c1.copy( p1 );
  41354. c2.copy( p2 );
  41355. c1.sub( c2 );
  41356. return c1.dot( c1 );
  41357. }
  41358. if ( a <= EPSILON ) {
  41359. // First segment degenerates into a point
  41360. s = 0;
  41361. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41362. t = clamp( t, 0, 1 );
  41363. } else {
  41364. const c = _d1.dot( _r );
  41365. if ( e <= EPSILON ) {
  41366. // Second segment degenerates into a point
  41367. t = 0;
  41368. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41369. } else {
  41370. // The general nondegenerate case starts here
  41371. const b = _d1.dot( _d2 );
  41372. const denom = a * e - b * b; // Always nonnegative
  41373. // If segments not parallel, compute closest point on L1 to L2 and
  41374. // clamp to segment S1. Else pick arbitrary s (here 0)
  41375. if ( denom !== 0 ) {
  41376. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41377. } else {
  41378. s = 0;
  41379. }
  41380. // Compute point on L2 closest to S1(s) using
  41381. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41382. t = ( b * s + f ) / e;
  41383. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41384. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41385. // and clamp s to [0, 1]
  41386. if ( t < 0 ) {
  41387. t = 0.;
  41388. s = clamp( - c / a, 0, 1 );
  41389. } else if ( t > 1 ) {
  41390. t = 1;
  41391. s = clamp( ( b - c ) / a, 0, 1 );
  41392. }
  41393. }
  41394. }
  41395. c1.copy( p1 ).addScaledVector( _d1, s );
  41396. c2.copy( p2 ).addScaledVector( _d2, t );
  41397. return c1.distanceToSquared( c2 );
  41398. }
  41399. /**
  41400. * Applies a 4x4 transformation matrix to this line segment.
  41401. *
  41402. * @param {Matrix4} matrix - The transformation matrix.
  41403. * @return {Line3} A reference to this line segment.
  41404. */
  41405. applyMatrix4( matrix ) {
  41406. this.start.applyMatrix4( matrix );
  41407. this.end.applyMatrix4( matrix );
  41408. return this;
  41409. }
  41410. /**
  41411. * Returns `true` if this line segment is equal with the given one.
  41412. *
  41413. * @param {Line3} line - The line segment to test for equality.
  41414. * @return {boolean} Whether this line segment is equal with the given one.
  41415. */
  41416. equals( line ) {
  41417. return line.start.equals( this.start ) && line.end.equals( this.end );
  41418. }
  41419. /**
  41420. * Returns a new line segment with copied values from this instance.
  41421. *
  41422. * @return {Line3} A clone of this instance.
  41423. */
  41424. clone() {
  41425. return new this.constructor().copy( this );
  41426. }
  41427. }
  41428. const _vector$3 = /*@__PURE__*/ new Vector3();
  41429. /**
  41430. * This displays a cone shaped helper object for a {@link SpotLight}.
  41431. *
  41432. * When the spot light or its target are transformed or light properties are
  41433. * changed, it's necessary to call the `update()` method of the respective helper.
  41434. *
  41435. * ```js
  41436. * const spotLight = new THREE.SpotLight( 0xffffff );
  41437. * spotLight.position.set( 10, 10, 10 );
  41438. * scene.add( spotLight );
  41439. *
  41440. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41441. * scene.add( spotLightHelper );
  41442. * ```
  41443. *
  41444. * @augments Object3D
  41445. */
  41446. class SpotLightHelper extends Object3D {
  41447. /**
  41448. * Constructs a new spot light helper.
  41449. *
  41450. * @param {HemisphereLight} light - The light to be visualized.
  41451. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41452. * the color of the light.
  41453. */
  41454. constructor( light, color ) {
  41455. super();
  41456. /**
  41457. * The light being visualized.
  41458. *
  41459. * @type {SpotLight}
  41460. */
  41461. this.light = light;
  41462. this.matrixAutoUpdate = false;
  41463. /**
  41464. * The color parameter passed in the constructor.
  41465. * If not set, the helper will take the color of the light.
  41466. *
  41467. * @type {number|Color|string}
  41468. */
  41469. this.color = color;
  41470. this.type = 'SpotLightHelper';
  41471. const geometry = new BufferGeometry();
  41472. const positions = [
  41473. 0, 0, 0, 0, 0, 1,
  41474. 0, 0, 0, 1, 0, 1,
  41475. 0, 0, 0, -1, 0, 1,
  41476. 0, 0, 0, 0, 1, 1,
  41477. 0, 0, 0, 0, -1, 1
  41478. ];
  41479. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41480. const p1 = ( i / l ) * Math.PI * 2;
  41481. const p2 = ( j / l ) * Math.PI * 2;
  41482. positions.push(
  41483. Math.cos( p1 ), Math.sin( p1 ), 1,
  41484. Math.cos( p2 ), Math.sin( p2 ), 1
  41485. );
  41486. }
  41487. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41488. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41489. this.cone = new LineSegments( geometry, material );
  41490. this.add( this.cone );
  41491. this.update();
  41492. }
  41493. /**
  41494. * Frees the GPU-related resources allocated by this instance. Call this
  41495. * method whenever this instance is no longer used in your app.
  41496. */
  41497. dispose() {
  41498. this.cone.geometry.dispose();
  41499. this.cone.material.dispose();
  41500. }
  41501. /**
  41502. * Updates the helper to match the position and direction of the
  41503. * light being visualized.
  41504. */
  41505. update() {
  41506. this.light.updateWorldMatrix( true, false );
  41507. this.light.target.updateWorldMatrix( true, false );
  41508. // update the local matrix based on the parent and light target transforms
  41509. if ( this.parent ) {
  41510. this.parent.updateWorldMatrix( true );
  41511. this.matrix
  41512. .copy( this.parent.matrixWorld )
  41513. .invert()
  41514. .multiply( this.light.matrixWorld );
  41515. } else {
  41516. this.matrix.copy( this.light.matrixWorld );
  41517. }
  41518. this.matrixWorld.copy( this.light.matrixWorld );
  41519. const coneLength = this.light.distance ? this.light.distance : 1000;
  41520. const coneWidth = coneLength * Math.tan( this.light.angle );
  41521. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41522. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41523. this.cone.lookAt( _vector$3 );
  41524. if ( this.color !== undefined ) {
  41525. this.cone.material.color.set( this.color );
  41526. } else {
  41527. this.cone.material.color.copy( this.light.color );
  41528. }
  41529. }
  41530. }
  41531. const _vector$2 = /*@__PURE__*/ new Vector3();
  41532. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41533. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41534. /**
  41535. * A helper object to assist with visualizing a {@link Skeleton}.
  41536. *
  41537. * ```js
  41538. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41539. * scene.add( helper );
  41540. * ```
  41541. *
  41542. * @augments LineSegments
  41543. */
  41544. class SkeletonHelper extends LineSegments {
  41545. /**
  41546. * Constructs a new skeleton helper.
  41547. *
  41548. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41549. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41550. */
  41551. constructor( object ) {
  41552. const bones = getBoneList( object );
  41553. const geometry = new BufferGeometry();
  41554. const vertices = [];
  41555. const colors = [];
  41556. for ( let i = 0; i < bones.length; i ++ ) {
  41557. const bone = bones[ i ];
  41558. if ( bone.parent && bone.parent.isBone ) {
  41559. vertices.push( 0, 0, 0 );
  41560. vertices.push( 0, 0, 0 );
  41561. colors.push( 0, 0, 0 );
  41562. colors.push( 0, 0, 0 );
  41563. }
  41564. }
  41565. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41566. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41567. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41568. super( geometry, material );
  41569. /**
  41570. * This flag can be used for type testing.
  41571. *
  41572. * @type {boolean}
  41573. * @readonly
  41574. * @default true
  41575. */
  41576. this.isSkeletonHelper = true;
  41577. this.type = 'SkeletonHelper';
  41578. /**
  41579. * The object being visualized.
  41580. *
  41581. * @type {Object3D}
  41582. */
  41583. this.root = object;
  41584. /**
  41585. * The list of bones that the helper visualizes.
  41586. *
  41587. * @type {Array<Bone>}
  41588. */
  41589. this.bones = bones;
  41590. this.matrix = object.matrixWorld;
  41591. this.matrixAutoUpdate = false;
  41592. // colors
  41593. const color1 = new Color( 0x0000ff );
  41594. const color2 = new Color( 0x00ff00 );
  41595. this.setColors( color1, color2 );
  41596. }
  41597. updateMatrixWorld( force ) {
  41598. const bones = this.bones;
  41599. const geometry = this.geometry;
  41600. const position = geometry.getAttribute( 'position' );
  41601. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41602. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41603. const bone = bones[ i ];
  41604. if ( bone.parent && bone.parent.isBone ) {
  41605. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41606. _vector$2.setFromMatrixPosition( _boneMatrix );
  41607. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41608. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41609. _vector$2.setFromMatrixPosition( _boneMatrix );
  41610. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41611. j += 2;
  41612. }
  41613. }
  41614. geometry.getAttribute( 'position' ).needsUpdate = true;
  41615. super.updateMatrixWorld( force );
  41616. }
  41617. /**
  41618. * Defines the colors of the helper.
  41619. *
  41620. * @param {Color} color1 - The first line color for each bone.
  41621. * @param {Color} color2 - The second line color for each bone.
  41622. * @return {SkeletonHelper} A reference to this helper.
  41623. */
  41624. setColors( color1, color2 ) {
  41625. const geometry = this.geometry;
  41626. const colorAttribute = geometry.getAttribute( 'color' );
  41627. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41628. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41629. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41630. }
  41631. colorAttribute.needsUpdate = true;
  41632. return this;
  41633. }
  41634. /**
  41635. * Frees the GPU-related resources allocated by this instance. Call this
  41636. * method whenever this instance is no longer used in your app.
  41637. */
  41638. dispose() {
  41639. this.geometry.dispose();
  41640. this.material.dispose();
  41641. }
  41642. }
  41643. function getBoneList( object ) {
  41644. const boneList = [];
  41645. if ( object.isBone === true ) {
  41646. boneList.push( object );
  41647. }
  41648. for ( let i = 0; i < object.children.length; i ++ ) {
  41649. boneList.push( ...getBoneList( object.children[ i ] ) );
  41650. }
  41651. return boneList;
  41652. }
  41653. /**
  41654. * This displays a helper object consisting of a spherical mesh for
  41655. * visualizing an instance of {@link PointLight}.
  41656. *
  41657. * ```js
  41658. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41659. * pointLight.position.set( 10, 10, 10 );
  41660. * scene.add( pointLight );
  41661. *
  41662. * const sphereSize = 1;
  41663. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41664. * scene.add( pointLightHelper );
  41665. * ```
  41666. *
  41667. * @augments Mesh
  41668. */
  41669. class PointLightHelper extends Mesh {
  41670. /**
  41671. * Constructs a new point light helper.
  41672. *
  41673. * @param {PointLight} light - The light to be visualized.
  41674. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41675. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41676. * the color of the light.
  41677. */
  41678. constructor( light, sphereSize, color ) {
  41679. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41680. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41681. super( geometry, material );
  41682. /**
  41683. * The light being visualized.
  41684. *
  41685. * @type {PointLight}
  41686. */
  41687. this.light = light;
  41688. /**
  41689. * The color parameter passed in the constructor.
  41690. * If not set, the helper will take the color of the light.
  41691. *
  41692. * @type {number|Color|string}
  41693. */
  41694. this.color = color;
  41695. this.type = 'PointLightHelper';
  41696. this.matrix = this.light.matrixWorld;
  41697. this.matrixAutoUpdate = false;
  41698. this.update();
  41699. }
  41700. /**
  41701. * Frees the GPU-related resources allocated by this instance. Call this
  41702. * method whenever this instance is no longer used in your app.
  41703. */
  41704. dispose() {
  41705. this.geometry.dispose();
  41706. this.material.dispose();
  41707. }
  41708. /**
  41709. * Updates the helper to match the position of the
  41710. * light being visualized.
  41711. */
  41712. update() {
  41713. this.light.updateWorldMatrix( true, false );
  41714. if ( this.color !== undefined ) {
  41715. this.material.color.set( this.color );
  41716. } else {
  41717. this.material.color.copy( this.light.color );
  41718. }
  41719. /*
  41720. const d = this.light.distance;
  41721. if ( d === 0.0 ) {
  41722. this.lightDistance.visible = false;
  41723. } else {
  41724. this.lightDistance.visible = true;
  41725. this.lightDistance.scale.set( d, d, d );
  41726. }
  41727. */
  41728. }
  41729. }
  41730. const _vector$1 = /*@__PURE__*/ new Vector3();
  41731. const _color1 = /*@__PURE__*/ new Color();
  41732. const _color2 = /*@__PURE__*/ new Color();
  41733. /**
  41734. * Creates a visual aid consisting of a spherical mesh for a
  41735. * given {@link HemisphereLight}.
  41736. *
  41737. * When the hemisphere light is transformed or its light properties are changed,
  41738. * it's necessary to call the `update()` method of the respective helper.
  41739. *
  41740. * ```js
  41741. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41742. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41743. * scene.add( helper );
  41744. * ```
  41745. *
  41746. * @augments Object3D
  41747. */
  41748. class HemisphereLightHelper extends Object3D {
  41749. /**
  41750. * Constructs a new hemisphere light helper.
  41751. *
  41752. * @param {HemisphereLight} light - The light to be visualized.
  41753. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41754. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41755. * the color of the light.
  41756. */
  41757. constructor( light, size, color ) {
  41758. super();
  41759. /**
  41760. * The light being visualized.
  41761. *
  41762. * @type {HemisphereLight}
  41763. */
  41764. this.light = light;
  41765. this.matrix = light.matrixWorld;
  41766. this.matrixAutoUpdate = false;
  41767. /**
  41768. * The color parameter passed in the constructor.
  41769. * If not set, the helper will take the color of the light.
  41770. *
  41771. * @type {number|Color|string}
  41772. */
  41773. this.color = color;
  41774. this.type = 'HemisphereLightHelper';
  41775. const geometry = new OctahedronGeometry( size );
  41776. geometry.rotateY( Math.PI * 0.5 );
  41777. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41778. if ( this.color === undefined ) this.material.vertexColors = true;
  41779. const position = geometry.getAttribute( 'position' );
  41780. const colors = new Float32Array( position.count * 3 );
  41781. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41782. this.add( new Mesh( geometry, this.material ) );
  41783. this.update();
  41784. }
  41785. /**
  41786. * Frees the GPU-related resources allocated by this instance. Call this
  41787. * method whenever this instance is no longer used in your app.
  41788. */
  41789. dispose() {
  41790. this.children[ 0 ].geometry.dispose();
  41791. this.children[ 0 ].material.dispose();
  41792. }
  41793. /**
  41794. * Updates the helper to match the position and direction of the
  41795. * light being visualized.
  41796. */
  41797. update() {
  41798. const mesh = this.children[ 0 ];
  41799. if ( this.color !== undefined ) {
  41800. this.material.color.set( this.color );
  41801. } else {
  41802. const colors = mesh.geometry.getAttribute( 'color' );
  41803. _color1.copy( this.light.color );
  41804. _color2.copy( this.light.groundColor );
  41805. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41806. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41807. colors.setXYZ( i, color.r, color.g, color.b );
  41808. }
  41809. colors.needsUpdate = true;
  41810. }
  41811. this.light.updateWorldMatrix( true, false );
  41812. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41813. }
  41814. }
  41815. /**
  41816. * The helper is an object to define grids. Grids are two-dimensional
  41817. * arrays of lines.
  41818. *
  41819. * ```js
  41820. * const size = 10;
  41821. * const divisions = 10;
  41822. *
  41823. * const gridHelper = new THREE.GridHelper( size, divisions );
  41824. * scene.add( gridHelper );
  41825. * ```
  41826. *
  41827. * @augments LineSegments
  41828. */
  41829. class GridHelper extends LineSegments {
  41830. /**
  41831. * Constructs a new grid helper.
  41832. *
  41833. * @param {number} [size=10] - The size of the grid.
  41834. * @param {number} [divisions=10] - The number of divisions across the grid.
  41835. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41836. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41837. */
  41838. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41839. color1 = new Color( color1 );
  41840. color2 = new Color( color2 );
  41841. const center = divisions / 2;
  41842. const step = size / divisions;
  41843. const halfSize = size / 2;
  41844. const vertices = [], colors = [];
  41845. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41846. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41847. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41848. const color = i === center ? color1 : color2;
  41849. color.toArray( colors, j ); j += 3;
  41850. color.toArray( colors, j ); j += 3;
  41851. color.toArray( colors, j ); j += 3;
  41852. color.toArray( colors, j ); j += 3;
  41853. }
  41854. const geometry = new BufferGeometry();
  41855. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41856. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41857. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41858. super( geometry, material );
  41859. this.type = 'GridHelper';
  41860. }
  41861. /**
  41862. * Frees the GPU-related resources allocated by this instance. Call this
  41863. * method whenever this instance is no longer used in your app.
  41864. */
  41865. dispose() {
  41866. this.geometry.dispose();
  41867. this.material.dispose();
  41868. }
  41869. }
  41870. /**
  41871. * This helper is an object to define polar grids. Grids are
  41872. * two-dimensional arrays of lines.
  41873. *
  41874. * ```js
  41875. * const radius = 10;
  41876. * const sectors = 16;
  41877. * const rings = 8;
  41878. * const divisions = 64;
  41879. *
  41880. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41881. * scene.add( helper );
  41882. * ```
  41883. *
  41884. * @augments LineSegments
  41885. */
  41886. class PolarGridHelper extends LineSegments {
  41887. /**
  41888. * Constructs a new polar grid helper.
  41889. *
  41890. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41891. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41892. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41893. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41894. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41895. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41896. */
  41897. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41898. color1 = new Color( color1 );
  41899. color2 = new Color( color2 );
  41900. const vertices = [];
  41901. const colors = [];
  41902. // create the sectors
  41903. if ( sectors > 1 ) {
  41904. for ( let i = 0; i < sectors; i ++ ) {
  41905. const v = ( i / sectors ) * ( Math.PI * 2 );
  41906. const x = Math.sin( v ) * radius;
  41907. const z = Math.cos( v ) * radius;
  41908. vertices.push( 0, 0, 0 );
  41909. vertices.push( x, 0, z );
  41910. const color = ( i & 1 ) ? color1 : color2;
  41911. colors.push( color.r, color.g, color.b );
  41912. colors.push( color.r, color.g, color.b );
  41913. }
  41914. }
  41915. // create the rings
  41916. for ( let i = 0; i < rings; i ++ ) {
  41917. const color = ( i & 1 ) ? color1 : color2;
  41918. const r = radius - ( radius / rings * i );
  41919. for ( let j = 0; j < divisions; j ++ ) {
  41920. // first vertex
  41921. let v = ( j / divisions ) * ( Math.PI * 2 );
  41922. let x = Math.sin( v ) * r;
  41923. let z = Math.cos( v ) * r;
  41924. vertices.push( x, 0, z );
  41925. colors.push( color.r, color.g, color.b );
  41926. // second vertex
  41927. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41928. x = Math.sin( v ) * r;
  41929. z = Math.cos( v ) * r;
  41930. vertices.push( x, 0, z );
  41931. colors.push( color.r, color.g, color.b );
  41932. }
  41933. }
  41934. const geometry = new BufferGeometry();
  41935. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41936. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41937. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41938. super( geometry, material );
  41939. this.type = 'PolarGridHelper';
  41940. }
  41941. /**
  41942. * Frees the GPU-related resources allocated by this instance. Call this
  41943. * method whenever this instance is no longer used in your app.
  41944. */
  41945. dispose() {
  41946. this.geometry.dispose();
  41947. this.material.dispose();
  41948. }
  41949. }
  41950. const _v1 = /*@__PURE__*/ new Vector3();
  41951. const _v2 = /*@__PURE__*/ new Vector3();
  41952. const _v3 = /*@__PURE__*/ new Vector3();
  41953. /**
  41954. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41955. * effect on the scene. This consists of a plane and a line representing the
  41956. * light's position and direction.
  41957. *
  41958. * When the directional light or its target are transformed or light properties
  41959. * are changed, it's necessary to call the `update()` method of the respective helper.
  41960. *
  41961. * ```js
  41962. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41963. * scene.add( light );
  41964. *
  41965. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41966. * scene.add( helper );
  41967. * ```
  41968. *
  41969. * @augments Object3D
  41970. */
  41971. class DirectionalLightHelper extends Object3D {
  41972. /**
  41973. * Constructs a new directional light helper.
  41974. *
  41975. * @param {DirectionalLight} light - The light to be visualized.
  41976. * @param {number} [size=1] - The dimensions of the plane.
  41977. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41978. * the color of the light.
  41979. */
  41980. constructor( light, size, color ) {
  41981. super();
  41982. /**
  41983. * The light being visualized.
  41984. *
  41985. * @type {DirectionalLight}
  41986. */
  41987. this.light = light;
  41988. this.matrix = light.matrixWorld;
  41989. this.matrixAutoUpdate = false;
  41990. /**
  41991. * The color parameter passed in the constructor.
  41992. * If not set, the helper will take the color of the light.
  41993. *
  41994. * @type {number|Color|string}
  41995. */
  41996. this.color = color;
  41997. this.type = 'DirectionalLightHelper';
  41998. if ( size === undefined ) size = 1;
  41999. let geometry = new BufferGeometry();
  42000. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  42001. - size, size, 0,
  42002. size, size, 0,
  42003. size, - size, 0,
  42004. - size, - size, 0,
  42005. - size, size, 0
  42006. ], 3 ) );
  42007. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  42008. /**
  42009. * Contains the line showing the location of the directional light.
  42010. *
  42011. * @type {Line}
  42012. */
  42013. this.lightPlane = new Line( geometry, material );
  42014. this.add( this.lightPlane );
  42015. geometry = new BufferGeometry();
  42016. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  42017. /**
  42018. * Represents the target line of the directional light.
  42019. *
  42020. * @type {Line}
  42021. */
  42022. this.targetLine = new Line( geometry, material );
  42023. this.add( this.targetLine );
  42024. this.update();
  42025. }
  42026. /**
  42027. * Frees the GPU-related resources allocated by this instance. Call this
  42028. * method whenever this instance is no longer used in your app.
  42029. */
  42030. dispose() {
  42031. this.lightPlane.geometry.dispose();
  42032. this.lightPlane.material.dispose();
  42033. this.targetLine.geometry.dispose();
  42034. this.targetLine.material.dispose();
  42035. }
  42036. /**
  42037. * Updates the helper to match the position and direction of the
  42038. * light being visualized.
  42039. */
  42040. update() {
  42041. this.light.updateWorldMatrix( true, false );
  42042. this.light.target.updateWorldMatrix( true, false );
  42043. _v1.setFromMatrixPosition( this.light.matrixWorld );
  42044. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  42045. _v3.subVectors( _v2, _v1 );
  42046. this.lightPlane.lookAt( _v2 );
  42047. if ( this.color !== undefined ) {
  42048. this.lightPlane.material.color.set( this.color );
  42049. this.targetLine.material.color.set( this.color );
  42050. } else {
  42051. this.lightPlane.material.color.copy( this.light.color );
  42052. this.targetLine.material.color.copy( this.light.color );
  42053. }
  42054. this.targetLine.lookAt( _v2 );
  42055. this.targetLine.scale.z = _v3.length();
  42056. }
  42057. }
  42058. const _vector = /*@__PURE__*/ new Vector3();
  42059. const _camera = /*@__PURE__*/ new Camera();
  42060. /**
  42061. * This helps with visualizing what a camera contains in its frustum. It
  42062. * visualizes the frustum of a camera using a line segments.
  42063. *
  42064. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  42065. *
  42066. * `CameraHelper` must be a child of the scene.
  42067. *
  42068. * When the camera is transformed or its projection matrix is changed, it's necessary
  42069. * to call the `update()` method of the respective helper.
  42070. *
  42071. * ```js
  42072. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  42073. * const helper = new THREE.CameraHelper( camera );
  42074. * scene.add( helper );
  42075. * ```
  42076. *
  42077. * @augments LineSegments
  42078. */
  42079. class CameraHelper extends LineSegments {
  42080. /**
  42081. * Constructs a new arrow helper.
  42082. *
  42083. * @param {Camera} camera - The camera to visualize.
  42084. */
  42085. constructor( camera ) {
  42086. const geometry = new BufferGeometry();
  42087. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  42088. const vertices = [];
  42089. const colors = [];
  42090. const pointMap = {};
  42091. // near
  42092. addLine( 'n1', 'n2' );
  42093. addLine( 'n2', 'n4' );
  42094. addLine( 'n4', 'n3' );
  42095. addLine( 'n3', 'n1' );
  42096. // far
  42097. addLine( 'f1', 'f2' );
  42098. addLine( 'f2', 'f4' );
  42099. addLine( 'f4', 'f3' );
  42100. addLine( 'f3', 'f1' );
  42101. // sides
  42102. addLine( 'n1', 'f1' );
  42103. addLine( 'n2', 'f2' );
  42104. addLine( 'n3', 'f3' );
  42105. addLine( 'n4', 'f4' );
  42106. // cone
  42107. addLine( 'p', 'n1' );
  42108. addLine( 'p', 'n2' );
  42109. addLine( 'p', 'n3' );
  42110. addLine( 'p', 'n4' );
  42111. // up
  42112. addLine( 'u1', 'u2' );
  42113. addLine( 'u2', 'u3' );
  42114. addLine( 'u3', 'u1' );
  42115. // target
  42116. addLine( 'c', 't' );
  42117. addLine( 'p', 'c' );
  42118. // cross
  42119. addLine( 'cn1', 'cn2' );
  42120. addLine( 'cn3', 'cn4' );
  42121. addLine( 'cf1', 'cf2' );
  42122. addLine( 'cf3', 'cf4' );
  42123. function addLine( a, b ) {
  42124. addPoint( a );
  42125. addPoint( b );
  42126. }
  42127. function addPoint( id ) {
  42128. vertices.push( 0, 0, 0 );
  42129. colors.push( 0, 0, 0 );
  42130. if ( pointMap[ id ] === undefined ) {
  42131. pointMap[ id ] = [];
  42132. }
  42133. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  42134. }
  42135. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42136. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42137. super( geometry, material );
  42138. this.type = 'CameraHelper';
  42139. /**
  42140. * The camera being visualized.
  42141. *
  42142. * @type {Camera}
  42143. */
  42144. this.camera = camera;
  42145. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  42146. this.matrix = camera.matrixWorld;
  42147. this.matrixAutoUpdate = false;
  42148. /**
  42149. * This contains the points used to visualize the camera.
  42150. *
  42151. * @type {Object<string,Array<number>>}
  42152. */
  42153. this.pointMap = pointMap;
  42154. this.update();
  42155. // colors
  42156. const colorFrustum = new Color( 0xffaa00 );
  42157. const colorCone = new Color( 0xff0000 );
  42158. const colorUp = new Color( 0x00aaff );
  42159. const colorTarget = new Color( 0xffffff );
  42160. const colorCross = new Color( 0x333333 );
  42161. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  42162. }
  42163. /**
  42164. * Defines the colors of the helper.
  42165. *
  42166. * @param {Color} frustum - The frustum line color.
  42167. * @param {Color} cone - The cone line color.
  42168. * @param {Color} up - The up line color.
  42169. * @param {Color} target - The target line color.
  42170. * @param {Color} cross - The cross line color.
  42171. * @return {CameraHelper} A reference to this helper.
  42172. */
  42173. setColors( frustum, cone, up, target, cross ) {
  42174. const geometry = this.geometry;
  42175. const colorAttribute = geometry.getAttribute( 'color' );
  42176. // near
  42177. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  42178. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  42179. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  42180. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  42181. // far
  42182. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  42183. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  42184. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  42185. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  42186. // sides
  42187. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  42188. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  42189. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  42190. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  42191. // cone
  42192. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  42193. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  42194. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  42195. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  42196. // up
  42197. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  42198. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  42199. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  42200. // target
  42201. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  42202. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  42203. // cross
  42204. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  42205. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  42206. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  42207. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  42208. colorAttribute.needsUpdate = true;
  42209. return this;
  42210. }
  42211. /**
  42212. * Updates the helper based on the projection matrix of the camera.
  42213. */
  42214. update() {
  42215. const geometry = this.geometry;
  42216. const pointMap = this.pointMap;
  42217. const w = 1, h = 1;
  42218. let nearZ, farZ;
  42219. // we need just camera projection matrix inverse
  42220. // world matrix must be identity
  42221. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  42222. // Adjust z values based on coordinate system
  42223. if ( this.camera.reversedDepth === true ) {
  42224. nearZ = 1;
  42225. farZ = 0;
  42226. } else {
  42227. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  42228. nearZ = -1;
  42229. farZ = 1;
  42230. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  42231. nearZ = 0;
  42232. farZ = 1;
  42233. } else {
  42234. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  42235. }
  42236. }
  42237. // center / target
  42238. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  42239. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  42240. // near
  42241. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  42242. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  42243. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  42244. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  42245. // far
  42246. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  42247. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  42248. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  42249. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  42250. // up
  42251. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  42252. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  42253. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  42254. // cross
  42255. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  42256. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  42257. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  42258. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  42259. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  42260. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  42261. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  42262. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  42263. geometry.getAttribute( 'position' ).needsUpdate = true;
  42264. }
  42265. /**
  42266. * Frees the GPU-related resources allocated by this instance. Call this
  42267. * method whenever this instance is no longer used in your app.
  42268. */
  42269. dispose() {
  42270. this.geometry.dispose();
  42271. this.material.dispose();
  42272. }
  42273. }
  42274. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42275. _vector.set( x, y, z ).unproject( camera );
  42276. const points = pointMap[ point ];
  42277. if ( points !== undefined ) {
  42278. const position = geometry.getAttribute( 'position' );
  42279. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42280. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42281. }
  42282. }
  42283. }
  42284. const _box = /*@__PURE__*/ new Box3();
  42285. /**
  42286. * Helper object to graphically show the world-axis-aligned bounding box
  42287. * around an object. The actual bounding box is handled with {@link Box3},
  42288. * this is just a visual helper for debugging. It can be automatically
  42289. * resized with {@link BoxHelper#update} when the object it's created from
  42290. * is transformed. Note that the object must have a geometry for this to work,
  42291. * so it won't work with sprites.
  42292. *
  42293. * ```js
  42294. * const sphere = new THREE.SphereGeometry();
  42295. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42296. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42297. * scene.add( box );
  42298. * ```
  42299. *
  42300. * @augments LineSegments
  42301. */
  42302. class BoxHelper extends LineSegments {
  42303. /**
  42304. * Constructs a new box helper.
  42305. *
  42306. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42307. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42308. */
  42309. constructor( object, color = 0xffff00 ) {
  42310. 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 ] );
  42311. const positions = new Float32Array( 8 * 3 );
  42312. const geometry = new BufferGeometry();
  42313. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42314. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42315. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42316. /**
  42317. * The 3D object being visualized.
  42318. *
  42319. * @type {Object3D}
  42320. */
  42321. this.object = object;
  42322. this.type = 'BoxHelper';
  42323. this.matrixAutoUpdate = false;
  42324. this.update();
  42325. }
  42326. /**
  42327. * Updates the helper's geometry to match the dimensions of the object,
  42328. * including any children.
  42329. */
  42330. update() {
  42331. if ( this.object !== undefined ) {
  42332. _box.setFromObject( this.object );
  42333. }
  42334. if ( _box.isEmpty() ) return;
  42335. const min = _box.min;
  42336. const max = _box.max;
  42337. /*
  42338. 5____4
  42339. 1/___0/|
  42340. | 6__|_7
  42341. 2/___3/
  42342. 0: max.x, max.y, max.z
  42343. 1: min.x, max.y, max.z
  42344. 2: min.x, min.y, max.z
  42345. 3: max.x, min.y, max.z
  42346. 4: max.x, max.y, min.z
  42347. 5: min.x, max.y, min.z
  42348. 6: min.x, min.y, min.z
  42349. 7: max.x, min.y, min.z
  42350. */
  42351. const position = this.geometry.attributes.position;
  42352. const array = position.array;
  42353. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42354. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42355. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42356. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42357. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42358. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42359. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42360. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42361. position.needsUpdate = true;
  42362. this.geometry.computeBoundingSphere();
  42363. }
  42364. /**
  42365. * Updates the wireframe box for the passed object.
  42366. *
  42367. * @param {Object3D} object - The 3D object to create the helper for.
  42368. * @return {BoxHelper} A reference to this instance.
  42369. */
  42370. setFromObject( object ) {
  42371. this.object = object;
  42372. this.update();
  42373. return this;
  42374. }
  42375. copy( source, recursive ) {
  42376. super.copy( source, recursive );
  42377. this.object = source.object;
  42378. return this;
  42379. }
  42380. /**
  42381. * Frees the GPU-related resources allocated by this instance. Call this
  42382. * method whenever this instance is no longer used in your app.
  42383. */
  42384. dispose() {
  42385. this.geometry.dispose();
  42386. this.material.dispose();
  42387. }
  42388. }
  42389. /**
  42390. * A helper object to visualize an instance of {@link Box3}.
  42391. *
  42392. * ```js
  42393. * const box = new THREE.Box3();
  42394. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42395. *
  42396. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42397. * scene.add( helper )
  42398. * ```
  42399. *
  42400. * @augments LineSegments
  42401. */
  42402. class Box3Helper extends LineSegments {
  42403. /**
  42404. * Constructs a new box3 helper.
  42405. *
  42406. * @param {Box3} box - The box to visualize.
  42407. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42408. */
  42409. constructor( box, color = 0xffff00 ) {
  42410. 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 ] );
  42411. 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 ];
  42412. const geometry = new BufferGeometry();
  42413. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42414. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42415. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42416. /**
  42417. * The box being visualized.
  42418. *
  42419. * @type {Box3}
  42420. */
  42421. this.box = box;
  42422. this.type = 'Box3Helper';
  42423. this.geometry.computeBoundingSphere();
  42424. }
  42425. updateMatrixWorld( force ) {
  42426. const box = this.box;
  42427. if ( box.isEmpty() ) return;
  42428. box.getCenter( this.position );
  42429. box.getSize( this.scale );
  42430. this.scale.multiplyScalar( 0.5 );
  42431. super.updateMatrixWorld( force );
  42432. }
  42433. /**
  42434. * Frees the GPU-related resources allocated by this instance. Call this
  42435. * method whenever this instance is no longer used in your app.
  42436. */
  42437. dispose() {
  42438. this.geometry.dispose();
  42439. this.material.dispose();
  42440. }
  42441. }
  42442. /**
  42443. * A helper object to visualize an instance of {@link Plane}.
  42444. *
  42445. * ```js
  42446. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42447. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42448. * scene.add( helper );
  42449. * ```
  42450. *
  42451. * @augments Line
  42452. */
  42453. class PlaneHelper extends Line {
  42454. /**
  42455. * Constructs a new plane helper.
  42456. *
  42457. * @param {Plane} plane - The plane to be visualized.
  42458. * @param {number} [size=1] - The side length of plane helper.
  42459. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42460. */
  42461. constructor( plane, size = 1, hex = 0xffff00 ) {
  42462. const color = hex;
  42463. 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 ];
  42464. const geometry = new BufferGeometry();
  42465. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42466. geometry.computeBoundingSphere();
  42467. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42468. this.type = 'PlaneHelper';
  42469. /**
  42470. * The plane being visualized.
  42471. *
  42472. * @type {Plane}
  42473. */
  42474. this.plane = plane;
  42475. /**
  42476. * The side length of plane helper.
  42477. *
  42478. * @type {number}
  42479. * @default 1
  42480. */
  42481. this.size = size;
  42482. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42483. const geometry2 = new BufferGeometry();
  42484. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42485. geometry2.computeBoundingSphere();
  42486. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42487. }
  42488. updateMatrixWorld( force ) {
  42489. this.position.set( 0, 0, 0 );
  42490. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42491. this.lookAt( this.plane.normal );
  42492. this.translateZ( - this.plane.constant );
  42493. super.updateMatrixWorld( force );
  42494. }
  42495. /**
  42496. * Updates the helper to match the position and direction of the
  42497. * light being visualized.
  42498. */
  42499. dispose() {
  42500. this.geometry.dispose();
  42501. this.material.dispose();
  42502. this.children[ 0 ].geometry.dispose();
  42503. this.children[ 0 ].material.dispose();
  42504. }
  42505. }
  42506. const _axis = /*@__PURE__*/ new Vector3();
  42507. let _lineGeometry, _coneGeometry;
  42508. /**
  42509. * An 3D arrow object for visualizing directions.
  42510. *
  42511. * ```js
  42512. * const dir = new THREE.Vector3( 1, 2, 0 );
  42513. *
  42514. * //normalize the direction vector (convert to vector of length 1)
  42515. * dir.normalize();
  42516. *
  42517. * const origin = new THREE.Vector3( 0, 0, 0 );
  42518. * const length = 1;
  42519. * const hex = 0xffff00;
  42520. *
  42521. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42522. * scene.add( arrowHelper );
  42523. * ```
  42524. *
  42525. * @augments Object3D
  42526. */
  42527. class ArrowHelper extends Object3D {
  42528. /**
  42529. * Constructs a new arrow helper.
  42530. *
  42531. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42532. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42533. * @param {number} [length=1] - Length of the arrow in world units.
  42534. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42535. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42536. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42537. */
  42538. 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 ) {
  42539. super();
  42540. this.type = 'ArrowHelper';
  42541. if ( _lineGeometry === undefined ) {
  42542. _lineGeometry = new BufferGeometry();
  42543. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42544. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42545. _coneGeometry.translate( 0, -0.5, 0 );
  42546. }
  42547. this.position.copy( origin );
  42548. /**
  42549. * The line part of the arrow helper.
  42550. *
  42551. * @type {Line}
  42552. */
  42553. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42554. this.line.matrixAutoUpdate = false;
  42555. this.add( this.line );
  42556. /**
  42557. * The cone part of the arrow helper.
  42558. *
  42559. * @type {Mesh}
  42560. */
  42561. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42562. this.cone.matrixAutoUpdate = false;
  42563. this.add( this.cone );
  42564. this.setDirection( dir );
  42565. this.setLength( length, headLength, headWidth );
  42566. }
  42567. /**
  42568. * Sets the direction of the helper.
  42569. *
  42570. * @param {Vector3} dir - The normalized direction vector.
  42571. */
  42572. setDirection( dir ) {
  42573. // dir is assumed to be normalized
  42574. if ( dir.y > 0.99999 ) {
  42575. this.quaternion.set( 0, 0, 0, 1 );
  42576. } else if ( dir.y < -0.99999 ) {
  42577. this.quaternion.set( 1, 0, 0, 0 );
  42578. } else {
  42579. _axis.set( dir.z, 0, - dir.x ).normalize();
  42580. const radians = Math.acos( dir.y );
  42581. this.quaternion.setFromAxisAngle( _axis, radians );
  42582. }
  42583. }
  42584. /**
  42585. * Sets the length of the helper.
  42586. *
  42587. * @param {number} length - Length of the arrow in world units.
  42588. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42589. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42590. */
  42591. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42592. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42593. this.line.updateMatrix();
  42594. this.cone.scale.set( headWidth, headLength, headWidth );
  42595. this.cone.position.y = length;
  42596. this.cone.updateMatrix();
  42597. }
  42598. /**
  42599. * Sets the color of the helper.
  42600. *
  42601. * @param {number|Color|string} color - The color to set.
  42602. */
  42603. setColor( color ) {
  42604. this.line.material.color.set( color );
  42605. this.cone.material.color.set( color );
  42606. }
  42607. copy( source ) {
  42608. super.copy( source, false );
  42609. this.line.copy( source.line );
  42610. this.cone.copy( source.cone );
  42611. return this;
  42612. }
  42613. /**
  42614. * Frees the GPU-related resources allocated by this instance. Call this
  42615. * method whenever this instance is no longer used in your app.
  42616. */
  42617. dispose() {
  42618. this.line.geometry.dispose();
  42619. this.line.material.dispose();
  42620. this.cone.geometry.dispose();
  42621. this.cone.material.dispose();
  42622. }
  42623. }
  42624. /**
  42625. * An axis object to visualize the 3 axes in a simple way.
  42626. * The X axis is red. The Y axis is green. The Z axis is blue.
  42627. *
  42628. * ```js
  42629. * const axesHelper = new THREE.AxesHelper( 5 );
  42630. * scene.add( axesHelper );
  42631. * ```
  42632. *
  42633. * @augments LineSegments
  42634. */
  42635. class AxesHelper extends LineSegments {
  42636. /**
  42637. * Constructs a new axes helper.
  42638. *
  42639. * @param {number} [size=1] - Size of the lines representing the axes.
  42640. */
  42641. constructor( size = 1 ) {
  42642. const vertices = [
  42643. 0, 0, 0, size, 0, 0,
  42644. 0, 0, 0, 0, size, 0,
  42645. 0, 0, 0, 0, 0, size
  42646. ];
  42647. const colors = [
  42648. 1, 0, 0, 1, 0.6, 0,
  42649. 0, 1, 0, 0.6, 1, 0,
  42650. 0, 0, 1, 0, 0.6, 1
  42651. ];
  42652. const geometry = new BufferGeometry();
  42653. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42654. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42655. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42656. super( geometry, material );
  42657. this.type = 'AxesHelper';
  42658. }
  42659. /**
  42660. * Defines the colors of the axes helper.
  42661. *
  42662. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42663. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42664. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42665. * @return {AxesHelper} A reference to this axes helper.
  42666. */
  42667. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42668. const color = new Color();
  42669. const array = this.geometry.attributes.color.array;
  42670. color.set( xAxisColor );
  42671. color.toArray( array, 0 );
  42672. color.toArray( array, 3 );
  42673. color.set( yAxisColor );
  42674. color.toArray( array, 6 );
  42675. color.toArray( array, 9 );
  42676. color.set( zAxisColor );
  42677. color.toArray( array, 12 );
  42678. color.toArray( array, 15 );
  42679. this.geometry.attributes.color.needsUpdate = true;
  42680. return this;
  42681. }
  42682. /**
  42683. * Frees the GPU-related resources allocated by this instance. Call this
  42684. * method whenever this instance is no longer used in your app.
  42685. */
  42686. dispose() {
  42687. this.geometry.dispose();
  42688. this.material.dispose();
  42689. }
  42690. }
  42691. /**
  42692. * This class is used to convert a series of paths to an array of
  42693. * shapes. It is specifically used in context of fonts and SVG.
  42694. */
  42695. class ShapePath {
  42696. /**
  42697. * Constructs a new shape path.
  42698. */
  42699. constructor() {
  42700. this.type = 'ShapePath';
  42701. /**
  42702. * The color of the shape.
  42703. *
  42704. * @type {Color}
  42705. */
  42706. this.color = new Color();
  42707. /**
  42708. * The paths that have been generated for this shape.
  42709. *
  42710. * @type {Array<Path>}
  42711. * @default null
  42712. */
  42713. this.subPaths = [];
  42714. /**
  42715. * The current path that is being generated.
  42716. *
  42717. * @type {?Path}
  42718. * @default null
  42719. */
  42720. this.currentPath = null;
  42721. }
  42722. /**
  42723. * Creates a new path and moves it current point to the given one.
  42724. *
  42725. * @param {number} x - The x coordinate.
  42726. * @param {number} y - The y coordinate.
  42727. * @return {ShapePath} A reference to this shape path.
  42728. */
  42729. moveTo( x, y ) {
  42730. this.currentPath = new Path();
  42731. this.subPaths.push( this.currentPath );
  42732. this.currentPath.moveTo( x, y );
  42733. return this;
  42734. }
  42735. /**
  42736. * Adds an instance of {@link LineCurve} to the path by connecting
  42737. * the current point with the given one.
  42738. *
  42739. * @param {number} x - The x coordinate of the end point.
  42740. * @param {number} y - The y coordinate of the end point.
  42741. * @return {ShapePath} A reference to this shape path.
  42742. */
  42743. lineTo( x, y ) {
  42744. this.currentPath.lineTo( x, y );
  42745. return this;
  42746. }
  42747. /**
  42748. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42749. * the current point with the given one.
  42750. *
  42751. * @param {number} aCPx - The x coordinate of the control point.
  42752. * @param {number} aCPy - The y coordinate of the control point.
  42753. * @param {number} aX - The x coordinate of the end point.
  42754. * @param {number} aY - The y coordinate of the end point.
  42755. * @return {ShapePath} A reference to this shape path.
  42756. */
  42757. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42758. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42759. return this;
  42760. }
  42761. /**
  42762. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42763. * the current point with the given one.
  42764. *
  42765. * @param {number} aCP1x - The x coordinate of the first control point.
  42766. * @param {number} aCP1y - The y coordinate of the first control point.
  42767. * @param {number} aCP2x - The x coordinate of the second control point.
  42768. * @param {number} aCP2y - The y coordinate of the second control point.
  42769. * @param {number} aX - The x coordinate of the end point.
  42770. * @param {number} aY - The y coordinate of the end point.
  42771. * @return {ShapePath} A reference to this shape path.
  42772. */
  42773. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42774. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42775. return this;
  42776. }
  42777. /**
  42778. * Adds an instance of {@link SplineCurve} to the path by connecting
  42779. * the current point with the given list of points.
  42780. *
  42781. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42782. * @return {ShapePath} A reference to this shape path.
  42783. */
  42784. splineThru( pts ) {
  42785. this.currentPath.splineThru( pts );
  42786. return this;
  42787. }
  42788. /**
  42789. * Converts the paths into an array of shapes.
  42790. *
  42791. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42792. * If this flag is set to `true`, then those are flipped.
  42793. * @return {Array<Shape>} An array of shapes.
  42794. */
  42795. toShapes( isCCW ) {
  42796. function toShapesNoHoles( inSubpaths ) {
  42797. const shapes = [];
  42798. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42799. const tmpPath = inSubpaths[ i ];
  42800. const tmpShape = new Shape();
  42801. tmpShape.curves = tmpPath.curves;
  42802. shapes.push( tmpShape );
  42803. }
  42804. return shapes;
  42805. }
  42806. function isPointInsidePolygon( inPt, inPolygon ) {
  42807. const polyLen = inPolygon.length;
  42808. // inPt on polygon contour => immediate success or
  42809. // toggling of inside/outside at every single! intersection point of an edge
  42810. // with the horizontal line through inPt, left of inPt
  42811. // not counting lowerY endpoints of edges and whole edges on that line
  42812. let inside = false;
  42813. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42814. let edgeLowPt = inPolygon[ p ];
  42815. let edgeHighPt = inPolygon[ q ];
  42816. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42817. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42818. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42819. // not parallel
  42820. if ( edgeDy < 0 ) {
  42821. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42822. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42823. }
  42824. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42825. if ( inPt.y === edgeLowPt.y ) {
  42826. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42827. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42828. } else {
  42829. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42830. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42831. if ( perpEdge < 0 ) continue;
  42832. inside = ! inside; // true intersection left of inPt
  42833. }
  42834. } else {
  42835. // parallel or collinear
  42836. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42837. // edge lies on the same horizontal line as inPt
  42838. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42839. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42840. // continue;
  42841. }
  42842. }
  42843. return inside;
  42844. }
  42845. const isClockWise = ShapeUtils.isClockWise;
  42846. const subPaths = this.subPaths;
  42847. if ( subPaths.length === 0 ) return [];
  42848. let solid, tmpPath, tmpShape;
  42849. const shapes = [];
  42850. if ( subPaths.length === 1 ) {
  42851. tmpPath = subPaths[ 0 ];
  42852. tmpShape = new Shape();
  42853. tmpShape.curves = tmpPath.curves;
  42854. shapes.push( tmpShape );
  42855. return shapes;
  42856. }
  42857. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42858. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42859. // log("Holes first", holesFirst);
  42860. const betterShapeHoles = [];
  42861. const newShapes = [];
  42862. let newShapeHoles = [];
  42863. let mainIdx = 0;
  42864. let tmpPoints;
  42865. newShapes[ mainIdx ] = undefined;
  42866. newShapeHoles[ mainIdx ] = [];
  42867. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42868. tmpPath = subPaths[ i ];
  42869. tmpPoints = tmpPath.getPoints();
  42870. solid = isClockWise( tmpPoints );
  42871. solid = isCCW ? ! solid : solid;
  42872. if ( solid ) {
  42873. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42874. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42875. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42876. if ( holesFirst ) mainIdx ++;
  42877. newShapeHoles[ mainIdx ] = [];
  42878. //log('cw', i);
  42879. } else {
  42880. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42881. //log('ccw', i);
  42882. }
  42883. }
  42884. // only Holes? -> probably all Shapes with wrong orientation
  42885. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42886. if ( newShapes.length > 1 ) {
  42887. let ambiguous = false;
  42888. let toChange = 0;
  42889. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42890. betterShapeHoles[ sIdx ] = [];
  42891. }
  42892. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42893. const sho = newShapeHoles[ sIdx ];
  42894. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42895. const ho = sho[ hIdx ];
  42896. let hole_unassigned = true;
  42897. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42898. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42899. if ( sIdx !== s2Idx ) toChange ++;
  42900. if ( hole_unassigned ) {
  42901. hole_unassigned = false;
  42902. betterShapeHoles[ s2Idx ].push( ho );
  42903. } else {
  42904. ambiguous = true;
  42905. }
  42906. }
  42907. }
  42908. if ( hole_unassigned ) {
  42909. betterShapeHoles[ sIdx ].push( ho );
  42910. }
  42911. }
  42912. }
  42913. if ( toChange > 0 && ambiguous === false ) {
  42914. newShapeHoles = betterShapeHoles;
  42915. }
  42916. }
  42917. let tmpHoles;
  42918. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42919. tmpShape = newShapes[ i ].s;
  42920. shapes.push( tmpShape );
  42921. tmpHoles = newShapeHoles[ i ];
  42922. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42923. tmpShape.holes.push( tmpHoles[ j ].h );
  42924. }
  42925. }
  42926. //log("shape", shapes);
  42927. return shapes;
  42928. }
  42929. }
  42930. /**
  42931. * Abstract base class for controls.
  42932. *
  42933. * @abstract
  42934. * @augments EventDispatcher
  42935. */
  42936. class Controls extends EventDispatcher {
  42937. /**
  42938. * Constructs a new controls instance.
  42939. *
  42940. * @param {Object3D} object - The object that is managed by the controls.
  42941. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42942. */
  42943. constructor( object, domElement = null ) {
  42944. super();
  42945. /**
  42946. * The object that is managed by the controls.
  42947. *
  42948. * @type {Object3D}
  42949. */
  42950. this.object = object;
  42951. /**
  42952. * The HTML element used for event listeners.
  42953. *
  42954. * @type {?HTMLElement}
  42955. * @default null
  42956. */
  42957. this.domElement = domElement;
  42958. /**
  42959. * Whether the controls responds to user input or not.
  42960. *
  42961. * @type {boolean}
  42962. * @default true
  42963. */
  42964. this.enabled = true;
  42965. /**
  42966. * The internal state of the controls.
  42967. *
  42968. * @type {number}
  42969. * @default -1
  42970. */
  42971. this.state = -1;
  42972. /**
  42973. * This object defines the keyboard input of the controls.
  42974. *
  42975. * @type {Object}
  42976. */
  42977. this.keys = {};
  42978. /**
  42979. * This object defines what type of actions are assigned to the available mouse buttons.
  42980. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42981. *
  42982. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42983. */
  42984. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42985. /**
  42986. * This object defines what type of actions are assigned to what kind of touch interaction.
  42987. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42988. *
  42989. * @type {{ONE: ?number, TWO: ?number}}
  42990. */
  42991. this.touches = { ONE: null, TWO: null };
  42992. }
  42993. /**
  42994. * Connects the controls to the DOM. This method has so called "side effects" since
  42995. * it adds the module's event listeners to the DOM.
  42996. *
  42997. * @param {HTMLElement} element - The DOM element to connect to.
  42998. */
  42999. connect( element ) {
  43000. if ( element === undefined ) {
  43001. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  43002. return;
  43003. }
  43004. if ( this.domElement !== null ) this.disconnect();
  43005. this.domElement = element;
  43006. }
  43007. /**
  43008. * Disconnects the controls from the DOM.
  43009. */
  43010. disconnect() {}
  43011. /**
  43012. * Call this method if you no longer want use to the controls. It frees all internal
  43013. * resources and removes all event listeners.
  43014. */
  43015. dispose() {}
  43016. /**
  43017. * Controls should implement this method if they have to update their internal state
  43018. * per simulation step.
  43019. *
  43020. * @param {number} [delta] - The time delta in seconds.
  43021. */
  43022. update( /* delta */ ) {}
  43023. }
  43024. /**
  43025. * Scales the texture as large as possible within its surface without cropping
  43026. * or stretching the texture. The method preserves the original aspect ratio of
  43027. * the texture. Akin to CSS `object-fit: contain`
  43028. *
  43029. * @param {Texture} texture - The texture.
  43030. * @param {number} aspect - The texture's aspect ratio.
  43031. * @return {Texture} The updated texture.
  43032. */
  43033. function contain( texture, aspect ) {
  43034. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  43035. if ( imageAspect > aspect ) {
  43036. texture.repeat.x = 1;
  43037. texture.repeat.y = imageAspect / aspect;
  43038. texture.offset.x = 0;
  43039. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  43040. } else {
  43041. texture.repeat.x = aspect / imageAspect;
  43042. texture.repeat.y = 1;
  43043. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  43044. texture.offset.y = 0;
  43045. }
  43046. return texture;
  43047. }
  43048. /**
  43049. * Scales the texture to the smallest possible size to fill the surface, leaving
  43050. * no empty space. The method preserves the original aspect ratio of the texture.
  43051. * Akin to CSS `object-fit: cover`.
  43052. *
  43053. * @param {Texture} texture - The texture.
  43054. * @param {number} aspect - The texture's aspect ratio.
  43055. * @return {Texture} The updated texture.
  43056. */
  43057. function cover( texture, aspect ) {
  43058. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  43059. if ( imageAspect > aspect ) {
  43060. texture.repeat.x = aspect / imageAspect;
  43061. texture.repeat.y = 1;
  43062. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  43063. texture.offset.y = 0;
  43064. } else {
  43065. texture.repeat.x = 1;
  43066. texture.repeat.y = imageAspect / aspect;
  43067. texture.offset.x = 0;
  43068. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  43069. }
  43070. return texture;
  43071. }
  43072. /**
  43073. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43074. *
  43075. * @param {Texture} texture - The texture.
  43076. * @return {Texture} The updated texture.
  43077. */
  43078. function fill( texture ) {
  43079. texture.repeat.x = 1;
  43080. texture.repeat.y = 1;
  43081. texture.offset.x = 0;
  43082. texture.offset.y = 0;
  43083. return texture;
  43084. }
  43085. /**
  43086. * Determines how many bytes must be used to represent the texture.
  43087. *
  43088. * @param {number} width - The width of the texture.
  43089. * @param {number} height - The height of the texture.
  43090. * @param {number} format - The texture's format.
  43091. * @param {number} type - The texture's type.
  43092. * @return {number} The byte length.
  43093. */
  43094. function getByteLength( width, height, format, type ) {
  43095. const typeByteLength = getTextureTypeByteLength( type );
  43096. switch ( format ) {
  43097. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  43098. case AlphaFormat:
  43099. return width * height;
  43100. case RedFormat:
  43101. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43102. case RedIntegerFormat:
  43103. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43104. case RGFormat:
  43105. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43106. case RGIntegerFormat:
  43107. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43108. case RGBFormat:
  43109. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43110. case RGBAFormat:
  43111. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43112. case RGBAIntegerFormat:
  43113. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43114. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  43115. case RGB_S3TC_DXT1_Format:
  43116. case RGBA_S3TC_DXT1_Format:
  43117. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43118. case RGBA_S3TC_DXT3_Format:
  43119. case RGBA_S3TC_DXT5_Format:
  43120. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43121. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  43122. case RGB_PVRTC_2BPPV1_Format:
  43123. case RGBA_PVRTC_2BPPV1_Format:
  43124. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  43125. case RGB_PVRTC_4BPPV1_Format:
  43126. case RGBA_PVRTC_4BPPV1_Format:
  43127. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  43128. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  43129. case RGB_ETC1_Format:
  43130. case RGB_ETC2_Format:
  43131. case R11_EAC_Format:
  43132. case SIGNED_R11_EAC_Format:
  43133. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43134. case RGBA_ETC2_EAC_Format:
  43135. case RG11_EAC_Format:
  43136. case SIGNED_RG11_EAC_Format:
  43137. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43138. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  43139. case RGBA_ASTC_4x4_Format:
  43140. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43141. case RGBA_ASTC_5x4_Format:
  43142. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43143. case RGBA_ASTC_5x5_Format:
  43144. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43145. case RGBA_ASTC_6x5_Format:
  43146. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43147. case RGBA_ASTC_6x6_Format:
  43148. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43149. case RGBA_ASTC_8x5_Format:
  43150. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43151. case RGBA_ASTC_8x6_Format:
  43152. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43153. case RGBA_ASTC_8x8_Format:
  43154. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43155. case RGBA_ASTC_10x5_Format:
  43156. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43157. case RGBA_ASTC_10x6_Format:
  43158. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43159. case RGBA_ASTC_10x8_Format:
  43160. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43161. case RGBA_ASTC_10x10_Format:
  43162. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43163. case RGBA_ASTC_12x10_Format:
  43164. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43165. case RGBA_ASTC_12x12_Format:
  43166. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  43167. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  43168. case RGBA_BPTC_Format:
  43169. case RGB_BPTC_SIGNED_Format:
  43170. case RGB_BPTC_UNSIGNED_Format:
  43171. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43172. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  43173. case RED_RGTC1_Format:
  43174. case SIGNED_RED_RGTC1_Format:
  43175. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  43176. case RED_GREEN_RGTC2_Format:
  43177. case SIGNED_RED_GREEN_RGTC2_Format:
  43178. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43179. }
  43180. throw new Error(
  43181. `Unable to determine texture byte length for ${format} format.`,
  43182. );
  43183. }
  43184. function getTextureTypeByteLength( type ) {
  43185. switch ( type ) {
  43186. case UnsignedByteType:
  43187. case ByteType:
  43188. return { byteLength: 1, components: 1 };
  43189. case UnsignedShortType:
  43190. case ShortType:
  43191. case HalfFloatType:
  43192. return { byteLength: 2, components: 1 };
  43193. case UnsignedShort4444Type:
  43194. case UnsignedShort5551Type:
  43195. return { byteLength: 2, components: 4 };
  43196. case UnsignedIntType:
  43197. case IntType:
  43198. case FloatType:
  43199. return { byteLength: 4, components: 1 };
  43200. case UnsignedInt5999Type:
  43201. case UnsignedInt101111Type:
  43202. return { byteLength: 4, components: 3 };
  43203. }
  43204. throw new Error( `Unknown texture type ${type}.` );
  43205. }
  43206. /**
  43207. * A class containing utility functions for textures.
  43208. *
  43209. * @hideconstructor
  43210. */
  43211. class TextureUtils {
  43212. /**
  43213. * Scales the texture as large as possible within its surface without cropping
  43214. * or stretching the texture. The method preserves the original aspect ratio of
  43215. * the texture. Akin to CSS `object-fit: contain`
  43216. *
  43217. * @param {Texture} texture - The texture.
  43218. * @param {number} aspect - The texture's aspect ratio.
  43219. * @return {Texture} The updated texture.
  43220. */
  43221. static contain( texture, aspect ) {
  43222. return contain( texture, aspect );
  43223. }
  43224. /**
  43225. * Scales the texture to the smallest possible size to fill the surface, leaving
  43226. * no empty space. The method preserves the original aspect ratio of the texture.
  43227. * Akin to CSS `object-fit: cover`.
  43228. *
  43229. * @param {Texture} texture - The texture.
  43230. * @param {number} aspect - The texture's aspect ratio.
  43231. * @return {Texture} The updated texture.
  43232. */
  43233. static cover( texture, aspect ) {
  43234. return cover( texture, aspect );
  43235. }
  43236. /**
  43237. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43238. *
  43239. * @param {Texture} texture - The texture.
  43240. * @return {Texture} The updated texture.
  43241. */
  43242. static fill( texture ) {
  43243. return fill( texture );
  43244. }
  43245. /**
  43246. * Determines how many bytes must be used to represent the texture.
  43247. *
  43248. * @param {number} width - The width of the texture.
  43249. * @param {number} height - The height of the texture.
  43250. * @param {number} format - The texture's format.
  43251. * @param {number} type - The texture's type.
  43252. * @return {number} The byte length.
  43253. */
  43254. static getByteLength( width, height, format, type ) {
  43255. return getByteLength( width, height, format, type );
  43256. }
  43257. }
  43258. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43259. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43260. revision: REVISION,
  43261. } } ) );
  43262. }
  43263. if ( typeof window !== 'undefined' ) {
  43264. if ( window.__THREE__ ) {
  43265. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43266. } else {
  43267. window.__THREE__ = REVISION;
  43268. }
  43269. }
  43270. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeDepthTexture, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExternalTexture, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HTMLTexture, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialBlending, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoNormalPacking, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NormalGAPacking, NormalRGPacking, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, R11_EAC_Format, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RenderTarget3D, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, ReversedDepthFuncs, RingGeometry, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, cloneUniforms, createCanvasElement, createElementNS, error, getByteLength, getConsoleFunction, getUnlitUniformColorSpace, isTypedArray, log, mergeUniforms, probeAsync, setConsoleFunction, warn, warnOnce, yieldToMain };
粤ICP备19079148号