three.core.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '186dev';
  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( 'THREE.MathUtils: 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( 'THREE.MathUtils: 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( 'THREE.Vector2: 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( 'THREE.Vector2: 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( 'THREE.Vector3: 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( 'THREE.Vector3: 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. * @deprecated
  5088. * @param {number} sx - The amount to scale in the X axis.
  5089. * @param {number} sy - The amount to scale in the Y axis.
  5090. * @return {Matrix3} A reference to this matrix.
  5091. */
  5092. scale( sx, sy ) {
  5093. warnOnce( 'Matrix3: .scale() is deprecated. Use .makeScale() instead.' ); // @deprecated r185
  5094. this.premultiply( _m3.makeScale( sx, sy ) );
  5095. return this;
  5096. }
  5097. /**
  5098. * Rotates this matrix by the given angle.
  5099. *
  5100. * @deprecated
  5101. * @param {number} theta - The rotation in radians.
  5102. * @return {Matrix3} A reference to this matrix.
  5103. */
  5104. rotate( theta ) {
  5105. warnOnce( 'Matrix3: .rotate() is deprecated. Use .makeRotation() instead.' ); // @deprecated r185
  5106. this.premultiply( _m3.makeRotation( - theta ) );
  5107. return this;
  5108. }
  5109. /**
  5110. * Translates this matrix by the given scalar values.
  5111. *
  5112. * @deprecated
  5113. * @param {number} tx - The amount to translate in the X axis.
  5114. * @param {number} ty - The amount to translate in the Y axis.
  5115. * @return {Matrix3} A reference to this matrix.
  5116. */
  5117. translate( tx, ty ) {
  5118. warnOnce( 'Matrix3: .translate() is deprecated. Use .makeTranslation() instead.' ); // @deprecated r185
  5119. this.premultiply( _m3.makeTranslation( tx, ty ) );
  5120. return this;
  5121. }
  5122. // for 2D Transforms
  5123. /**
  5124. * Sets this matrix as a 2D translation transform.
  5125. *
  5126. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  5127. * @param {number} y - The amount to translate in the Y axis.
  5128. * @return {Matrix3} A reference to this matrix.
  5129. */
  5130. makeTranslation( x, y ) {
  5131. if ( x.isVector2 ) {
  5132. this.set(
  5133. 1, 0, x.x,
  5134. 0, 1, x.y,
  5135. 0, 0, 1
  5136. );
  5137. } else {
  5138. this.set(
  5139. 1, 0, x,
  5140. 0, 1, y,
  5141. 0, 0, 1
  5142. );
  5143. }
  5144. return this;
  5145. }
  5146. /**
  5147. * Sets this matrix as a 2D rotational transformation.
  5148. *
  5149. * @param {number} theta - The rotation in radians.
  5150. * @return {Matrix3} A reference to this matrix.
  5151. */
  5152. makeRotation( theta ) {
  5153. // counterclockwise
  5154. const c = Math.cos( theta );
  5155. const s = Math.sin( theta );
  5156. this.set(
  5157. c, - s, 0,
  5158. s, c, 0,
  5159. 0, 0, 1
  5160. );
  5161. return this;
  5162. }
  5163. /**
  5164. * Sets this matrix as a 2D scale transform.
  5165. *
  5166. * @param {number} x - The amount to scale in the X axis.
  5167. * @param {number} y - The amount to scale in the Y axis.
  5168. * @return {Matrix3} A reference to this matrix.
  5169. */
  5170. makeScale( x, y ) {
  5171. this.set(
  5172. x, 0, 0,
  5173. 0, y, 0,
  5174. 0, 0, 1
  5175. );
  5176. return this;
  5177. }
  5178. /**
  5179. * Returns `true` if this matrix is equal with the given one.
  5180. *
  5181. * @param {Matrix3} matrix - The matrix to test for equality.
  5182. * @return {boolean} Whether this matrix is equal with the given one.
  5183. */
  5184. equals( matrix ) {
  5185. const te = this.elements;
  5186. const me = matrix.elements;
  5187. for ( let i = 0; i < 9; i ++ ) {
  5188. if ( te[ i ] !== me[ i ] ) return false;
  5189. }
  5190. return true;
  5191. }
  5192. /**
  5193. * Sets the elements of the matrix from the given array.
  5194. *
  5195. * @param {Array<number>} array - The matrix elements in column-major order.
  5196. * @param {number} [offset=0] - Index of the first element in the array.
  5197. * @return {Matrix3} A reference to this matrix.
  5198. */
  5199. fromArray( array, offset = 0 ) {
  5200. for ( let i = 0; i < 9; i ++ ) {
  5201. this.elements[ i ] = array[ i + offset ];
  5202. }
  5203. return this;
  5204. }
  5205. /**
  5206. * Writes the elements of this matrix to the given array. If no array is provided,
  5207. * the method returns a new instance.
  5208. *
  5209. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5210. * @param {number} [offset=0] - Index of the first element in the array.
  5211. * @return {Array<number>} The matrix elements in column-major order.
  5212. */
  5213. toArray( array = [], offset = 0 ) {
  5214. const te = this.elements;
  5215. array[ offset ] = te[ 0 ];
  5216. array[ offset + 1 ] = te[ 1 ];
  5217. array[ offset + 2 ] = te[ 2 ];
  5218. array[ offset + 3 ] = te[ 3 ];
  5219. array[ offset + 4 ] = te[ 4 ];
  5220. array[ offset + 5 ] = te[ 5 ];
  5221. array[ offset + 6 ] = te[ 6 ];
  5222. array[ offset + 7 ] = te[ 7 ];
  5223. array[ offset + 8 ] = te[ 8 ];
  5224. return array;
  5225. }
  5226. /**
  5227. * Returns a matrix with copied values from this instance.
  5228. *
  5229. * @return {Matrix3} A clone of this instance.
  5230. */
  5231. clone() {
  5232. return new this.constructor().fromArray( this.elements );
  5233. }
  5234. }
  5235. const _m3 = /*@__PURE__*/ new Matrix3();
  5236. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5237. 0.4123908, 0.3575843, 0.1804808,
  5238. 0.2126390, 0.7151687, 0.0721923,
  5239. 0.0193308, 0.1191948, 0.9505322
  5240. );
  5241. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5242. 3.2409699, -1.5373832, -0.4986108,
  5243. -0.9692436, 1.8759675, 0.0415551,
  5244. 0.0556301, -0.203977, 1.0569715
  5245. );
  5246. function createColorManagement() {
  5247. const ColorManagement = {
  5248. enabled: true,
  5249. workingColorSpace: LinearSRGBColorSpace,
  5250. /**
  5251. * Implementations of supported color spaces.
  5252. *
  5253. * Required:
  5254. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5255. * - whitePoint: reference white [ x y ]
  5256. * - transfer: transfer function (pre-defined)
  5257. * - toXYZ: Matrix3 RGB to XYZ transform
  5258. * - fromXYZ: Matrix3 XYZ to RGB transform
  5259. * - luminanceCoefficients: RGB luminance coefficients
  5260. *
  5261. * Optional:
  5262. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5263. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5264. *
  5265. * Reference:
  5266. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5267. */
  5268. spaces: {},
  5269. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5270. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5271. return color;
  5272. }
  5273. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5274. color.r = SRGBToLinear( color.r );
  5275. color.g = SRGBToLinear( color.g );
  5276. color.b = SRGBToLinear( color.b );
  5277. }
  5278. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5279. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5280. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5281. }
  5282. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5283. color.r = LinearToSRGB( color.r );
  5284. color.g = LinearToSRGB( color.g );
  5285. color.b = LinearToSRGB( color.b );
  5286. }
  5287. return color;
  5288. },
  5289. workingToColorSpace: function ( color, targetColorSpace ) {
  5290. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5291. },
  5292. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5293. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5294. },
  5295. getPrimaries: function ( colorSpace ) {
  5296. return this.spaces[ colorSpace ].primaries;
  5297. },
  5298. getTransfer: function ( colorSpace ) {
  5299. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5300. return this.spaces[ colorSpace ].transfer;
  5301. },
  5302. getToneMappingMode: function ( colorSpace ) {
  5303. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5304. },
  5305. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5306. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5307. },
  5308. define: function ( colorSpaces ) {
  5309. Object.assign( this.spaces, colorSpaces );
  5310. },
  5311. // Internal APIs
  5312. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5313. return targetMatrix
  5314. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5315. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5316. },
  5317. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5318. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5319. },
  5320. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5321. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5322. },
  5323. // Deprecated
  5324. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5325. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5326. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5327. },
  5328. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5329. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5330. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5331. },
  5332. };
  5333. /******************************************************************************
  5334. * sRGB definitions
  5335. */
  5336. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5337. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5338. const D65 = [ 0.3127, 0.3290 ];
  5339. ColorManagement.define( {
  5340. [ LinearSRGBColorSpace ]: {
  5341. primaries: REC709_PRIMARIES,
  5342. whitePoint: D65,
  5343. transfer: LinearTransfer,
  5344. toXYZ: LINEAR_REC709_TO_XYZ,
  5345. fromXYZ: XYZ_TO_LINEAR_REC709,
  5346. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5347. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5348. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5349. },
  5350. [ SRGBColorSpace ]: {
  5351. primaries: REC709_PRIMARIES,
  5352. whitePoint: D65,
  5353. transfer: SRGBTransfer,
  5354. toXYZ: LINEAR_REC709_TO_XYZ,
  5355. fromXYZ: XYZ_TO_LINEAR_REC709,
  5356. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5357. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5358. },
  5359. } );
  5360. return ColorManagement;
  5361. }
  5362. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5363. function SRGBToLinear( c ) {
  5364. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5365. }
  5366. function LinearToSRGB( c ) {
  5367. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5368. }
  5369. let _canvas;
  5370. /**
  5371. * A class containing utility functions for images.
  5372. *
  5373. * @hideconstructor
  5374. */
  5375. class ImageUtils {
  5376. /**
  5377. * Returns a data URI containing a representation of the given image.
  5378. *
  5379. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5380. * @param {string} [type='image/png'] - Indicates the image format.
  5381. * @return {string} The data URI.
  5382. */
  5383. static getDataURL( image, type = 'image/png' ) {
  5384. if ( /^data:/i.test( image.src ) ) {
  5385. return image.src;
  5386. }
  5387. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5388. return image.src;
  5389. }
  5390. let canvas;
  5391. if ( image instanceof HTMLCanvasElement ) {
  5392. canvas = image;
  5393. } else {
  5394. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5395. _canvas.width = image.width;
  5396. _canvas.height = image.height;
  5397. const context = _canvas.getContext( '2d' );
  5398. if ( image instanceof ImageData ) {
  5399. context.putImageData( image, 0, 0 );
  5400. } else {
  5401. context.drawImage( image, 0, 0, image.width, image.height );
  5402. }
  5403. canvas = _canvas;
  5404. }
  5405. return canvas.toDataURL( type );
  5406. }
  5407. /**
  5408. * Converts the given sRGB image data to linear color space.
  5409. *
  5410. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5411. * @return {HTMLCanvasElement|Object} The converted image.
  5412. */
  5413. static sRGBToLinear( image ) {
  5414. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5415. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5416. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5417. const canvas = createElementNS( 'canvas' );
  5418. canvas.width = image.width;
  5419. canvas.height = image.height;
  5420. const context = canvas.getContext( '2d' );
  5421. context.drawImage( image, 0, 0, image.width, image.height );
  5422. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5423. const data = imageData.data;
  5424. for ( let i = 0; i < data.length; i ++ ) {
  5425. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5426. }
  5427. context.putImageData( imageData, 0, 0 );
  5428. return canvas;
  5429. } else if ( image.data ) {
  5430. const data = image.data.slice( 0 );
  5431. for ( let i = 0; i < data.length; i ++ ) {
  5432. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5433. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5434. } else {
  5435. // assuming float
  5436. data[ i ] = SRGBToLinear( data[ i ] );
  5437. }
  5438. }
  5439. return {
  5440. data: data,
  5441. width: image.width,
  5442. height: image.height
  5443. };
  5444. } else {
  5445. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5446. return image;
  5447. }
  5448. }
  5449. }
  5450. let _sourceId = 0;
  5451. /**
  5452. * Represents the data source of a texture.
  5453. *
  5454. * The main purpose of this class is to decouple the data definition from the texture
  5455. * definition so the same data can be used with multiple texture instances.
  5456. */
  5457. class Source {
  5458. /**
  5459. * Constructs a new video texture.
  5460. *
  5461. * @param {any} [data=null] - The data definition of a texture.
  5462. */
  5463. constructor( data = null ) {
  5464. /**
  5465. * This flag can be used for type testing.
  5466. *
  5467. * @type {boolean}
  5468. * @readonly
  5469. * @default true
  5470. */
  5471. this.isSource = true;
  5472. /**
  5473. * The ID of the source.
  5474. *
  5475. * @name Source#id
  5476. * @type {number}
  5477. * @readonly
  5478. */
  5479. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5480. /**
  5481. * The UUID of the source.
  5482. *
  5483. * @type {string}
  5484. * @readonly
  5485. */
  5486. this.uuid = generateUUID();
  5487. /**
  5488. * The data definition of a texture.
  5489. *
  5490. * @type {any}
  5491. */
  5492. this.data = data;
  5493. /**
  5494. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5495. * provides more control on how texture data should be processed. When `dataReady` is set
  5496. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5497. * the data into the GPU memory.
  5498. *
  5499. * @type {boolean}
  5500. * @default true
  5501. */
  5502. this.dataReady = true;
  5503. /**
  5504. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5505. *
  5506. * @type {number}
  5507. * @readonly
  5508. * @default 0
  5509. */
  5510. this.version = 0;
  5511. }
  5512. /**
  5513. * Returns the dimensions of the source into the given target vector.
  5514. *
  5515. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5516. * @return {(Vector2|Vector3)} The dimensions of the source.
  5517. */
  5518. getSize( target ) {
  5519. const data = this.data;
  5520. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5521. target.set( data.videoWidth, data.videoHeight, 0 );
  5522. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5523. target.set( data.displayWidth, data.displayHeight, 0 );
  5524. } else if ( data !== null ) {
  5525. target.set( data.width, data.height, data.depth || 0 );
  5526. } else {
  5527. target.set( 0, 0, 0 );
  5528. }
  5529. return target;
  5530. }
  5531. /**
  5532. * When the property is set to `true`, the engine allocates the memory
  5533. * for the texture (if necessary) and triggers the actual texture upload
  5534. * to the GPU next time the source is used.
  5535. *
  5536. * @type {boolean}
  5537. * @default false
  5538. * @param {boolean} value
  5539. */
  5540. set needsUpdate( value ) {
  5541. if ( value === true ) this.version ++;
  5542. }
  5543. /**
  5544. * Serializes the source into JSON.
  5545. *
  5546. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5547. * @return {Object} A JSON object representing the serialized source.
  5548. * @see {@link ObjectLoader#parse}
  5549. */
  5550. toJSON( meta ) {
  5551. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5552. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5553. return meta.images[ this.uuid ];
  5554. }
  5555. const output = {
  5556. uuid: this.uuid,
  5557. url: ''
  5558. };
  5559. const data = this.data;
  5560. if ( data !== null ) {
  5561. let url;
  5562. if ( Array.isArray( data ) ) {
  5563. // cube texture
  5564. url = [];
  5565. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5566. if ( data[ i ].isDataTexture ) {
  5567. url.push( serializeImage( data[ i ].image ) );
  5568. } else {
  5569. url.push( serializeImage( data[ i ] ) );
  5570. }
  5571. }
  5572. } else {
  5573. // texture
  5574. url = serializeImage( data );
  5575. }
  5576. output.url = url;
  5577. }
  5578. if ( ! isRootObject ) {
  5579. meta.images[ this.uuid ] = output;
  5580. }
  5581. return output;
  5582. }
  5583. }
  5584. function serializeImage( image ) {
  5585. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5586. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5587. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5588. // default images
  5589. return ImageUtils.getDataURL( image );
  5590. } else {
  5591. if ( image.data ) {
  5592. // images of DataTexture
  5593. return {
  5594. data: Array.from( image.data ),
  5595. width: image.width,
  5596. height: image.height,
  5597. type: image.data.constructor.name
  5598. };
  5599. } else {
  5600. warn( 'Texture: Unable to serialize Texture.' );
  5601. return {};
  5602. }
  5603. }
  5604. }
  5605. let _textureId = 0;
  5606. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5607. /**
  5608. * Base class for all textures.
  5609. *
  5610. * Note: After the initial use of a texture, its dimensions, format, and type
  5611. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5612. *
  5613. * @augments EventDispatcher
  5614. */
  5615. class Texture extends EventDispatcher {
  5616. /**
  5617. * Constructs a new texture.
  5618. *
  5619. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5620. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5621. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5622. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5623. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5624. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5625. * @param {number} [format=RGBAFormat] - The texture format.
  5626. * @param {number} [type=UnsignedByteType] - The texture type.
  5627. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5628. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5629. */
  5630. 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 ) {
  5631. super();
  5632. /**
  5633. * This flag can be used for type testing.
  5634. *
  5635. * @type {boolean}
  5636. * @readonly
  5637. * @default true
  5638. */
  5639. this.isTexture = true;
  5640. /**
  5641. * The ID of the texture.
  5642. *
  5643. * @name Texture#id
  5644. * @type {number}
  5645. * @readonly
  5646. */
  5647. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5648. /**
  5649. * The UUID of the texture.
  5650. *
  5651. * @type {string}
  5652. * @readonly
  5653. */
  5654. this.uuid = generateUUID();
  5655. /**
  5656. * The name of the texture.
  5657. *
  5658. * @type {string}
  5659. */
  5660. this.name = '';
  5661. /**
  5662. * The data definition of a texture. A reference to the data source can be
  5663. * shared across textures. This is often useful in context of spritesheets
  5664. * where multiple textures render the same data but with different texture
  5665. * transformations.
  5666. *
  5667. * @type {Source}
  5668. */
  5669. this.source = new Source( image );
  5670. /**
  5671. * An array holding user-defined mipmaps.
  5672. *
  5673. * @type {Array<Object>}
  5674. */
  5675. this.mipmaps = [];
  5676. /**
  5677. * How the texture is applied to the object. The value `UVMapping`
  5678. * is the default, where texture or uv coordinates are used to apply the map.
  5679. *
  5680. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5681. * @default UVMapping
  5682. */
  5683. this.mapping = mapping;
  5684. /**
  5685. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5686. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5687. *
  5688. * @type {number}
  5689. * @default 0
  5690. */
  5691. this.channel = 0;
  5692. /**
  5693. * This defines how the texture is wrapped horizontally and corresponds to
  5694. * *U* in UV mapping.
  5695. *
  5696. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5697. * @default ClampToEdgeWrapping
  5698. */
  5699. this.wrapS = wrapS;
  5700. /**
  5701. * This defines how the texture is wrapped horizontally and corresponds to
  5702. * *V* in UV mapping.
  5703. *
  5704. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5705. * @default ClampToEdgeWrapping
  5706. */
  5707. this.wrapT = wrapT;
  5708. /**
  5709. * How the texture is sampled when a texel covers more than one pixel.
  5710. *
  5711. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5712. * @default LinearFilter
  5713. */
  5714. this.magFilter = magFilter;
  5715. /**
  5716. * How the texture is sampled when a texel covers less than one pixel.
  5717. *
  5718. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5719. * @default LinearMipmapLinearFilter
  5720. */
  5721. this.minFilter = minFilter;
  5722. /**
  5723. * The number of samples taken along the axis through the pixel that has the
  5724. * highest density of texels. By default, this value is `1`. A higher value
  5725. * gives a less blurry result than a basic mipmap, at the cost of more
  5726. * texture samples being used.
  5727. *
  5728. * @type {number}
  5729. * @default Texture.DEFAULT_ANISOTROPY
  5730. */
  5731. this.anisotropy = anisotropy;
  5732. /**
  5733. * The format of the texture.
  5734. *
  5735. * @type {number}
  5736. * @default RGBAFormat
  5737. */
  5738. this.format = format;
  5739. /**
  5740. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5741. * defines how the texture data is going to be stored on the GPU.
  5742. *
  5743. * This property allows to overwrite the default format.
  5744. *
  5745. * @type {?string}
  5746. * @default null
  5747. */
  5748. this.internalFormat = null;
  5749. /**
  5750. * The data type of the texture.
  5751. *
  5752. * @type {number}
  5753. * @default UnsignedByteType
  5754. */
  5755. this.type = type;
  5756. /**
  5757. * How much a single repetition of the texture is offset from the beginning,
  5758. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5759. *
  5760. * @type {Vector2}
  5761. * @default (0,0)
  5762. */
  5763. this.offset = new Vector2( 0, 0 );
  5764. /**
  5765. * How many times the texture is repeated across the surface, in each
  5766. * direction U and V. If repeat is set greater than `1` in either direction,
  5767. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5768. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5769. *
  5770. * @type {Vector2}
  5771. * @default (1,1)
  5772. */
  5773. this.repeat = new Vector2( 1, 1 );
  5774. /**
  5775. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5776. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5777. *
  5778. * @type {Vector2}
  5779. * @default (0,0)
  5780. */
  5781. this.center = new Vector2( 0, 0 );
  5782. /**
  5783. * How much the texture is rotated around the center point, in radians.
  5784. * Positive values are counter-clockwise.
  5785. *
  5786. * @type {number}
  5787. * @default 0
  5788. */
  5789. this.rotation = 0;
  5790. /**
  5791. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5792. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5793. * {@link Texture#rotation}, and {@link Texture#center}.
  5794. *
  5795. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5796. *
  5797. * @type {boolean}
  5798. * @default true
  5799. */
  5800. this.matrixAutoUpdate = true;
  5801. /**
  5802. * The uv-transformation matrix of the texture.
  5803. *
  5804. * @type {Matrix3}
  5805. */
  5806. this.matrix = new Matrix3();
  5807. /**
  5808. * Whether to generate mipmaps (if possible) for a texture.
  5809. *
  5810. * Set this to `false` if you are creating mipmaps manually.
  5811. *
  5812. * @type {boolean}
  5813. * @default true
  5814. */
  5815. this.generateMipmaps = true;
  5816. /**
  5817. * If set to `true`, the alpha channel, if present, is multiplied into the
  5818. * color channels when the texture is uploaded to the GPU.
  5819. *
  5820. * Note that this property has no effect when using `ImageBitmap`. You need to
  5821. * configure premultiply alpha on bitmap creation instead.
  5822. *
  5823. * @type {boolean}
  5824. * @default false
  5825. */
  5826. this.premultiplyAlpha = false;
  5827. /**
  5828. * If set to `true`, the texture is flipped along the vertical axis when
  5829. * uploaded to the GPU.
  5830. *
  5831. * Note that this property has no effect when using `ImageBitmap`. You need to
  5832. * configure the flip on bitmap creation instead.
  5833. *
  5834. * @type {boolean}
  5835. * @default true
  5836. */
  5837. this.flipY = true;
  5838. /**
  5839. * Specifies the alignment requirements for the start of each pixel row in memory.
  5840. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5841. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5842. *
  5843. * @type {number}
  5844. * @default 4
  5845. */
  5846. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5847. /**
  5848. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5849. *
  5850. * @type {string}
  5851. * @default NoColorSpace
  5852. */
  5853. this.colorSpace = colorSpace;
  5854. /**
  5855. * An object that can be used to store custom data about the texture. It
  5856. * should not hold references to functions as these will not be cloned.
  5857. *
  5858. * @type {Object}
  5859. */
  5860. this.userData = {};
  5861. /**
  5862. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5863. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5864. *
  5865. * @type {Array<Object>}
  5866. */
  5867. this.updateRanges = [];
  5868. /**
  5869. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5870. *
  5871. * @type {number}
  5872. * @readonly
  5873. * @default 0
  5874. */
  5875. this.version = 0;
  5876. /**
  5877. * A callback function, called when the texture is updated (e.g., when
  5878. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5879. *
  5880. * @type {?Function}
  5881. * @default null
  5882. */
  5883. this.onUpdate = null;
  5884. /**
  5885. * An optional back reference to the textures render target.
  5886. *
  5887. * @type {?(RenderTarget|WebGLRenderTarget)}
  5888. * @default null
  5889. */
  5890. this.renderTarget = null;
  5891. /**
  5892. * Indicates whether a texture belongs to a render target or not.
  5893. *
  5894. * @type {boolean}
  5895. * @readonly
  5896. * @default false
  5897. */
  5898. this.isRenderTargetTexture = false;
  5899. /**
  5900. * Indicates if a texture should be handled like a texture array.
  5901. *
  5902. * @type {boolean}
  5903. * @readonly
  5904. * @default false
  5905. */
  5906. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5907. /**
  5908. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5909. * (only relevant for render target textures).
  5910. *
  5911. * @type {number}
  5912. * @readonly
  5913. * @default 0
  5914. */
  5915. this.pmremVersion = 0;
  5916. /**
  5917. * Whether the texture should use one of the 16 bit integer formats which are normalized
  5918. * to [0, 1] or [-1, 1] (depending on signed/unsigned) when sampled.
  5919. *
  5920. * @type {boolean}
  5921. * @default false
  5922. */
  5923. this.normalized = false;
  5924. }
  5925. /**
  5926. * The width of the texture in pixels.
  5927. */
  5928. get width() {
  5929. return this.source.getSize( _tempVec3 ).x;
  5930. }
  5931. /**
  5932. * The height of the texture in pixels.
  5933. */
  5934. get height() {
  5935. return this.source.getSize( _tempVec3 ).y;
  5936. }
  5937. /**
  5938. * The depth of the texture in pixels.
  5939. */
  5940. get depth() {
  5941. return this.source.getSize( _tempVec3 ).z;
  5942. }
  5943. /**
  5944. * The image object holding the texture data.
  5945. *
  5946. * @type {?Object}
  5947. */
  5948. get image() {
  5949. return this.source.data;
  5950. }
  5951. set image( value ) {
  5952. this.source.data = value;
  5953. }
  5954. /**
  5955. * Updates the texture transformation matrix from the properties {@link Texture#offset},
  5956. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5957. */
  5958. updateMatrix() {
  5959. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5960. }
  5961. /**
  5962. * Adds a range of data in the data texture to be updated on the GPU.
  5963. *
  5964. * @param {number} start - Position at which to start update.
  5965. * @param {number} count - The number of components to update.
  5966. */
  5967. addUpdateRange( start, count ) {
  5968. this.updateRanges.push( { start, count } );
  5969. }
  5970. /**
  5971. * Clears the update ranges.
  5972. */
  5973. clearUpdateRanges() {
  5974. this.updateRanges.length = 0;
  5975. }
  5976. /**
  5977. * Returns a new texture with copied values from this instance.
  5978. *
  5979. * @return {Texture} A clone of this instance.
  5980. */
  5981. clone() {
  5982. return new this.constructor().copy( this );
  5983. }
  5984. /**
  5985. * Copies the values of the given texture to this instance.
  5986. *
  5987. * @param {Texture} source - The texture to copy.
  5988. * @return {Texture} A reference to this instance.
  5989. */
  5990. copy( source ) {
  5991. this.name = source.name;
  5992. this.source = source.source;
  5993. this.mipmaps = source.mipmaps.slice( 0 );
  5994. this.mapping = source.mapping;
  5995. this.channel = source.channel;
  5996. this.wrapS = source.wrapS;
  5997. this.wrapT = source.wrapT;
  5998. this.magFilter = source.magFilter;
  5999. this.minFilter = source.minFilter;
  6000. this.anisotropy = source.anisotropy;
  6001. this.format = source.format;
  6002. this.internalFormat = source.internalFormat;
  6003. this.type = source.type;
  6004. this.normalized = source.normalized;
  6005. this.offset.copy( source.offset );
  6006. this.repeat.copy( source.repeat );
  6007. this.center.copy( source.center );
  6008. this.rotation = source.rotation;
  6009. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6010. this.matrix.copy( source.matrix );
  6011. this.generateMipmaps = source.generateMipmaps;
  6012. this.premultiplyAlpha = source.premultiplyAlpha;
  6013. this.flipY = source.flipY;
  6014. this.unpackAlignment = source.unpackAlignment;
  6015. this.colorSpace = source.colorSpace;
  6016. this.renderTarget = source.renderTarget;
  6017. this.isRenderTargetTexture = source.isRenderTargetTexture;
  6018. this.isArrayTexture = source.isArrayTexture;
  6019. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6020. this.needsUpdate = true;
  6021. return this;
  6022. }
  6023. /**
  6024. * Sets this texture's properties based on `values`.
  6025. * @param {Object} values - A container with texture parameters.
  6026. */
  6027. setValues( values ) {
  6028. for ( const key in values ) {
  6029. const newValue = values[ key ];
  6030. if ( newValue === undefined ) {
  6031. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  6032. continue;
  6033. }
  6034. const currentValue = this[ key ];
  6035. if ( currentValue === undefined ) {
  6036. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  6037. continue;
  6038. }
  6039. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  6040. currentValue.copy( newValue );
  6041. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  6042. currentValue.copy( newValue );
  6043. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  6044. currentValue.copy( newValue );
  6045. } else {
  6046. this[ key ] = newValue;
  6047. }
  6048. }
  6049. }
  6050. /**
  6051. * Serializes the texture into JSON.
  6052. *
  6053. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  6054. * @return {Object} A JSON object representing the serialized texture.
  6055. * @see {@link ObjectLoader#parse}
  6056. */
  6057. toJSON( meta ) {
  6058. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  6059. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6060. return meta.textures[ this.uuid ];
  6061. }
  6062. const output = {
  6063. metadata: {
  6064. version: 4.7,
  6065. type: 'Texture',
  6066. generator: 'Texture.toJSON'
  6067. },
  6068. uuid: this.uuid,
  6069. name: this.name,
  6070. image: this.source.toJSON( meta ).uuid,
  6071. mapping: this.mapping,
  6072. channel: this.channel,
  6073. repeat: [ this.repeat.x, this.repeat.y ],
  6074. offset: [ this.offset.x, this.offset.y ],
  6075. center: [ this.center.x, this.center.y ],
  6076. rotation: this.rotation,
  6077. wrap: [ this.wrapS, this.wrapT ],
  6078. format: this.format,
  6079. internalFormat: this.internalFormat,
  6080. type: this.type,
  6081. normalized: this.normalized,
  6082. colorSpace: this.colorSpace,
  6083. minFilter: this.minFilter,
  6084. magFilter: this.magFilter,
  6085. anisotropy: this.anisotropy,
  6086. flipY: this.flipY,
  6087. generateMipmaps: this.generateMipmaps,
  6088. premultiplyAlpha: this.premultiplyAlpha,
  6089. unpackAlignment: this.unpackAlignment
  6090. };
  6091. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6092. if ( ! isRootObject ) {
  6093. meta.textures[ this.uuid ] = output;
  6094. }
  6095. return output;
  6096. }
  6097. /**
  6098. * Frees the GPU-related resources allocated by this instance. Call this
  6099. * method whenever this instance is no longer used in your app.
  6100. *
  6101. * @fires Texture#dispose
  6102. */
  6103. dispose() {
  6104. /**
  6105. * Fires when the texture has been disposed of.
  6106. *
  6107. * @event Texture#dispose
  6108. * @type {Object}
  6109. */
  6110. this.dispatchEvent( { type: 'dispose' } );
  6111. }
  6112. /**
  6113. * Transforms the given uv vector with the textures uv transformation matrix.
  6114. *
  6115. * @param {Vector2} uv - The uv vector.
  6116. * @return {Vector2} The transformed uv vector.
  6117. */
  6118. transformUv( uv ) {
  6119. if ( this.mapping !== UVMapping ) return uv;
  6120. uv.applyMatrix3( this.matrix );
  6121. if ( uv.x < 0 || uv.x > 1 ) {
  6122. switch ( this.wrapS ) {
  6123. case RepeatWrapping:
  6124. uv.x = uv.x - Math.floor( uv.x );
  6125. break;
  6126. case ClampToEdgeWrapping:
  6127. uv.x = uv.x < 0 ? 0 : 1;
  6128. break;
  6129. case MirroredRepeatWrapping:
  6130. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6131. uv.x = Math.ceil( uv.x ) - uv.x;
  6132. } else {
  6133. uv.x = uv.x - Math.floor( uv.x );
  6134. }
  6135. break;
  6136. }
  6137. }
  6138. if ( uv.y < 0 || uv.y > 1 ) {
  6139. switch ( this.wrapT ) {
  6140. case RepeatWrapping:
  6141. uv.y = uv.y - Math.floor( uv.y );
  6142. break;
  6143. case ClampToEdgeWrapping:
  6144. uv.y = uv.y < 0 ? 0 : 1;
  6145. break;
  6146. case MirroredRepeatWrapping:
  6147. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6148. uv.y = Math.ceil( uv.y ) - uv.y;
  6149. } else {
  6150. uv.y = uv.y - Math.floor( uv.y );
  6151. }
  6152. break;
  6153. }
  6154. }
  6155. if ( this.flipY ) {
  6156. uv.y = 1 - uv.y;
  6157. }
  6158. return uv;
  6159. }
  6160. /**
  6161. * Setting this property to `true` indicates the engine the texture
  6162. * must be updated in the next render. This triggers a texture upload
  6163. * to the GPU and ensures correct texture parameter configuration.
  6164. *
  6165. * @type {boolean}
  6166. * @default false
  6167. * @param {boolean} value
  6168. */
  6169. set needsUpdate( value ) {
  6170. if ( value === true ) {
  6171. this.version ++;
  6172. this.source.needsUpdate = true;
  6173. }
  6174. }
  6175. /**
  6176. * Setting this property to `true` indicates the engine the PMREM
  6177. * must be regenerated.
  6178. *
  6179. * @type {boolean}
  6180. * @default false
  6181. * @param {boolean} value
  6182. */
  6183. set needsPMREMUpdate( value ) {
  6184. if ( value === true ) {
  6185. this.pmremVersion ++;
  6186. }
  6187. }
  6188. }
  6189. /**
  6190. * The default image for all textures.
  6191. *
  6192. * @static
  6193. * @type {?Image}
  6194. * @default null
  6195. */
  6196. Texture.DEFAULT_IMAGE = null;
  6197. /**
  6198. * The default mapping for all textures.
  6199. *
  6200. * @static
  6201. * @type {number}
  6202. * @default UVMapping
  6203. */
  6204. Texture.DEFAULT_MAPPING = UVMapping;
  6205. /**
  6206. * The default anisotropy value for all textures.
  6207. *
  6208. * @static
  6209. * @type {number}
  6210. * @default 1
  6211. */
  6212. Texture.DEFAULT_ANISOTROPY = 1;
  6213. /**
  6214. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6215. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6216. *
  6217. * - A point in 4D space.
  6218. * - A direction and length in 4D space. In three.js the length will
  6219. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6220. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6221. * - Any arbitrary ordered quadruplet of numbers.
  6222. *
  6223. * There are other things a 4D vector can be used to represent, however these
  6224. * are the most common uses in *three.js*.
  6225. *
  6226. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6227. * the corresponding order.
  6228. * ```js
  6229. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6230. *
  6231. * //no arguments; will be initialised to (0, 0, 0, 1)
  6232. * const b = new THREE.Vector4( );
  6233. *
  6234. * const d = a.dot( b );
  6235. * ```
  6236. */
  6237. class Vector4 {
  6238. static {
  6239. /**
  6240. * This flag can be used for type testing.
  6241. *
  6242. * @type {boolean}
  6243. * @readonly
  6244. * @default true
  6245. */
  6246. Vector4.prototype.isVector4 = true;
  6247. }
  6248. /**
  6249. * Constructs a new 4D vector.
  6250. *
  6251. * @param {number} [x=0] - The x value of this vector.
  6252. * @param {number} [y=0] - The y value of this vector.
  6253. * @param {number} [z=0] - The z value of this vector.
  6254. * @param {number} [w=1] - The w value of this vector.
  6255. */
  6256. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6257. /**
  6258. * The x value of this vector.
  6259. *
  6260. * @type {number}
  6261. */
  6262. this.x = x;
  6263. /**
  6264. * The y value of this vector.
  6265. *
  6266. * @type {number}
  6267. */
  6268. this.y = y;
  6269. /**
  6270. * The z value of this vector.
  6271. *
  6272. * @type {number}
  6273. */
  6274. this.z = z;
  6275. /**
  6276. * The w value of this vector.
  6277. *
  6278. * @type {number}
  6279. */
  6280. this.w = w;
  6281. }
  6282. /**
  6283. * Alias for {@link Vector4#z}.
  6284. *
  6285. * @type {number}
  6286. */
  6287. get width() {
  6288. return this.z;
  6289. }
  6290. set width( value ) {
  6291. this.z = value;
  6292. }
  6293. /**
  6294. * Alias for {@link Vector4#w}.
  6295. *
  6296. * @type {number}
  6297. */
  6298. get height() {
  6299. return this.w;
  6300. }
  6301. set height( value ) {
  6302. this.w = value;
  6303. }
  6304. /**
  6305. * Sets the vector components.
  6306. *
  6307. * @param {number} x - The value of the x component.
  6308. * @param {number} y - The value of the y component.
  6309. * @param {number} z - The value of the z component.
  6310. * @param {number} w - The value of the w component.
  6311. * @return {Vector4} A reference to this vector.
  6312. */
  6313. set( x, y, z, w ) {
  6314. this.x = x;
  6315. this.y = y;
  6316. this.z = z;
  6317. this.w = w;
  6318. return this;
  6319. }
  6320. /**
  6321. * Sets the vector components to the same value.
  6322. *
  6323. * @param {number} scalar - The value to set for all vector components.
  6324. * @return {Vector4} A reference to this vector.
  6325. */
  6326. setScalar( scalar ) {
  6327. this.x = scalar;
  6328. this.y = scalar;
  6329. this.z = scalar;
  6330. this.w = scalar;
  6331. return this;
  6332. }
  6333. /**
  6334. * Sets the vector's x component to the given value
  6335. *
  6336. * @param {number} x - The value to set.
  6337. * @return {Vector4} A reference to this vector.
  6338. */
  6339. setX( x ) {
  6340. this.x = x;
  6341. return this;
  6342. }
  6343. /**
  6344. * Sets the vector's y component to the given value
  6345. *
  6346. * @param {number} y - The value to set.
  6347. * @return {Vector4} A reference to this vector.
  6348. */
  6349. setY( y ) {
  6350. this.y = y;
  6351. return this;
  6352. }
  6353. /**
  6354. * Sets the vector's z component to the given value
  6355. *
  6356. * @param {number} z - The value to set.
  6357. * @return {Vector4} A reference to this vector.
  6358. */
  6359. setZ( z ) {
  6360. this.z = z;
  6361. return this;
  6362. }
  6363. /**
  6364. * Sets the vector's w component to the given value
  6365. *
  6366. * @param {number} w - The value to set.
  6367. * @return {Vector4} A reference to this vector.
  6368. */
  6369. setW( w ) {
  6370. this.w = w;
  6371. return this;
  6372. }
  6373. /**
  6374. * Allows to set a vector component with an index.
  6375. *
  6376. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6377. * `2` equals to z, `3` equals to w.
  6378. * @param {number} value - The value to set.
  6379. * @return {Vector4} A reference to this vector.
  6380. */
  6381. setComponent( index, value ) {
  6382. switch ( index ) {
  6383. case 0: this.x = value; break;
  6384. case 1: this.y = value; break;
  6385. case 2: this.z = value; break;
  6386. case 3: this.w = value; break;
  6387. default: throw new Error( 'THREE.Vector4: index is out of range: ' + index );
  6388. }
  6389. return this;
  6390. }
  6391. /**
  6392. * Returns the value of the vector component which matches the given index.
  6393. *
  6394. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6395. * `2` equals to z, `3` equals to w.
  6396. * @return {number} A vector component value.
  6397. */
  6398. getComponent( index ) {
  6399. switch ( index ) {
  6400. case 0: return this.x;
  6401. case 1: return this.y;
  6402. case 2: return this.z;
  6403. case 3: return this.w;
  6404. default: throw new Error( 'THREE.Vector4: index is out of range: ' + index );
  6405. }
  6406. }
  6407. /**
  6408. * Returns a new vector with copied values from this instance.
  6409. *
  6410. * @return {Vector4} A clone of this instance.
  6411. */
  6412. clone() {
  6413. return new this.constructor( this.x, this.y, this.z, this.w );
  6414. }
  6415. /**
  6416. * Copies the values of the given vector to this instance.
  6417. *
  6418. * @param {Vector3|Vector4} v - The vector to copy.
  6419. * @return {Vector4} A reference to this vector.
  6420. */
  6421. copy( v ) {
  6422. this.x = v.x;
  6423. this.y = v.y;
  6424. this.z = v.z;
  6425. this.w = ( v.w !== undefined ) ? v.w : 1;
  6426. return this;
  6427. }
  6428. /**
  6429. * Adds the given vector to this instance.
  6430. *
  6431. * @param {Vector4} v - The vector to add.
  6432. * @return {Vector4} A reference to this vector.
  6433. */
  6434. add( v ) {
  6435. this.x += v.x;
  6436. this.y += v.y;
  6437. this.z += v.z;
  6438. this.w += v.w;
  6439. return this;
  6440. }
  6441. /**
  6442. * Adds the given scalar value to all components of this instance.
  6443. *
  6444. * @param {number} s - The scalar to add.
  6445. * @return {Vector4} A reference to this vector.
  6446. */
  6447. addScalar( s ) {
  6448. this.x += s;
  6449. this.y += s;
  6450. this.z += s;
  6451. this.w += s;
  6452. return this;
  6453. }
  6454. /**
  6455. * Adds the given vectors and stores the result in this instance.
  6456. *
  6457. * @param {Vector4} a - The first vector.
  6458. * @param {Vector4} b - The second vector.
  6459. * @return {Vector4} A reference to this vector.
  6460. */
  6461. addVectors( a, b ) {
  6462. this.x = a.x + b.x;
  6463. this.y = a.y + b.y;
  6464. this.z = a.z + b.z;
  6465. this.w = a.w + b.w;
  6466. return this;
  6467. }
  6468. /**
  6469. * Adds the given vector scaled by the given factor to this instance.
  6470. *
  6471. * @param {Vector4} v - The vector.
  6472. * @param {number} s - The factor that scales `v`.
  6473. * @return {Vector4} A reference to this vector.
  6474. */
  6475. addScaledVector( v, s ) {
  6476. this.x += v.x * s;
  6477. this.y += v.y * s;
  6478. this.z += v.z * s;
  6479. this.w += v.w * s;
  6480. return this;
  6481. }
  6482. /**
  6483. * Subtracts the given vector from this instance.
  6484. *
  6485. * @param {Vector4} v - The vector to subtract.
  6486. * @return {Vector4} A reference to this vector.
  6487. */
  6488. sub( v ) {
  6489. this.x -= v.x;
  6490. this.y -= v.y;
  6491. this.z -= v.z;
  6492. this.w -= v.w;
  6493. return this;
  6494. }
  6495. /**
  6496. * Subtracts the given scalar value from all components of this instance.
  6497. *
  6498. * @param {number} s - The scalar to subtract.
  6499. * @return {Vector4} A reference to this vector.
  6500. */
  6501. subScalar( s ) {
  6502. this.x -= s;
  6503. this.y -= s;
  6504. this.z -= s;
  6505. this.w -= s;
  6506. return this;
  6507. }
  6508. /**
  6509. * Subtracts the given vectors and stores the result in this instance.
  6510. *
  6511. * @param {Vector4} a - The first vector.
  6512. * @param {Vector4} b - The second vector.
  6513. * @return {Vector4} A reference to this vector.
  6514. */
  6515. subVectors( a, b ) {
  6516. this.x = a.x - b.x;
  6517. this.y = a.y - b.y;
  6518. this.z = a.z - b.z;
  6519. this.w = a.w - b.w;
  6520. return this;
  6521. }
  6522. /**
  6523. * Multiplies the given vector with this instance.
  6524. *
  6525. * @param {Vector4} v - The vector to multiply.
  6526. * @return {Vector4} A reference to this vector.
  6527. */
  6528. multiply( v ) {
  6529. this.x *= v.x;
  6530. this.y *= v.y;
  6531. this.z *= v.z;
  6532. this.w *= v.w;
  6533. return this;
  6534. }
  6535. /**
  6536. * Multiplies the given scalar value with all components of this instance.
  6537. *
  6538. * @param {number} scalar - The scalar to multiply.
  6539. * @return {Vector4} A reference to this vector.
  6540. */
  6541. multiplyScalar( scalar ) {
  6542. this.x *= scalar;
  6543. this.y *= scalar;
  6544. this.z *= scalar;
  6545. this.w *= scalar;
  6546. return this;
  6547. }
  6548. /**
  6549. * Multiplies this vector with the given 4x4 matrix.
  6550. *
  6551. * @param {Matrix4} m - The 4x4 matrix.
  6552. * @return {Vector4} A reference to this vector.
  6553. */
  6554. applyMatrix4( m ) {
  6555. const x = this.x, y = this.y, z = this.z, w = this.w;
  6556. const e = m.elements;
  6557. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6558. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6559. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6560. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6561. return this;
  6562. }
  6563. /**
  6564. * Divides this instance by the given vector.
  6565. *
  6566. * @param {Vector4} v - The vector to divide.
  6567. * @return {Vector4} A reference to this vector.
  6568. */
  6569. divide( v ) {
  6570. this.x /= v.x;
  6571. this.y /= v.y;
  6572. this.z /= v.z;
  6573. this.w /= v.w;
  6574. return this;
  6575. }
  6576. /**
  6577. * Divides this vector by the given scalar.
  6578. *
  6579. * @param {number} scalar - The scalar to divide.
  6580. * @return {Vector4} A reference to this vector.
  6581. */
  6582. divideScalar( scalar ) {
  6583. return this.multiplyScalar( 1 / scalar );
  6584. }
  6585. /**
  6586. * Sets the x, y and z components of this
  6587. * vector to the quaternion's axis and w to the angle.
  6588. *
  6589. * @param {Quaternion} q - The Quaternion to set.
  6590. * @return {Vector4} A reference to this vector.
  6591. */
  6592. setAxisAngleFromQuaternion( q ) {
  6593. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6594. // q is assumed to be normalized
  6595. this.w = 2 * Math.acos( q.w );
  6596. const s = Math.sqrt( 1 - q.w * q.w );
  6597. if ( s < 0.0001 ) {
  6598. this.x = 1;
  6599. this.y = 0;
  6600. this.z = 0;
  6601. } else {
  6602. this.x = q.x / s;
  6603. this.y = q.y / s;
  6604. this.z = q.z / s;
  6605. }
  6606. return this;
  6607. }
  6608. /**
  6609. * Sets the x, y and z components of this
  6610. * vector to the axis of rotation and w to the angle.
  6611. *
  6612. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6613. * @return {Vector4} A reference to this vector.
  6614. */
  6615. setAxisAngleFromRotationMatrix( m ) {
  6616. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6617. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6618. let angle, x, y, z; // variables for result
  6619. const epsilon = 0.01, // margin to allow for rounding errors
  6620. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6621. te = m.elements,
  6622. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6623. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6624. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6625. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6626. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6627. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6628. // singularity found
  6629. // first check for identity matrix which must have +1 for all terms
  6630. // in leading diagonal and zero in other terms
  6631. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6632. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6633. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6634. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6635. // this singularity is identity matrix so angle = 0
  6636. this.set( 1, 0, 0, 0 );
  6637. return this; // zero angle, arbitrary axis
  6638. }
  6639. // otherwise this singularity is angle = 180
  6640. angle = Math.PI;
  6641. const xx = ( m11 + 1 ) / 2;
  6642. const yy = ( m22 + 1 ) / 2;
  6643. const zz = ( m33 + 1 ) / 2;
  6644. const xy = ( m12 + m21 ) / 4;
  6645. const xz = ( m13 + m31 ) / 4;
  6646. const yz = ( m23 + m32 ) / 4;
  6647. if ( ( xx > yy ) && ( xx > zz ) ) {
  6648. // m11 is the largest diagonal term
  6649. if ( xx < epsilon ) {
  6650. x = 0;
  6651. y = 0.707106781;
  6652. z = 0.707106781;
  6653. } else {
  6654. x = Math.sqrt( xx );
  6655. y = xy / x;
  6656. z = xz / x;
  6657. }
  6658. } else if ( yy > zz ) {
  6659. // m22 is the largest diagonal term
  6660. if ( yy < epsilon ) {
  6661. x = 0.707106781;
  6662. y = 0;
  6663. z = 0.707106781;
  6664. } else {
  6665. y = Math.sqrt( yy );
  6666. x = xy / y;
  6667. z = yz / y;
  6668. }
  6669. } else {
  6670. // m33 is the largest diagonal term so base result on this
  6671. if ( zz < epsilon ) {
  6672. x = 0.707106781;
  6673. y = 0.707106781;
  6674. z = 0;
  6675. } else {
  6676. z = Math.sqrt( zz );
  6677. x = xz / z;
  6678. y = yz / z;
  6679. }
  6680. }
  6681. this.set( x, y, z, angle );
  6682. return this; // return 180 deg rotation
  6683. }
  6684. // as we have reached here there are no singularities so we can handle normally
  6685. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6686. ( m13 - m31 ) * ( m13 - m31 ) +
  6687. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6688. if ( Math.abs( s ) < 0.001 ) s = 1;
  6689. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6690. // caught by singularity test above, but I've left it in just in case
  6691. this.x = ( m32 - m23 ) / s;
  6692. this.y = ( m13 - m31 ) / s;
  6693. this.z = ( m21 - m12 ) / s;
  6694. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6695. return this;
  6696. }
  6697. /**
  6698. * Sets the vector components to the position elements of the
  6699. * given transformation matrix.
  6700. *
  6701. * @param {Matrix4} m - The 4x4 matrix.
  6702. * @return {Vector4} A reference to this vector.
  6703. */
  6704. setFromMatrixPosition( m ) {
  6705. const e = m.elements;
  6706. this.x = e[ 12 ];
  6707. this.y = e[ 13 ];
  6708. this.z = e[ 14 ];
  6709. this.w = e[ 15 ];
  6710. return this;
  6711. }
  6712. /**
  6713. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6714. * value, replace that value with the corresponding min value.
  6715. *
  6716. * @param {Vector4} v - The vector.
  6717. * @return {Vector4} A reference to this vector.
  6718. */
  6719. min( v ) {
  6720. this.x = Math.min( this.x, v.x );
  6721. this.y = Math.min( this.y, v.y );
  6722. this.z = Math.min( this.z, v.z );
  6723. this.w = Math.min( this.w, v.w );
  6724. return this;
  6725. }
  6726. /**
  6727. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6728. * value, replace that value with the corresponding max value.
  6729. *
  6730. * @param {Vector4} v - The vector.
  6731. * @return {Vector4} A reference to this vector.
  6732. */
  6733. max( v ) {
  6734. this.x = Math.max( this.x, v.x );
  6735. this.y = Math.max( this.y, v.y );
  6736. this.z = Math.max( this.z, v.z );
  6737. this.w = Math.max( this.w, v.w );
  6738. return this;
  6739. }
  6740. /**
  6741. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6742. * value, it is replaced by the corresponding value.
  6743. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6744. * it is replaced by the corresponding value.
  6745. *
  6746. * @param {Vector4} min - The minimum x, y and z values.
  6747. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6748. * @return {Vector4} A reference to this vector.
  6749. */
  6750. clamp( min, max ) {
  6751. // assumes min < max, componentwise
  6752. this.x = clamp( this.x, min.x, max.x );
  6753. this.y = clamp( this.y, min.y, max.y );
  6754. this.z = clamp( this.z, min.z, max.z );
  6755. this.w = clamp( this.w, min.w, max.w );
  6756. return this;
  6757. }
  6758. /**
  6759. * If this vector's x, y, z or w values are greater than the max value, they are
  6760. * replaced by the max value.
  6761. * If this vector's x, y, z or w values are less than the min value, they are
  6762. * replaced by the min value.
  6763. *
  6764. * @param {number} minVal - The minimum value the components will be clamped to.
  6765. * @param {number} maxVal - The maximum value the components will be clamped to.
  6766. * @return {Vector4} A reference to this vector.
  6767. */
  6768. clampScalar( minVal, maxVal ) {
  6769. this.x = clamp( this.x, minVal, maxVal );
  6770. this.y = clamp( this.y, minVal, maxVal );
  6771. this.z = clamp( this.z, minVal, maxVal );
  6772. this.w = clamp( this.w, minVal, maxVal );
  6773. return this;
  6774. }
  6775. /**
  6776. * If this vector's length is greater than the max value, it is replaced by
  6777. * the max value.
  6778. * If this vector's length is less than the min value, it is replaced by the
  6779. * min value.
  6780. *
  6781. * @param {number} min - The minimum value the vector length will be clamped to.
  6782. * @param {number} max - The maximum value the vector length will be clamped to.
  6783. * @return {Vector4} A reference to this vector.
  6784. */
  6785. clampLength( min, max ) {
  6786. const length = this.length();
  6787. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6788. }
  6789. /**
  6790. * The components of this vector are rounded down to the nearest integer value.
  6791. *
  6792. * @return {Vector4} A reference to this vector.
  6793. */
  6794. floor() {
  6795. this.x = Math.floor( this.x );
  6796. this.y = Math.floor( this.y );
  6797. this.z = Math.floor( this.z );
  6798. this.w = Math.floor( this.w );
  6799. return this;
  6800. }
  6801. /**
  6802. * The components of this vector are rounded up to the nearest integer value.
  6803. *
  6804. * @return {Vector4} A reference to this vector.
  6805. */
  6806. ceil() {
  6807. this.x = Math.ceil( this.x );
  6808. this.y = Math.ceil( this.y );
  6809. this.z = Math.ceil( this.z );
  6810. this.w = Math.ceil( this.w );
  6811. return this;
  6812. }
  6813. /**
  6814. * The components of this vector are rounded to the nearest integer value
  6815. *
  6816. * @return {Vector4} A reference to this vector.
  6817. */
  6818. round() {
  6819. this.x = Math.round( this.x );
  6820. this.y = Math.round( this.y );
  6821. this.z = Math.round( this.z );
  6822. this.w = Math.round( this.w );
  6823. return this;
  6824. }
  6825. /**
  6826. * The components of this vector are rounded towards zero (up if negative,
  6827. * down if positive) to an integer value.
  6828. *
  6829. * @return {Vector4} A reference to this vector.
  6830. */
  6831. roundToZero() {
  6832. this.x = Math.trunc( this.x );
  6833. this.y = Math.trunc( this.y );
  6834. this.z = Math.trunc( this.z );
  6835. this.w = Math.trunc( this.w );
  6836. return this;
  6837. }
  6838. /**
  6839. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6840. *
  6841. * @return {Vector4} A reference to this vector.
  6842. */
  6843. negate() {
  6844. this.x = - this.x;
  6845. this.y = - this.y;
  6846. this.z = - this.z;
  6847. this.w = - this.w;
  6848. return this;
  6849. }
  6850. /**
  6851. * Calculates the dot product of the given vector with this instance.
  6852. *
  6853. * @param {Vector4} v - The vector to compute the dot product with.
  6854. * @return {number} The result of the dot product.
  6855. */
  6856. dot( v ) {
  6857. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6858. }
  6859. /**
  6860. * Computes the square of the Euclidean length (straight-line length) from
  6861. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6862. * compare the length squared instead as it is slightly more efficient to calculate.
  6863. *
  6864. * @return {number} The square length of this vector.
  6865. */
  6866. lengthSq() {
  6867. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6868. }
  6869. /**
  6870. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6871. *
  6872. * @return {number} The length of this vector.
  6873. */
  6874. length() {
  6875. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6876. }
  6877. /**
  6878. * Computes the Manhattan length of this vector.
  6879. *
  6880. * @return {number} The length of this vector.
  6881. */
  6882. manhattanLength() {
  6883. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6884. }
  6885. /**
  6886. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6887. * with the same direction as this one, but with a vector length of `1`.
  6888. *
  6889. * @return {Vector4} A reference to this vector.
  6890. */
  6891. normalize() {
  6892. return this.divideScalar( this.length() || 1 );
  6893. }
  6894. /**
  6895. * Sets this vector to a vector with the same direction as this one, but
  6896. * with the specified length.
  6897. *
  6898. * @param {number} length - The new length of this vector.
  6899. * @return {Vector4} A reference to this vector.
  6900. */
  6901. setLength( length ) {
  6902. return this.normalize().multiplyScalar( length );
  6903. }
  6904. /**
  6905. * Linearly interpolates between the given vector and this instance, where
  6906. * alpha is the percent distance along the line - alpha = 0 will be this
  6907. * vector, and alpha = 1 will be the given one.
  6908. *
  6909. * @param {Vector4} v - The vector to interpolate towards.
  6910. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6911. * @return {Vector4} A reference to this vector.
  6912. */
  6913. lerp( v, alpha ) {
  6914. this.x += ( v.x - this.x ) * alpha;
  6915. this.y += ( v.y - this.y ) * alpha;
  6916. this.z += ( v.z - this.z ) * alpha;
  6917. this.w += ( v.w - this.w ) * alpha;
  6918. return this;
  6919. }
  6920. /**
  6921. * Linearly interpolates between the given vectors, where alpha is the percent
  6922. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6923. * be the second one. The result is stored in this instance.
  6924. *
  6925. * @param {Vector4} v1 - The first vector.
  6926. * @param {Vector4} v2 - The second vector.
  6927. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6928. * @return {Vector4} A reference to this vector.
  6929. */
  6930. lerpVectors( v1, v2, alpha ) {
  6931. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6932. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6933. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6934. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6935. return this;
  6936. }
  6937. /**
  6938. * Returns `true` if this vector is equal with the given one.
  6939. *
  6940. * @param {Vector4} v - The vector to test for equality.
  6941. * @return {boolean} Whether this vector is equal with the given one.
  6942. */
  6943. equals( v ) {
  6944. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6945. }
  6946. /**
  6947. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6948. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6949. *
  6950. * @param {Array<number>} array - An array holding the vector component values.
  6951. * @param {number} [offset=0] - The offset into the array.
  6952. * @return {Vector4} A reference to this vector.
  6953. */
  6954. fromArray( array, offset = 0 ) {
  6955. this.x = array[ offset ];
  6956. this.y = array[ offset + 1 ];
  6957. this.z = array[ offset + 2 ];
  6958. this.w = array[ offset + 3 ];
  6959. return this;
  6960. }
  6961. /**
  6962. * Writes the components of this vector to the given array. If no array is provided,
  6963. * the method returns a new instance.
  6964. *
  6965. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6966. * @param {number} [offset=0] - Index of the first element in the array.
  6967. * @return {Array<number>} The vector components.
  6968. */
  6969. toArray( array = [], offset = 0 ) {
  6970. array[ offset ] = this.x;
  6971. array[ offset + 1 ] = this.y;
  6972. array[ offset + 2 ] = this.z;
  6973. array[ offset + 3 ] = this.w;
  6974. return array;
  6975. }
  6976. /**
  6977. * Sets the components of this vector from the given buffer attribute.
  6978. *
  6979. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6980. * @param {number} index - The index into the attribute.
  6981. * @return {Vector4} A reference to this vector.
  6982. */
  6983. fromBufferAttribute( attribute, index ) {
  6984. this.x = attribute.getX( index );
  6985. this.y = attribute.getY( index );
  6986. this.z = attribute.getZ( index );
  6987. this.w = attribute.getW( index );
  6988. return this;
  6989. }
  6990. /**
  6991. * Sets each component of this vector to a pseudo-random value between `0` and
  6992. * `1`, excluding `1`.
  6993. *
  6994. * @return {Vector4} A reference to this vector.
  6995. */
  6996. random() {
  6997. this.x = Math.random();
  6998. this.y = Math.random();
  6999. this.z = Math.random();
  7000. this.w = Math.random();
  7001. return this;
  7002. }
  7003. *[ Symbol.iterator ]() {
  7004. yield this.x;
  7005. yield this.y;
  7006. yield this.z;
  7007. yield this.w;
  7008. }
  7009. }
  7010. /**
  7011. * A render target is a buffer where the video card draws pixels for a scene
  7012. * that is being rendered in the background. It is used in different effects,
  7013. * such as applying postprocessing to a rendered image before displaying it
  7014. * on the screen.
  7015. *
  7016. * @augments EventDispatcher
  7017. */
  7018. class RenderTarget extends EventDispatcher {
  7019. /**
  7020. * Render target options.
  7021. *
  7022. * @typedef {Object} RenderTarget~Options
  7023. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  7024. * @property {number} [magFilter=LinearFilter] - The mag filter.
  7025. * @property {number} [minFilter=LinearFilter] - The min filter.
  7026. * @property {number} [format=RGBAFormat] - The texture format.
  7027. * @property {number} [type=UnsignedByteType] - The texture type.
  7028. * @property {?string} [internalFormat=null] - The texture's internal format.
  7029. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  7030. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  7031. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  7032. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  7033. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  7034. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  7035. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  7036. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  7037. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  7038. * @property {number} [samples=0] - The MSAA samples count.
  7039. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  7040. * @property {number} [depth=1] - The texture depth.
  7041. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering (WebGL OVR_multiview2 extension).
  7042. * @property {boolean} [useArrayDepthTexture=false] - Whether to create the depth texture as an array texture for per-layer depth testing. This is separate from multiview so layered render targets can use array depth without the multiview extension.
  7043. */
  7044. /**
  7045. * Constructs a new render target.
  7046. *
  7047. * @param {number} [width=1] - The width of the render target.
  7048. * @param {number} [height=1] - The height of the render target.
  7049. * @param {RenderTarget~Options} [options] - The configuration object.
  7050. */
  7051. constructor( width = 1, height = 1, options = {} ) {
  7052. super();
  7053. options = Object.assign( {
  7054. generateMipmaps: false,
  7055. internalFormat: null,
  7056. minFilter: LinearFilter,
  7057. depthBuffer: true,
  7058. stencilBuffer: false,
  7059. resolveDepthBuffer: true,
  7060. resolveStencilBuffer: true,
  7061. depthTexture: null,
  7062. samples: 0,
  7063. count: 1,
  7064. depth: 1,
  7065. multiview: false,
  7066. useArrayDepthTexture: false
  7067. }, options );
  7068. /**
  7069. * This flag can be used for type testing.
  7070. *
  7071. * @type {boolean}
  7072. * @readonly
  7073. * @default true
  7074. */
  7075. this.isRenderTarget = true;
  7076. /**
  7077. * The width of the render target.
  7078. *
  7079. * @type {number}
  7080. * @default 1
  7081. */
  7082. this.width = width;
  7083. /**
  7084. * The height of the render target.
  7085. *
  7086. * @type {number}
  7087. * @default 1
  7088. */
  7089. this.height = height;
  7090. /**
  7091. * The depth of the render target.
  7092. *
  7093. * @type {number}
  7094. * @default 1
  7095. */
  7096. this.depth = options.depth;
  7097. /**
  7098. * A rectangular area inside the render target's viewport. Fragments that are
  7099. * outside the area will be discarded.
  7100. *
  7101. * @type {Vector4}
  7102. * @default (0,0,width,height)
  7103. */
  7104. this.scissor = new Vector4( 0, 0, width, height );
  7105. /**
  7106. * Indicates whether the scissor test should be enabled when rendering into
  7107. * this render target or not.
  7108. *
  7109. * @type {boolean}
  7110. * @default false
  7111. */
  7112. this.scissorTest = false;
  7113. /**
  7114. * A rectangular area representing the render target's viewport.
  7115. *
  7116. * @type {Vector4}
  7117. * @default (0,0,width,height)
  7118. */
  7119. this.viewport = new Vector4( 0, 0, width, height );
  7120. /**
  7121. * An array of textures. Each color attachment is represented as a separate texture.
  7122. * Has at least a single entry for the default color attachment.
  7123. *
  7124. * @type {Array<Texture>}
  7125. */
  7126. this.textures = [];
  7127. const image = { width: width, height: height, depth: options.depth };
  7128. const texture = new Texture( image );
  7129. const count = options.count;
  7130. for ( let i = 0; i < count; i ++ ) {
  7131. this.textures[ i ] = texture.clone();
  7132. this.textures[ i ].isRenderTargetTexture = true;
  7133. this.textures[ i ].renderTarget = this;
  7134. }
  7135. this._setTextureOptions( options );
  7136. /**
  7137. * Whether to allocate a depth buffer or not.
  7138. *
  7139. * @type {boolean}
  7140. * @default true
  7141. */
  7142. this.depthBuffer = options.depthBuffer;
  7143. /**
  7144. * Whether to allocate a stencil buffer or not.
  7145. *
  7146. * @type {boolean}
  7147. * @default false
  7148. */
  7149. this.stencilBuffer = options.stencilBuffer;
  7150. /**
  7151. * Whether to resolve the depth buffer or not.
  7152. *
  7153. * @type {boolean}
  7154. * @default true
  7155. */
  7156. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7157. /**
  7158. * Whether to resolve the stencil buffer or not.
  7159. *
  7160. * @type {boolean}
  7161. * @default true
  7162. */
  7163. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7164. this._depthTexture = null;
  7165. this.depthTexture = options.depthTexture;
  7166. /**
  7167. * The number of MSAA samples.
  7168. *
  7169. * A value of `0` disables MSAA.
  7170. *
  7171. * @type {number}
  7172. * @default 0
  7173. */
  7174. this.samples = options.samples;
  7175. /**
  7176. * Whether to this target is used in multiview rendering.
  7177. *
  7178. * @type {boolean}
  7179. * @default false
  7180. */
  7181. this.multiview = options.multiview;
  7182. /**
  7183. * Whether to create the depth texture as an array texture for per-layer depth testing.
  7184. * This is separate from multiview so layered render targets can use array depth without
  7185. * the multiview extension.
  7186. *
  7187. * @type {boolean}
  7188. * @default false
  7189. */
  7190. this.useArrayDepthTexture = options.useArrayDepthTexture;
  7191. }
  7192. _setTextureOptions( options = {} ) {
  7193. const values = {
  7194. minFilter: LinearFilter,
  7195. generateMipmaps: false,
  7196. flipY: false,
  7197. internalFormat: null
  7198. };
  7199. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7200. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7201. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7202. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7203. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7204. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7205. if ( options.format !== undefined ) values.format = options.format;
  7206. if ( options.type !== undefined ) values.type = options.type;
  7207. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7208. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7209. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7210. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7211. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7212. for ( let i = 0; i < this.textures.length; i ++ ) {
  7213. const texture = this.textures[ i ];
  7214. texture.setValues( values );
  7215. }
  7216. }
  7217. /**
  7218. * The texture representing the default color attachment.
  7219. *
  7220. * @type {Texture}
  7221. */
  7222. get texture() {
  7223. return this.textures[ 0 ];
  7224. }
  7225. set texture( value ) {
  7226. this.textures[ 0 ] = value;
  7227. }
  7228. set depthTexture( current ) {
  7229. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7230. if ( current !== null ) current.renderTarget = this;
  7231. this._depthTexture = current;
  7232. }
  7233. /**
  7234. * Instead of saving the depth in a renderbuffer, a texture
  7235. * can be used instead which is useful for further processing
  7236. * e.g. in context of post-processing.
  7237. *
  7238. * @type {?DepthTexture}
  7239. * @default null
  7240. */
  7241. get depthTexture() {
  7242. return this._depthTexture;
  7243. }
  7244. /**
  7245. * Sets the size of this render target.
  7246. *
  7247. * @param {number} width - The width.
  7248. * @param {number} height - The height.
  7249. * @param {number} [depth=1] - The depth.
  7250. */
  7251. setSize( width, height, depth = 1 ) {
  7252. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7253. this.width = width;
  7254. this.height = height;
  7255. this.depth = depth;
  7256. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7257. this.textures[ i ].image.width = width;
  7258. this.textures[ i ].image.height = height;
  7259. this.textures[ i ].image.depth = depth;
  7260. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7261. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7262. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7263. // both are evaluated on each call?
  7264. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7265. }
  7266. }
  7267. this.dispose();
  7268. }
  7269. this.viewport.set( 0, 0, width, height );
  7270. this.scissor.set( 0, 0, width, height );
  7271. }
  7272. /**
  7273. * Returns a new render target with copied values from this instance.
  7274. *
  7275. * @return {RenderTarget} A clone of this instance.
  7276. */
  7277. clone() {
  7278. return new this.constructor().copy( this );
  7279. }
  7280. /**
  7281. * Copies the settings of the given render target. This is a structural copy so
  7282. * no resources are shared between render targets after the copy. That includes
  7283. * all MRT textures and the depth texture.
  7284. *
  7285. * @param {RenderTarget} source - The render target to copy.
  7286. * @return {RenderTarget} A reference to this instance.
  7287. */
  7288. copy( source ) {
  7289. this.width = source.width;
  7290. this.height = source.height;
  7291. this.depth = source.depth;
  7292. this.scissor.copy( source.scissor );
  7293. this.scissorTest = source.scissorTest;
  7294. this.viewport.copy( source.viewport );
  7295. this.textures.length = 0;
  7296. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7297. this.textures[ i ] = source.textures[ i ].clone();
  7298. this.textures[ i ].isRenderTargetTexture = true;
  7299. this.textures[ i ].renderTarget = this;
  7300. // ensure image object is not shared, see #20328
  7301. const image = Object.assign( {}, source.textures[ i ].image );
  7302. this.textures[ i ].source = new Source( image );
  7303. }
  7304. this.depthBuffer = source.depthBuffer;
  7305. this.stencilBuffer = source.stencilBuffer;
  7306. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7307. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7308. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7309. this.samples = source.samples;
  7310. this.multiview = source.multiview;
  7311. this.useArrayDepthTexture = source.useArrayDepthTexture;
  7312. return this;
  7313. }
  7314. /**
  7315. * Frees the GPU-related resources allocated by this instance. Call this
  7316. * method whenever this instance is no longer used in your app.
  7317. *
  7318. * @fires RenderTarget#dispose
  7319. */
  7320. dispose() {
  7321. this.dispatchEvent( { type: 'dispose' } );
  7322. }
  7323. }
  7324. /**
  7325. * A render target used in context of {@link WebGLRenderer}.
  7326. *
  7327. * @augments RenderTarget
  7328. */
  7329. class WebGLRenderTarget extends RenderTarget {
  7330. /**
  7331. * Constructs a new 3D render target.
  7332. *
  7333. * @param {number} [width=1] - The width of the render target.
  7334. * @param {number} [height=1] - The height of the render target.
  7335. * @param {RenderTarget~Options} [options] - The configuration object.
  7336. */
  7337. constructor( width = 1, height = 1, options = {} ) {
  7338. super( width, height, options );
  7339. /**
  7340. * This flag can be used for type testing.
  7341. *
  7342. * @type {boolean}
  7343. * @readonly
  7344. * @default true
  7345. */
  7346. this.isWebGLRenderTarget = true;
  7347. }
  7348. }
  7349. /**
  7350. * Creates an array of textures directly from raw buffer data.
  7351. *
  7352. * @augments Texture
  7353. */
  7354. class DataArrayTexture extends Texture {
  7355. /**
  7356. * Constructs a new data array texture.
  7357. *
  7358. * @param {?TypedArray} [data=null] - The buffer data.
  7359. * @param {number} [width=1] - The width of the texture.
  7360. * @param {number} [height=1] - The height of the texture.
  7361. * @param {number} [depth=1] - The depth of the texture.
  7362. */
  7363. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7364. super( null );
  7365. /**
  7366. * This flag can be used for type testing.
  7367. *
  7368. * @type {boolean}
  7369. * @readonly
  7370. * @default true
  7371. */
  7372. this.isDataArrayTexture = true;
  7373. /**
  7374. * The image definition of a data texture.
  7375. *
  7376. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7377. */
  7378. this.image = { data, width, height, depth };
  7379. /**
  7380. * How the texture is sampled when a texel covers more than one pixel.
  7381. *
  7382. * Overwritten and set to `NearestFilter` by default.
  7383. *
  7384. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7385. * @default NearestFilter
  7386. */
  7387. this.magFilter = NearestFilter;
  7388. /**
  7389. * How the texture is sampled when a texel covers less than one pixel.
  7390. *
  7391. * Overwritten and set to `NearestFilter` by default.
  7392. *
  7393. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7394. * @default NearestFilter
  7395. */
  7396. this.minFilter = NearestFilter;
  7397. /**
  7398. * This defines how the texture is wrapped in the depth and corresponds to
  7399. * *W* in UVW mapping.
  7400. *
  7401. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7402. * @default ClampToEdgeWrapping
  7403. */
  7404. this.wrapR = ClampToEdgeWrapping;
  7405. /**
  7406. * Whether to generate mipmaps (if possible) for a texture.
  7407. *
  7408. * Overwritten and set to `false` by default.
  7409. *
  7410. * @type {boolean}
  7411. * @default false
  7412. */
  7413. this.generateMipmaps = false;
  7414. /**
  7415. * If set to `true`, the texture is flipped along the vertical axis when
  7416. * uploaded to the GPU.
  7417. *
  7418. * Overwritten and set to `false` by default.
  7419. *
  7420. * @type {boolean}
  7421. * @default false
  7422. */
  7423. this.flipY = false;
  7424. /**
  7425. * Specifies the alignment requirements for the start of each pixel row in memory.
  7426. *
  7427. * Overwritten and set to `1` by default.
  7428. *
  7429. * @type {boolean}
  7430. * @default 1
  7431. */
  7432. this.unpackAlignment = 1;
  7433. /**
  7434. * A set of all layers which need to be updated in the texture.
  7435. *
  7436. * @type {Set<number>}
  7437. */
  7438. this.layerUpdates = new Set();
  7439. }
  7440. /**
  7441. * Describes that a specific layer of the texture needs to be updated.
  7442. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7443. * entire data texture array is sent to the GPU. Marking specific
  7444. * layers will only transmit subsets of all mipmaps associated with a
  7445. * specific depth in the array which is often much more performant.
  7446. *
  7447. * @param {number} layerIndex - The layer index that should be updated.
  7448. */
  7449. addLayerUpdate( layerIndex ) {
  7450. this.layerUpdates.add( layerIndex );
  7451. }
  7452. /**
  7453. * Resets the layer updates registry.
  7454. */
  7455. clearLayerUpdates() {
  7456. this.layerUpdates.clear();
  7457. }
  7458. }
  7459. /**
  7460. * An array render target used in context of {@link WebGLRenderer}.
  7461. *
  7462. * @augments WebGLRenderTarget
  7463. */
  7464. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7465. /**
  7466. * Constructs a new array render target.
  7467. *
  7468. * @param {number} [width=1] - The width of the render target.
  7469. * @param {number} [height=1] - The height of the render target.
  7470. * @param {number} [depth=1] - The height of the render target.
  7471. * @param {RenderTarget~Options} [options] - The configuration object.
  7472. */
  7473. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7474. super( width, height, options );
  7475. /**
  7476. * This flag can be used for type testing.
  7477. *
  7478. * @type {boolean}
  7479. * @readonly
  7480. * @default true
  7481. */
  7482. this.isWebGLArrayRenderTarget = true;
  7483. this.depth = depth;
  7484. /**
  7485. * Overwritten with a different texture type.
  7486. *
  7487. * @type {DataArrayTexture}
  7488. */
  7489. this.texture = new DataArrayTexture( null, width, height, depth );
  7490. this._setTextureOptions( options );
  7491. this.texture.isRenderTargetTexture = true;
  7492. }
  7493. }
  7494. /**
  7495. * Creates a three-dimensional texture from raw data, with parameters to
  7496. * divide it into width, height, and depth.
  7497. *
  7498. * @augments Texture
  7499. */
  7500. class Data3DTexture extends Texture {
  7501. /**
  7502. * Constructs a new data array texture.
  7503. *
  7504. * @param {?TypedArray} [data=null] - The buffer data.
  7505. * @param {number} [width=1] - The width of the texture.
  7506. * @param {number} [height=1] - The height of the texture.
  7507. * @param {number} [depth=1] - The depth of the texture.
  7508. */
  7509. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7510. // We're going to add .setXXX() methods for setting properties later.
  7511. // Users can still set in Data3DTexture directly.
  7512. //
  7513. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7514. // texture.anisotropy = 16;
  7515. //
  7516. // See #14839
  7517. super( null );
  7518. /**
  7519. * This flag can be used for type testing.
  7520. *
  7521. * @type {boolean}
  7522. * @readonly
  7523. * @default true
  7524. */
  7525. this.isData3DTexture = true;
  7526. /**
  7527. * The image definition of a data texture.
  7528. *
  7529. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7530. */
  7531. this.image = { data, width, height, depth };
  7532. /**
  7533. * How the texture is sampled when a texel covers more than one pixel.
  7534. *
  7535. * Overwritten and set to `NearestFilter` by default.
  7536. *
  7537. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7538. * @default NearestFilter
  7539. */
  7540. this.magFilter = NearestFilter;
  7541. /**
  7542. * How the texture is sampled when a texel covers less than one pixel.
  7543. *
  7544. * Overwritten and set to `NearestFilter` by default.
  7545. *
  7546. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7547. * @default NearestFilter
  7548. */
  7549. this.minFilter = NearestFilter;
  7550. /**
  7551. * This defines how the texture is wrapped in the depth and corresponds to
  7552. * *W* in UVW mapping.
  7553. *
  7554. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7555. * @default ClampToEdgeWrapping
  7556. */
  7557. this.wrapR = ClampToEdgeWrapping;
  7558. /**
  7559. * Whether to generate mipmaps (if possible) for a texture.
  7560. *
  7561. * Overwritten and set to `false` by default.
  7562. *
  7563. * @type {boolean}
  7564. * @default false
  7565. */
  7566. this.generateMipmaps = false;
  7567. /**
  7568. * If set to `true`, the texture is flipped along the vertical axis when
  7569. * uploaded to the GPU.
  7570. *
  7571. * Overwritten and set to `false` by default.
  7572. *
  7573. * @type {boolean}
  7574. * @default false
  7575. */
  7576. this.flipY = false;
  7577. /**
  7578. * Specifies the alignment requirements for the start of each pixel row in memory.
  7579. *
  7580. * Overwritten and set to `1` by default.
  7581. *
  7582. * @type {boolean}
  7583. * @default 1
  7584. */
  7585. this.unpackAlignment = 1;
  7586. }
  7587. }
  7588. /**
  7589. * A 3D render target used in context of {@link WebGLRenderer}.
  7590. *
  7591. * @augments WebGLRenderTarget
  7592. */
  7593. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7594. /**
  7595. * Constructs a new 3D render target.
  7596. *
  7597. * @param {number} [width=1] - The width of the render target.
  7598. * @param {number} [height=1] - The height of the render target.
  7599. * @param {number} [depth=1] - The height of the render target.
  7600. * @param {RenderTarget~Options} [options] - The configuration object.
  7601. */
  7602. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7603. super( width, height, options );
  7604. /**
  7605. * This flag can be used for type testing.
  7606. *
  7607. * @type {boolean}
  7608. * @readonly
  7609. * @default true
  7610. */
  7611. this.isWebGL3DRenderTarget = true;
  7612. this.depth = depth;
  7613. /**
  7614. * Overwritten with a different texture type.
  7615. *
  7616. * @type {Data3DTexture}
  7617. */
  7618. this.texture = new Data3DTexture( null, width, height, depth );
  7619. this._setTextureOptions( options );
  7620. this.texture.isRenderTargetTexture = true;
  7621. }
  7622. }
  7623. /**
  7624. * Represents a 4x4 matrix.
  7625. *
  7626. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  7627. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  7628. *
  7629. * This allows a 3D vector representing a point in 3D space to undergo
  7630. * transformations such as translation, rotation, shear, scale, reflection,
  7631. * orthogonal or perspective projection and so on, by being multiplied by the
  7632. * matrix. This is known as `applying` the matrix to the vector.
  7633. *
  7634. * A Note on Row-Major and Column-Major Ordering:
  7635. *
  7636. * The constructor and {@link Matrix3#set} method take arguments in
  7637. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  7638. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  7639. * This means that calling:
  7640. * ```js
  7641. * const m = new THREE.Matrix4();
  7642. * m.set( 11, 12, 13, 14,
  7643. * 21, 22, 23, 24,
  7644. * 31, 32, 33, 34,
  7645. * 41, 42, 43, 44 );
  7646. * ```
  7647. * will result in the elements array containing:
  7648. * ```js
  7649. * m.elements = [ 11, 21, 31, 41,
  7650. * 12, 22, 32, 42,
  7651. * 13, 23, 33, 43,
  7652. * 14, 24, 34, 44 ];
  7653. * ```
  7654. * and internally all calculations are performed using column-major ordering.
  7655. * However, as the actual ordering makes no difference mathematically and
  7656. * most people are used to thinking about matrices in row-major order, the
  7657. * three.js documentation shows matrices in row-major order. Just bear in
  7658. * mind that if you are reading the source code, you'll have to take the
  7659. * transpose of any matrices outlined here to make sense of the calculations.
  7660. */
  7661. class Matrix4 {
  7662. static {
  7663. /**
  7664. * This flag can be used for type testing.
  7665. *
  7666. * @type {boolean}
  7667. * @readonly
  7668. * @default true
  7669. */
  7670. Matrix4.prototype.isMatrix4 = true;
  7671. }
  7672. /**
  7673. * Constructs a new 4x4 matrix. The arguments are supposed to be
  7674. * in row-major order. If no arguments are provided, the constructor
  7675. * initializes the matrix as an identity matrix.
  7676. *
  7677. * @param {number} [n11] - 1-1 matrix element.
  7678. * @param {number} [n12] - 1-2 matrix element.
  7679. * @param {number} [n13] - 1-3 matrix element.
  7680. * @param {number} [n14] - 1-4 matrix element.
  7681. * @param {number} [n21] - 2-1 matrix element.
  7682. * @param {number} [n22] - 2-2 matrix element.
  7683. * @param {number} [n23] - 2-3 matrix element.
  7684. * @param {number} [n24] - 2-4 matrix element.
  7685. * @param {number} [n31] - 3-1 matrix element.
  7686. * @param {number} [n32] - 3-2 matrix element.
  7687. * @param {number} [n33] - 3-3 matrix element.
  7688. * @param {number} [n34] - 3-4 matrix element.
  7689. * @param {number} [n41] - 4-1 matrix element.
  7690. * @param {number} [n42] - 4-2 matrix element.
  7691. * @param {number} [n43] - 4-3 matrix element.
  7692. * @param {number} [n44] - 4-4 matrix element.
  7693. */
  7694. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7695. /**
  7696. * A column-major list of matrix values.
  7697. *
  7698. * @type {Array<number>}
  7699. */
  7700. this.elements = [
  7701. 1, 0, 0, 0,
  7702. 0, 1, 0, 0,
  7703. 0, 0, 1, 0,
  7704. 0, 0, 0, 1
  7705. ];
  7706. if ( n11 !== undefined ) {
  7707. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  7708. }
  7709. }
  7710. /**
  7711. * Sets the elements of the matrix.The arguments are supposed to be
  7712. * in row-major order.
  7713. *
  7714. * @param {number} [n11] - 1-1 matrix element.
  7715. * @param {number} [n12] - 1-2 matrix element.
  7716. * @param {number} [n13] - 1-3 matrix element.
  7717. * @param {number} [n14] - 1-4 matrix element.
  7718. * @param {number} [n21] - 2-1 matrix element.
  7719. * @param {number} [n22] - 2-2 matrix element.
  7720. * @param {number} [n23] - 2-3 matrix element.
  7721. * @param {number} [n24] - 2-4 matrix element.
  7722. * @param {number} [n31] - 3-1 matrix element.
  7723. * @param {number} [n32] - 3-2 matrix element.
  7724. * @param {number} [n33] - 3-3 matrix element.
  7725. * @param {number} [n34] - 3-4 matrix element.
  7726. * @param {number} [n41] - 4-1 matrix element.
  7727. * @param {number} [n42] - 4-2 matrix element.
  7728. * @param {number} [n43] - 4-3 matrix element.
  7729. * @param {number} [n44] - 4-4 matrix element.
  7730. * @return {Matrix4} A reference to this matrix.
  7731. */
  7732. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7733. const te = this.elements;
  7734. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  7735. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  7736. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  7737. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  7738. return this;
  7739. }
  7740. /**
  7741. * Sets this matrix to the 4x4 identity matrix.
  7742. *
  7743. * @return {Matrix4} A reference to this matrix.
  7744. */
  7745. identity() {
  7746. this.set(
  7747. 1, 0, 0, 0,
  7748. 0, 1, 0, 0,
  7749. 0, 0, 1, 0,
  7750. 0, 0, 0, 1
  7751. );
  7752. return this;
  7753. }
  7754. /**
  7755. * Returns a matrix with copied values from this instance.
  7756. *
  7757. * @return {Matrix4} A clone of this instance.
  7758. */
  7759. clone() {
  7760. return new Matrix4().fromArray( this.elements );
  7761. }
  7762. /**
  7763. * Copies the values of the given matrix to this instance.
  7764. *
  7765. * @param {Matrix4} m - The matrix to copy.
  7766. * @return {Matrix4} A reference to this matrix.
  7767. */
  7768. copy( m ) {
  7769. const te = this.elements;
  7770. const me = m.elements;
  7771. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  7772. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  7773. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  7774. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  7775. return this;
  7776. }
  7777. /**
  7778. * Copies the translation component of the given matrix
  7779. * into this matrix's translation component.
  7780. *
  7781. * @param {Matrix4} m - The matrix to copy the translation component.
  7782. * @return {Matrix4} A reference to this matrix.
  7783. */
  7784. copyPosition( m ) {
  7785. const te = this.elements, me = m.elements;
  7786. te[ 12 ] = me[ 12 ];
  7787. te[ 13 ] = me[ 13 ];
  7788. te[ 14 ] = me[ 14 ];
  7789. return this;
  7790. }
  7791. /**
  7792. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  7793. *
  7794. * @param {Matrix3} m - The 3x3 matrix.
  7795. * @return {Matrix4} A reference to this matrix.
  7796. */
  7797. setFromMatrix3( m ) {
  7798. const me = m.elements;
  7799. this.set(
  7800. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  7801. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  7802. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  7803. 0, 0, 0, 1
  7804. );
  7805. return this;
  7806. }
  7807. /**
  7808. * Extracts the basis of this matrix into the three axis vectors provided.
  7809. *
  7810. * @param {Vector3} xAxis - The basis's x axis.
  7811. * @param {Vector3} yAxis - The basis's y axis.
  7812. * @param {Vector3} zAxis - The basis's z axis.
  7813. * @return {Matrix4} A reference to this matrix.
  7814. */
  7815. extractBasis( xAxis, yAxis, zAxis ) {
  7816. if ( this.determinantAffine() === 0 ) {
  7817. xAxis.set( 1, 0, 0 );
  7818. yAxis.set( 0, 1, 0 );
  7819. zAxis.set( 0, 0, 1 );
  7820. return this;
  7821. }
  7822. xAxis.setFromMatrixColumn( this, 0 );
  7823. yAxis.setFromMatrixColumn( this, 1 );
  7824. zAxis.setFromMatrixColumn( this, 2 );
  7825. return this;
  7826. }
  7827. /**
  7828. * Sets the given basis vectors to this matrix.
  7829. *
  7830. * @param {Vector3} xAxis - The basis's x axis.
  7831. * @param {Vector3} yAxis - The basis's y axis.
  7832. * @param {Vector3} zAxis - The basis's z axis.
  7833. * @return {Matrix4} A reference to this matrix.
  7834. */
  7835. makeBasis( xAxis, yAxis, zAxis ) {
  7836. this.set(
  7837. xAxis.x, yAxis.x, zAxis.x, 0,
  7838. xAxis.y, yAxis.y, zAxis.y, 0,
  7839. xAxis.z, yAxis.z, zAxis.z, 0,
  7840. 0, 0, 0, 1
  7841. );
  7842. return this;
  7843. }
  7844. /**
  7845. * Extracts the rotation component of the given matrix
  7846. * into this matrix's rotation component.
  7847. *
  7848. * Note: This method does not support reflection matrices.
  7849. *
  7850. * @param {Matrix4} m - The matrix.
  7851. * @return {Matrix4} A reference to this matrix.
  7852. */
  7853. extractRotation( m ) {
  7854. if ( m.determinantAffine() === 0 ) {
  7855. return this.identity();
  7856. }
  7857. const te = this.elements;
  7858. const me = m.elements;
  7859. const scaleX = 1 / _v1$7.setFromMatrixColumn( m, 0 ).length();
  7860. const scaleY = 1 / _v1$7.setFromMatrixColumn( m, 1 ).length();
  7861. const scaleZ = 1 / _v1$7.setFromMatrixColumn( m, 2 ).length();
  7862. te[ 0 ] = me[ 0 ] * scaleX;
  7863. te[ 1 ] = me[ 1 ] * scaleX;
  7864. te[ 2 ] = me[ 2 ] * scaleX;
  7865. te[ 3 ] = 0;
  7866. te[ 4 ] = me[ 4 ] * scaleY;
  7867. te[ 5 ] = me[ 5 ] * scaleY;
  7868. te[ 6 ] = me[ 6 ] * scaleY;
  7869. te[ 7 ] = 0;
  7870. te[ 8 ] = me[ 8 ] * scaleZ;
  7871. te[ 9 ] = me[ 9 ] * scaleZ;
  7872. te[ 10 ] = me[ 10 ] * scaleZ;
  7873. te[ 11 ] = 0;
  7874. te[ 12 ] = 0;
  7875. te[ 13 ] = 0;
  7876. te[ 14 ] = 0;
  7877. te[ 15 ] = 1;
  7878. return this;
  7879. }
  7880. /**
  7881. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  7882. * the rotation specified by the given Euler angles. The rest of
  7883. * the matrix is set to the identity. Depending on the {@link Euler#order},
  7884. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  7885. * for a complete list.
  7886. *
  7887. * @param {Euler} euler - The Euler angles.
  7888. * @return {Matrix4} A reference to this matrix.
  7889. */
  7890. makeRotationFromEuler( euler ) {
  7891. const te = this.elements;
  7892. const x = euler.x, y = euler.y, z = euler.z;
  7893. const a = Math.cos( x ), b = Math.sin( x );
  7894. const c = Math.cos( y ), d = Math.sin( y );
  7895. const e = Math.cos( z ), f = Math.sin( z );
  7896. if ( euler.order === 'XYZ' ) {
  7897. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7898. te[ 0 ] = c * e;
  7899. te[ 4 ] = - c * f;
  7900. te[ 8 ] = d;
  7901. te[ 1 ] = af + be * d;
  7902. te[ 5 ] = ae - bf * d;
  7903. te[ 9 ] = - b * c;
  7904. te[ 2 ] = bf - ae * d;
  7905. te[ 6 ] = be + af * d;
  7906. te[ 10 ] = a * c;
  7907. } else if ( euler.order === 'YXZ' ) {
  7908. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7909. te[ 0 ] = ce + df * b;
  7910. te[ 4 ] = de * b - cf;
  7911. te[ 8 ] = a * d;
  7912. te[ 1 ] = a * f;
  7913. te[ 5 ] = a * e;
  7914. te[ 9 ] = - b;
  7915. te[ 2 ] = cf * b - de;
  7916. te[ 6 ] = df + ce * b;
  7917. te[ 10 ] = a * c;
  7918. } else if ( euler.order === 'ZXY' ) {
  7919. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7920. te[ 0 ] = ce - df * b;
  7921. te[ 4 ] = - a * f;
  7922. te[ 8 ] = de + cf * b;
  7923. te[ 1 ] = cf + de * b;
  7924. te[ 5 ] = a * e;
  7925. te[ 9 ] = df - ce * b;
  7926. te[ 2 ] = - a * d;
  7927. te[ 6 ] = b;
  7928. te[ 10 ] = a * c;
  7929. } else if ( euler.order === 'ZYX' ) {
  7930. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7931. te[ 0 ] = c * e;
  7932. te[ 4 ] = be * d - af;
  7933. te[ 8 ] = ae * d + bf;
  7934. te[ 1 ] = c * f;
  7935. te[ 5 ] = bf * d + ae;
  7936. te[ 9 ] = af * d - be;
  7937. te[ 2 ] = - d;
  7938. te[ 6 ] = b * c;
  7939. te[ 10 ] = a * c;
  7940. } else if ( euler.order === 'YZX' ) {
  7941. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7942. te[ 0 ] = c * e;
  7943. te[ 4 ] = bd - ac * f;
  7944. te[ 8 ] = bc * f + ad;
  7945. te[ 1 ] = f;
  7946. te[ 5 ] = a * e;
  7947. te[ 9 ] = - b * e;
  7948. te[ 2 ] = - d * e;
  7949. te[ 6 ] = ad * f + bc;
  7950. te[ 10 ] = ac - bd * f;
  7951. } else if ( euler.order === 'XZY' ) {
  7952. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7953. te[ 0 ] = c * e;
  7954. te[ 4 ] = - f;
  7955. te[ 8 ] = d * e;
  7956. te[ 1 ] = ac * f + bd;
  7957. te[ 5 ] = a * e;
  7958. te[ 9 ] = ad * f - bc;
  7959. te[ 2 ] = bc * f - ad;
  7960. te[ 6 ] = b * e;
  7961. te[ 10 ] = bd * f + ac;
  7962. }
  7963. // bottom row
  7964. te[ 3 ] = 0;
  7965. te[ 7 ] = 0;
  7966. te[ 11 ] = 0;
  7967. // last column
  7968. te[ 12 ] = 0;
  7969. te[ 13 ] = 0;
  7970. te[ 14 ] = 0;
  7971. te[ 15 ] = 1;
  7972. return this;
  7973. }
  7974. /**
  7975. * Sets the rotation component of this matrix to the rotation specified by
  7976. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  7977. * The rest of the matrix is set to the identity.
  7978. *
  7979. * @param {Quaternion} q - The Quaternion.
  7980. * @return {Matrix4} A reference to this matrix.
  7981. */
  7982. makeRotationFromQuaternion( q ) {
  7983. return this.compose( _zero, q, _one );
  7984. }
  7985. /**
  7986. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  7987. * `target`, and oriented by the up-direction.
  7988. *
  7989. * @param {Vector3} eye - The eye vector.
  7990. * @param {Vector3} target - The target vector.
  7991. * @param {Vector3} up - The up vector.
  7992. * @return {Matrix4} A reference to this matrix.
  7993. */
  7994. lookAt( eye, target, up ) {
  7995. const te = this.elements;
  7996. _z.subVectors( eye, target );
  7997. if ( _z.lengthSq() === 0 ) {
  7998. // eye and target are in the same position
  7999. _z.z = 1;
  8000. }
  8001. _z.normalize();
  8002. _x.crossVectors( up, _z );
  8003. if ( _x.lengthSq() === 0 ) {
  8004. // up and z are parallel
  8005. if ( Math.abs( up.z ) === 1 ) {
  8006. _z.x += 0.0001;
  8007. } else {
  8008. _z.z += 0.0001;
  8009. }
  8010. _z.normalize();
  8011. _x.crossVectors( up, _z );
  8012. }
  8013. _x.normalize();
  8014. _y.crossVectors( _z, _x );
  8015. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8016. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8017. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8018. return this;
  8019. }
  8020. /**
  8021. * Post-multiplies this matrix by the given 4x4 matrix.
  8022. *
  8023. * @param {Matrix4} m - The matrix to multiply with.
  8024. * @return {Matrix4} A reference to this matrix.
  8025. */
  8026. multiply( m ) {
  8027. return this.multiplyMatrices( this, m );
  8028. }
  8029. /**
  8030. * Pre-multiplies this matrix by the given 4x4 matrix.
  8031. *
  8032. * @param {Matrix4} m - The matrix to multiply with.
  8033. * @return {Matrix4} A reference to this matrix.
  8034. */
  8035. premultiply( m ) {
  8036. return this.multiplyMatrices( m, this );
  8037. }
  8038. /**
  8039. * Multiples the given 4x4 matrices and stores the result
  8040. * in this matrix.
  8041. *
  8042. * @param {Matrix4} a - The first matrix.
  8043. * @param {Matrix4} b - The second matrix.
  8044. * @return {Matrix4} A reference to this matrix.
  8045. */
  8046. multiplyMatrices( a, b ) {
  8047. const ae = a.elements;
  8048. const be = b.elements;
  8049. const te = this.elements;
  8050. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8051. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8052. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8053. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8054. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8055. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8056. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8057. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8058. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8059. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8060. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8061. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8062. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8063. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8064. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8065. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8066. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8067. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8068. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8069. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8070. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8071. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8072. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8073. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8074. return this;
  8075. }
  8076. /**
  8077. * Multiplies every component of the matrix by the given scalar.
  8078. *
  8079. * @param {number} s - The scalar.
  8080. * @return {Matrix4} A reference to this matrix.
  8081. */
  8082. multiplyScalar( s ) {
  8083. const te = this.elements;
  8084. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8085. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8086. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8087. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8088. return this;
  8089. }
  8090. /**
  8091. * Computes and returns the determinant of this matrix.
  8092. *
  8093. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  8094. *
  8095. * @return {number} The determinant.
  8096. */
  8097. determinant() {
  8098. const te = this.elements;
  8099. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8100. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8101. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8102. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8103. const t11 = n23 * n34 - n24 * n33;
  8104. const t12 = n22 * n34 - n24 * n32;
  8105. const t13 = n22 * n33 - n23 * n32;
  8106. const t21 = n21 * n34 - n24 * n31;
  8107. const t22 = n21 * n33 - n23 * n31;
  8108. const t23 = n21 * n32 - n22 * n31;
  8109. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  8110. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  8111. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  8112. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  8113. }
  8114. /**
  8115. * Computes and returns the determinant of the 4x4 matrix, but assumes the
  8116. * matrix is affine, saving some computations.
  8117. *
  8118. * For affine matrices (like an object's world matrix), this value equals the
  8119. * full 4x4 {@link Matrix4#determinant} but is cheaper to compute.
  8120. *
  8121. * Assumes the bottom row is [0, 0, 0, 1].
  8122. *
  8123. * @return {number} The determinant of the matrix.
  8124. */
  8125. determinantAffine() {
  8126. const te = this.elements;
  8127. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ];
  8128. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ];
  8129. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ];
  8130. return n11 * ( n22 * n33 - n23 * n32 ) -
  8131. n12 * ( n21 * n33 - n23 * n31 ) +
  8132. n13 * ( n21 * n32 - n22 * n31 );
  8133. }
  8134. /**
  8135. * Transposes this matrix in place.
  8136. *
  8137. * @return {Matrix4} A reference to this matrix.
  8138. */
  8139. transpose() {
  8140. const te = this.elements;
  8141. let tmp;
  8142. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8143. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8144. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8145. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8146. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8147. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8148. return this;
  8149. }
  8150. /**
  8151. * Sets the position component for this matrix from the given vector,
  8152. * without affecting the rest of the matrix.
  8153. *
  8154. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  8155. * @param {number} y - The y component of the vector.
  8156. * @param {number} z - The z component of the vector.
  8157. * @return {Matrix4} A reference to this matrix.
  8158. */
  8159. setPosition( x, y, z ) {
  8160. const te = this.elements;
  8161. if ( x.isVector3 ) {
  8162. te[ 12 ] = x.x;
  8163. te[ 13 ] = x.y;
  8164. te[ 14 ] = x.z;
  8165. } else {
  8166. te[ 12 ] = x;
  8167. te[ 13 ] = y;
  8168. te[ 14 ] = z;
  8169. }
  8170. return this;
  8171. }
  8172. /**
  8173. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  8174. * You can not invert with a determinant of zero. If you attempt this, the method produces
  8175. * a zero matrix instead.
  8176. *
  8177. * @return {Matrix4} A reference to this matrix.
  8178. */
  8179. invert() {
  8180. // based on https://github.com/toji/gl-matrix
  8181. const te = this.elements,
  8182. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  8183. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  8184. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  8185. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  8186. t1 = n11 * n22 - n21 * n12,
  8187. t2 = n11 * n32 - n31 * n12,
  8188. t3 = n11 * n42 - n41 * n12,
  8189. t4 = n21 * n32 - n31 * n22,
  8190. t5 = n21 * n42 - n41 * n22,
  8191. t6 = n31 * n42 - n41 * n32,
  8192. t7 = n13 * n24 - n23 * n14,
  8193. t8 = n13 * n34 - n33 * n14,
  8194. t9 = n13 * n44 - n43 * n14,
  8195. t10 = n23 * n34 - n33 * n24,
  8196. t11 = n23 * n44 - n43 * n24,
  8197. t12 = n33 * n44 - n43 * n34;
  8198. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  8199. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  8200. const detInv = 1 / det;
  8201. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  8202. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  8203. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  8204. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  8205. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  8206. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  8207. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  8208. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  8209. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  8210. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  8211. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  8212. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  8213. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  8214. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  8215. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  8216. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  8217. return this;
  8218. }
  8219. /**
  8220. * Multiplies the columns of this matrix by the given vector.
  8221. *
  8222. * @param {Vector3} v - The scale vector.
  8223. * @return {Matrix4} A reference to this matrix.
  8224. */
  8225. scale( v ) {
  8226. const te = this.elements;
  8227. const x = v.x, y = v.y, z = v.z;
  8228. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8229. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8230. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8231. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  8232. return this;
  8233. }
  8234. /**
  8235. * Gets the maximum scale value of the three axes.
  8236. *
  8237. * @return {number} The maximum scale.
  8238. */
  8239. getMaxScaleOnAxis() {
  8240. const te = this.elements;
  8241. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  8242. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  8243. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  8244. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  8245. }
  8246. /**
  8247. * Sets this matrix as a translation transform from the given vector.
  8248. *
  8249. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  8250. * @param {number} y - The amount to translate in the Y axis.
  8251. * @param {number} z - The amount to translate in the z axis.
  8252. * @return {Matrix4} A reference to this matrix.
  8253. */
  8254. makeTranslation( x, y, z ) {
  8255. if ( x.isVector3 ) {
  8256. this.set(
  8257. 1, 0, 0, x.x,
  8258. 0, 1, 0, x.y,
  8259. 0, 0, 1, x.z,
  8260. 0, 0, 0, 1
  8261. );
  8262. } else {
  8263. this.set(
  8264. 1, 0, 0, x,
  8265. 0, 1, 0, y,
  8266. 0, 0, 1, z,
  8267. 0, 0, 0, 1
  8268. );
  8269. }
  8270. return this;
  8271. }
  8272. /**
  8273. * Sets this matrix as a rotational transformation around the X axis by
  8274. * the given angle.
  8275. *
  8276. * @param {number} theta - The rotation in radians.
  8277. * @return {Matrix4} A reference to this matrix.
  8278. */
  8279. makeRotationX( theta ) {
  8280. const c = Math.cos( theta ), s = Math.sin( theta );
  8281. this.set(
  8282. 1, 0, 0, 0,
  8283. 0, c, - s, 0,
  8284. 0, s, c, 0,
  8285. 0, 0, 0, 1
  8286. );
  8287. return this;
  8288. }
  8289. /**
  8290. * Sets this matrix as a rotational transformation around the Y axis by
  8291. * the given angle.
  8292. *
  8293. * @param {number} theta - The rotation in radians.
  8294. * @return {Matrix4} A reference to this matrix.
  8295. */
  8296. makeRotationY( theta ) {
  8297. const c = Math.cos( theta ), s = Math.sin( theta );
  8298. this.set(
  8299. c, 0, s, 0,
  8300. 0, 1, 0, 0,
  8301. - s, 0, c, 0,
  8302. 0, 0, 0, 1
  8303. );
  8304. return this;
  8305. }
  8306. /**
  8307. * Sets this matrix as a rotational transformation around the Z axis by
  8308. * the given angle.
  8309. *
  8310. * @param {number} theta - The rotation in radians.
  8311. * @return {Matrix4} A reference to this matrix.
  8312. */
  8313. makeRotationZ( theta ) {
  8314. const c = Math.cos( theta ), s = Math.sin( theta );
  8315. this.set(
  8316. c, - s, 0, 0,
  8317. s, c, 0, 0,
  8318. 0, 0, 1, 0,
  8319. 0, 0, 0, 1
  8320. );
  8321. return this;
  8322. }
  8323. /**
  8324. * Sets this matrix as a rotational transformation around the given axis by
  8325. * the given angle.
  8326. *
  8327. * This is a somewhat controversial but mathematically sound alternative to
  8328. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  8329. *
  8330. * @param {Vector3} axis - The normalized rotation axis.
  8331. * @param {number} angle - The rotation in radians.
  8332. * @return {Matrix4} A reference to this matrix.
  8333. */
  8334. makeRotationAxis( axis, angle ) {
  8335. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  8336. const c = Math.cos( angle );
  8337. const s = Math.sin( angle );
  8338. const t = 1 - c;
  8339. const x = axis.x, y = axis.y, z = axis.z;
  8340. const tx = t * x, ty = t * y;
  8341. this.set(
  8342. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  8343. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  8344. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  8345. 0, 0, 0, 1
  8346. );
  8347. return this;
  8348. }
  8349. /**
  8350. * Sets this matrix as a scale transformation.
  8351. *
  8352. * @param {number} x - The amount to scale in the X axis.
  8353. * @param {number} y - The amount to scale in the Y axis.
  8354. * @param {number} z - The amount to scale in the Z axis.
  8355. * @return {Matrix4} A reference to this matrix.
  8356. */
  8357. makeScale( x, y, z ) {
  8358. this.set(
  8359. x, 0, 0, 0,
  8360. 0, y, 0, 0,
  8361. 0, 0, z, 0,
  8362. 0, 0, 0, 1
  8363. );
  8364. return this;
  8365. }
  8366. /**
  8367. * Sets this matrix as a shear transformation.
  8368. *
  8369. * @param {number} xy - The amount to shear X by Y.
  8370. * @param {number} xz - The amount to shear X by Z.
  8371. * @param {number} yx - The amount to shear Y by X.
  8372. * @param {number} yz - The amount to shear Y by Z.
  8373. * @param {number} zx - The amount to shear Z by X.
  8374. * @param {number} zy - The amount to shear Z by Y.
  8375. * @return {Matrix4} A reference to this matrix.
  8376. */
  8377. makeShear( xy, xz, yx, yz, zx, zy ) {
  8378. this.set(
  8379. 1, yx, zx, 0,
  8380. xy, 1, zy, 0,
  8381. xz, yz, 1, 0,
  8382. 0, 0, 0, 1
  8383. );
  8384. return this;
  8385. }
  8386. /**
  8387. * Sets this matrix to the transformation composed of the given position,
  8388. * rotation (Quaternion) and scale.
  8389. *
  8390. * @param {Vector3} position - The position vector.
  8391. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8392. * @param {Vector3} scale - The scale vector.
  8393. * @return {Matrix4} A reference to this matrix.
  8394. */
  8395. compose( position, quaternion, scale ) {
  8396. const te = this.elements;
  8397. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  8398. const x2 = x + x, y2 = y + y, z2 = z + z;
  8399. const xx = x * x2, xy = x * y2, xz = x * z2;
  8400. const yy = y * y2, yz = y * z2, zz = z * z2;
  8401. const wx = w * x2, wy = w * y2, wz = w * z2;
  8402. const sx = scale.x, sy = scale.y, sz = scale.z;
  8403. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  8404. te[ 1 ] = ( xy + wz ) * sx;
  8405. te[ 2 ] = ( xz - wy ) * sx;
  8406. te[ 3 ] = 0;
  8407. te[ 4 ] = ( xy - wz ) * sy;
  8408. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  8409. te[ 6 ] = ( yz + wx ) * sy;
  8410. te[ 7 ] = 0;
  8411. te[ 8 ] = ( xz + wy ) * sz;
  8412. te[ 9 ] = ( yz - wx ) * sz;
  8413. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  8414. te[ 11 ] = 0;
  8415. te[ 12 ] = position.x;
  8416. te[ 13 ] = position.y;
  8417. te[ 14 ] = position.z;
  8418. te[ 15 ] = 1;
  8419. return this;
  8420. }
  8421. /**
  8422. * Decomposes this matrix into its position, rotation and scale components
  8423. * and provides the result in the given objects.
  8424. *
  8425. * Note: Not all matrices are decomposable in this way. For example, if an
  8426. * object has a non-uniformly scaled parent, then the object's world matrix
  8427. * may not be decomposable, and this method may not be appropriate.
  8428. *
  8429. * @param {Vector3} position - The position vector.
  8430. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8431. * @param {Vector3} scale - The scale vector.
  8432. * @return {Matrix4} A reference to this matrix.
  8433. */
  8434. decompose( position, quaternion, scale ) {
  8435. const te = this.elements;
  8436. position.x = te[ 12 ];
  8437. position.y = te[ 13 ];
  8438. position.z = te[ 14 ];
  8439. const det = this.determinantAffine();
  8440. if ( det === 0 ) {
  8441. scale.set( 1, 1, 1 );
  8442. quaternion.identity();
  8443. return this;
  8444. }
  8445. let sx = _v1$7.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  8446. const sy = _v1$7.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  8447. const sz = _v1$7.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  8448. // if determinant is negative, we need to invert one scale
  8449. if ( det < 0 ) sx = - sx;
  8450. // scale the rotation part
  8451. _m1$2.copy( this );
  8452. const invSX = 1 / sx;
  8453. const invSY = 1 / sy;
  8454. const invSZ = 1 / sz;
  8455. _m1$2.elements[ 0 ] *= invSX;
  8456. _m1$2.elements[ 1 ] *= invSX;
  8457. _m1$2.elements[ 2 ] *= invSX;
  8458. _m1$2.elements[ 4 ] *= invSY;
  8459. _m1$2.elements[ 5 ] *= invSY;
  8460. _m1$2.elements[ 6 ] *= invSY;
  8461. _m1$2.elements[ 8 ] *= invSZ;
  8462. _m1$2.elements[ 9 ] *= invSZ;
  8463. _m1$2.elements[ 10 ] *= invSZ;
  8464. quaternion.setFromRotationMatrix( _m1$2 );
  8465. scale.x = sx;
  8466. scale.y = sy;
  8467. scale.z = sz;
  8468. return this;
  8469. }
  8470. /**
  8471. * Creates a perspective projection matrix. This is used internally by
  8472. * {@link PerspectiveCamera#updateProjectionMatrix}.
  8473. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8474. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8475. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8476. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8477. * @param {number} near - The distance from the camera to the near plane.
  8478. * @param {number} far - The distance from the camera to the far plane.
  8479. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8480. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8481. * @return {Matrix4} A reference to this matrix.
  8482. */
  8483. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8484. const te = this.elements;
  8485. const x = 2 * near / ( right - left );
  8486. const y = 2 * near / ( top - bottom );
  8487. const a = ( right + left ) / ( right - left );
  8488. const b = ( top + bottom ) / ( top - bottom );
  8489. let c, d;
  8490. if ( reversedDepth ) {
  8491. c = near / ( far - near );
  8492. d = ( far * near ) / ( far - near );
  8493. } else {
  8494. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8495. c = - ( far + near ) / ( far - near );
  8496. d = ( -2 * far * near ) / ( far - near );
  8497. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8498. c = - far / ( far - near );
  8499. d = ( - far * near ) / ( far - near );
  8500. } else {
  8501. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  8502. }
  8503. }
  8504. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  8505. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  8506. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8507. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  8508. return this;
  8509. }
  8510. /**
  8511. * Creates a orthographic projection matrix. This is used internally by
  8512. * {@link OrthographicCamera#updateProjectionMatrix}.
  8513. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8514. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8515. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8516. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8517. * @param {number} near - The distance from the camera to the near plane.
  8518. * @param {number} far - The distance from the camera to the far plane.
  8519. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8520. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8521. * @return {Matrix4} A reference to this matrix.
  8522. */
  8523. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8524. const te = this.elements;
  8525. const x = 2 / ( right - left );
  8526. const y = 2 / ( top - bottom );
  8527. const a = - ( right + left ) / ( right - left );
  8528. const b = - ( top + bottom ) / ( top - bottom );
  8529. let c, d;
  8530. if ( reversedDepth ) {
  8531. c = 1 / ( far - near );
  8532. d = far / ( far - near );
  8533. } else {
  8534. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8535. c = -2 / ( far - near );
  8536. d = - ( far + near ) / ( far - near );
  8537. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8538. c = -1 / ( far - near );
  8539. d = - near / ( far - near );
  8540. } else {
  8541. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  8542. }
  8543. }
  8544. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  8545. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  8546. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8547. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  8548. return this;
  8549. }
  8550. /**
  8551. * Returns `true` if this matrix is equal with the given one.
  8552. *
  8553. * @param {Matrix4} matrix - The matrix to test for equality.
  8554. * @return {boolean} Whether this matrix is equal with the given one.
  8555. */
  8556. equals( matrix ) {
  8557. const te = this.elements;
  8558. const me = matrix.elements;
  8559. for ( let i = 0; i < 16; i ++ ) {
  8560. if ( te[ i ] !== me[ i ] ) return false;
  8561. }
  8562. return true;
  8563. }
  8564. /**
  8565. * Sets the elements of the matrix from the given array.
  8566. *
  8567. * @param {Array<number>} array - The matrix elements in column-major order.
  8568. * @param {number} [offset=0] - Index of the first element in the array.
  8569. * @return {Matrix4} A reference to this matrix.
  8570. */
  8571. fromArray( array, offset = 0 ) {
  8572. for ( let i = 0; i < 16; i ++ ) {
  8573. this.elements[ i ] = array[ i + offset ];
  8574. }
  8575. return this;
  8576. }
  8577. /**
  8578. * Writes the elements of this matrix to the given array. If no array is provided,
  8579. * the method returns a new instance.
  8580. *
  8581. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  8582. * @param {number} [offset=0] - Index of the first element in the array.
  8583. * @return {Array<number>} The matrix elements in column-major order.
  8584. */
  8585. toArray( array = [], offset = 0 ) {
  8586. const te = this.elements;
  8587. array[ offset ] = te[ 0 ];
  8588. array[ offset + 1 ] = te[ 1 ];
  8589. array[ offset + 2 ] = te[ 2 ];
  8590. array[ offset + 3 ] = te[ 3 ];
  8591. array[ offset + 4 ] = te[ 4 ];
  8592. array[ offset + 5 ] = te[ 5 ];
  8593. array[ offset + 6 ] = te[ 6 ];
  8594. array[ offset + 7 ] = te[ 7 ];
  8595. array[ offset + 8 ] = te[ 8 ];
  8596. array[ offset + 9 ] = te[ 9 ];
  8597. array[ offset + 10 ] = te[ 10 ];
  8598. array[ offset + 11 ] = te[ 11 ];
  8599. array[ offset + 12 ] = te[ 12 ];
  8600. array[ offset + 13 ] = te[ 13 ];
  8601. array[ offset + 14 ] = te[ 14 ];
  8602. array[ offset + 15 ] = te[ 15 ];
  8603. return array;
  8604. }
  8605. }
  8606. const _v1$7 = /*@__PURE__*/ new Vector3();
  8607. const _m1$2 = /*@__PURE__*/ new Matrix4();
  8608. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  8609. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  8610. const _x = /*@__PURE__*/ new Vector3();
  8611. const _y = /*@__PURE__*/ new Vector3();
  8612. const _z = /*@__PURE__*/ new Vector3();
  8613. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  8614. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  8615. /**
  8616. * A class representing Euler angles.
  8617. *
  8618. * Euler angles describe a rotational transformation by rotating an object on
  8619. * its various axes in specified amounts per axis, and a specified axis
  8620. * order.
  8621. *
  8622. * Iterating through an instance will yield its components (x, y, z,
  8623. * order) in the corresponding order.
  8624. *
  8625. * ```js
  8626. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  8627. * const b = new THREE.Vector3( 1, 0, 1 );
  8628. * b.applyEuler(a);
  8629. * ```
  8630. */
  8631. class Euler {
  8632. /**
  8633. * Constructs a new euler instance.
  8634. *
  8635. * @param {number} [x=0] - The angle of the x axis in radians.
  8636. * @param {number} [y=0] - The angle of the y axis in radians.
  8637. * @param {number} [z=0] - The angle of the z axis in radians.
  8638. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  8639. */
  8640. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  8641. /**
  8642. * This flag can be used for type testing.
  8643. *
  8644. * @type {boolean}
  8645. * @readonly
  8646. * @default true
  8647. */
  8648. this.isEuler = true;
  8649. this._x = x;
  8650. this._y = y;
  8651. this._z = z;
  8652. this._order = order;
  8653. }
  8654. /**
  8655. * The angle of the x axis in radians.
  8656. *
  8657. * @type {number}
  8658. * @default 0
  8659. */
  8660. get x() {
  8661. return this._x;
  8662. }
  8663. set x( value ) {
  8664. this._x = value;
  8665. this._onChangeCallback();
  8666. }
  8667. /**
  8668. * The angle of the y axis in radians.
  8669. *
  8670. * @type {number}
  8671. * @default 0
  8672. */
  8673. get y() {
  8674. return this._y;
  8675. }
  8676. set y( value ) {
  8677. this._y = value;
  8678. this._onChangeCallback();
  8679. }
  8680. /**
  8681. * The angle of the z axis in radians.
  8682. *
  8683. * @type {number}
  8684. * @default 0
  8685. */
  8686. get z() {
  8687. return this._z;
  8688. }
  8689. set z( value ) {
  8690. this._z = value;
  8691. this._onChangeCallback();
  8692. }
  8693. /**
  8694. * A string representing the order that the rotations are applied.
  8695. *
  8696. * @type {string}
  8697. * @default 'XYZ'
  8698. */
  8699. get order() {
  8700. return this._order;
  8701. }
  8702. set order( value ) {
  8703. this._order = value;
  8704. this._onChangeCallback();
  8705. }
  8706. /**
  8707. * Sets the Euler components.
  8708. *
  8709. * @param {number} x - The angle of the x axis in radians.
  8710. * @param {number} y - The angle of the y axis in radians.
  8711. * @param {number} z - The angle of the z axis in radians.
  8712. * @param {string} [order] - A string representing the order that the rotations are applied.
  8713. * @return {Euler} A reference to this Euler instance.
  8714. */
  8715. set( x, y, z, order = this._order ) {
  8716. this._x = x;
  8717. this._y = y;
  8718. this._z = z;
  8719. this._order = order;
  8720. this._onChangeCallback();
  8721. return this;
  8722. }
  8723. /**
  8724. * Returns a new Euler instance with copied values from this instance.
  8725. *
  8726. * @return {Euler} A clone of this instance.
  8727. */
  8728. clone() {
  8729. return new this.constructor( this._x, this._y, this._z, this._order );
  8730. }
  8731. /**
  8732. * Copies the values of the given Euler instance to this instance.
  8733. *
  8734. * @param {Euler} euler - The Euler instance to copy.
  8735. * @return {Euler} A reference to this Euler instance.
  8736. */
  8737. copy( euler ) {
  8738. this._x = euler._x;
  8739. this._y = euler._y;
  8740. this._z = euler._z;
  8741. this._order = euler._order;
  8742. this._onChangeCallback();
  8743. return this;
  8744. }
  8745. /**
  8746. * Sets the angles of this Euler instance from a pure rotation matrix.
  8747. *
  8748. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  8749. * @param {string} [order] - A string representing the order that the rotations are applied.
  8750. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8751. * @return {Euler} A reference to this Euler instance.
  8752. */
  8753. setFromRotationMatrix( m, order = this._order, update = true ) {
  8754. const te = m.elements;
  8755. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8756. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8757. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8758. switch ( order ) {
  8759. case 'XYZ':
  8760. this._y = Math.asin( clamp( m13, -1, 1 ) );
  8761. if ( Math.abs( m13 ) < 0.9999999 ) {
  8762. this._x = Math.atan2( - m23, m33 );
  8763. this._z = Math.atan2( - m12, m11 );
  8764. } else {
  8765. this._x = Math.atan2( m32, m22 );
  8766. this._z = 0;
  8767. }
  8768. break;
  8769. case 'YXZ':
  8770. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  8771. if ( Math.abs( m23 ) < 0.9999999 ) {
  8772. this._y = Math.atan2( m13, m33 );
  8773. this._z = Math.atan2( m21, m22 );
  8774. } else {
  8775. this._y = Math.atan2( - m31, m11 );
  8776. this._z = 0;
  8777. }
  8778. break;
  8779. case 'ZXY':
  8780. this._x = Math.asin( clamp( m32, -1, 1 ) );
  8781. if ( Math.abs( m32 ) < 0.9999999 ) {
  8782. this._y = Math.atan2( - m31, m33 );
  8783. this._z = Math.atan2( - m12, m22 );
  8784. } else {
  8785. this._y = 0;
  8786. this._z = Math.atan2( m21, m11 );
  8787. }
  8788. break;
  8789. case 'ZYX':
  8790. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  8791. if ( Math.abs( m31 ) < 0.9999999 ) {
  8792. this._x = Math.atan2( m32, m33 );
  8793. this._z = Math.atan2( m21, m11 );
  8794. } else {
  8795. this._x = 0;
  8796. this._z = Math.atan2( - m12, m22 );
  8797. }
  8798. break;
  8799. case 'YZX':
  8800. this._z = Math.asin( clamp( m21, -1, 1 ) );
  8801. if ( Math.abs( m21 ) < 0.9999999 ) {
  8802. this._x = Math.atan2( - m23, m22 );
  8803. this._y = Math.atan2( - m31, m11 );
  8804. } else {
  8805. this._x = 0;
  8806. this._y = Math.atan2( m13, m33 );
  8807. }
  8808. break;
  8809. case 'XZY':
  8810. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  8811. if ( Math.abs( m12 ) < 0.9999999 ) {
  8812. this._x = Math.atan2( m32, m22 );
  8813. this._y = Math.atan2( m13, m11 );
  8814. } else {
  8815. this._x = Math.atan2( - m23, m33 );
  8816. this._y = 0;
  8817. }
  8818. break;
  8819. default:
  8820. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  8821. }
  8822. this._order = order;
  8823. if ( update === true ) this._onChangeCallback();
  8824. return this;
  8825. }
  8826. /**
  8827. * Sets the angles of this Euler instance from a normalized quaternion.
  8828. *
  8829. * @param {Quaternion} q - A normalized Quaternion.
  8830. * @param {string} [order] - A string representing the order that the rotations are applied.
  8831. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8832. * @return {Euler} A reference to this Euler instance.
  8833. */
  8834. setFromQuaternion( q, order, update ) {
  8835. _matrix$2.makeRotationFromQuaternion( q );
  8836. return this.setFromRotationMatrix( _matrix$2, order, update );
  8837. }
  8838. /**
  8839. * Sets the angles of this Euler instance from the given vector.
  8840. *
  8841. * @param {Vector3} v - The vector.
  8842. * @param {string} [order] - A string representing the order that the rotations are applied.
  8843. * @return {Euler} A reference to this Euler instance.
  8844. */
  8845. setFromVector3( v, order = this._order ) {
  8846. return this.set( v.x, v.y, v.z, order );
  8847. }
  8848. /**
  8849. * Resets the euler angle with a new order by creating a quaternion from this
  8850. * euler angle and then setting this euler angle with the quaternion and the
  8851. * new order.
  8852. *
  8853. * Warning: This discards revolution information.
  8854. *
  8855. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  8856. * @return {Euler} A reference to this Euler instance.
  8857. */
  8858. reorder( newOrder ) {
  8859. _quaternion$4.setFromEuler( this );
  8860. return this.setFromQuaternion( _quaternion$4, newOrder );
  8861. }
  8862. /**
  8863. * Returns `true` if this Euler instance is equal with the given one.
  8864. *
  8865. * @param {Euler} euler - The Euler instance to test for equality.
  8866. * @return {boolean} Whether this Euler instance is equal with the given one.
  8867. */
  8868. equals( euler ) {
  8869. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8870. }
  8871. /**
  8872. * Sets this Euler instance's components to values from the given array. The first three
  8873. * entries of the array are assign to the x,y and z components. An optional fourth entry
  8874. * defines the Euler order.
  8875. *
  8876. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  8877. * @return {Euler} A reference to this Euler instance.
  8878. */
  8879. fromArray( array ) {
  8880. this._x = array[ 0 ];
  8881. this._y = array[ 1 ];
  8882. this._z = array[ 2 ];
  8883. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  8884. this._onChangeCallback();
  8885. return this;
  8886. }
  8887. /**
  8888. * Writes the components of this Euler instance to the given array. If no array is provided,
  8889. * the method returns a new instance.
  8890. *
  8891. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  8892. * @param {number} [offset=0] - Index of the first element in the array.
  8893. * @return {Array<number,number,number,string>} The Euler components.
  8894. */
  8895. toArray( array = [], offset = 0 ) {
  8896. array[ offset ] = this._x;
  8897. array[ offset + 1 ] = this._y;
  8898. array[ offset + 2 ] = this._z;
  8899. array[ offset + 3 ] = this._order;
  8900. return array;
  8901. }
  8902. _onChange( callback ) {
  8903. this._onChangeCallback = callback;
  8904. return this;
  8905. }
  8906. _onChangeCallback() {}
  8907. *[ Symbol.iterator ]() {
  8908. yield this._x;
  8909. yield this._y;
  8910. yield this._z;
  8911. yield this._order;
  8912. }
  8913. }
  8914. /**
  8915. * The default Euler angle order.
  8916. *
  8917. * @static
  8918. * @type {string}
  8919. * @default 'XYZ'
  8920. */
  8921. Euler.DEFAULT_ORDER = 'XYZ';
  8922. /**
  8923. * A layers object assigns an 3D object to 1 or more of 32
  8924. * layers numbered `0` to `31` - internally the layers are stored as a
  8925. * bit mask], and by default all 3D objects are a member of layer `0`.
  8926. *
  8927. * This can be used to control visibility - an object must share a layer with
  8928. * a camera to be visible when that camera's view is
  8929. * rendered.
  8930. *
  8931. * All classes that inherit from {@link Object3D} have an `layers` property which
  8932. * is an instance of this class.
  8933. */
  8934. class Layers {
  8935. /**
  8936. * Constructs a new layers instance, with membership
  8937. * initially set to layer `0`.
  8938. */
  8939. constructor() {
  8940. /**
  8941. * A bit mask storing which of the 32 layers this layers object is currently
  8942. * a member of.
  8943. *
  8944. * @type {number}
  8945. */
  8946. this.mask = 1 | 0;
  8947. }
  8948. /**
  8949. * Sets membership to the given layer, and remove membership all other layers.
  8950. *
  8951. * @param {number} layer - The layer to set.
  8952. */
  8953. set( layer ) {
  8954. this.mask = ( 1 << layer | 0 ) >>> 0;
  8955. }
  8956. /**
  8957. * Adds membership of the given layer.
  8958. *
  8959. * @param {number} layer - The layer to enable.
  8960. */
  8961. enable( layer ) {
  8962. this.mask |= 1 << layer | 0;
  8963. }
  8964. /**
  8965. * Adds membership to all layers.
  8966. */
  8967. enableAll() {
  8968. this.mask = 0xffffffff | 0;
  8969. }
  8970. /**
  8971. * Toggles the membership of the given layer.
  8972. *
  8973. * @param {number} layer - The layer to toggle.
  8974. */
  8975. toggle( layer ) {
  8976. this.mask ^= 1 << layer | 0;
  8977. }
  8978. /**
  8979. * Removes membership of the given layer.
  8980. *
  8981. * @param {number} layer - The layer to enable.
  8982. */
  8983. disable( layer ) {
  8984. this.mask &= ~ ( 1 << layer | 0 );
  8985. }
  8986. /**
  8987. * Removes the membership from all layers.
  8988. */
  8989. disableAll() {
  8990. this.mask = 0;
  8991. }
  8992. /**
  8993. * Returns `true` if this and the given layers object have at least one
  8994. * layer in common.
  8995. *
  8996. * @param {Layers} layers - The layers to test.
  8997. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  8998. */
  8999. test( layers ) {
  9000. return ( this.mask & layers.mask ) !== 0;
  9001. }
  9002. /**
  9003. * Returns `true` if the given layer is enabled.
  9004. *
  9005. * @param {number} layer - The layer to test.
  9006. * @return {boolean } Whether the given layer is enabled or not.
  9007. */
  9008. isEnabled( layer ) {
  9009. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9010. }
  9011. }
  9012. let _object3DId = 0;
  9013. const _v1$6 = /*@__PURE__*/ new Vector3();
  9014. const _q1 = /*@__PURE__*/ new Quaternion();
  9015. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9016. const _target = /*@__PURE__*/ new Vector3();
  9017. const _position$4 = /*@__PURE__*/ new Vector3();
  9018. const _scale$3 = /*@__PURE__*/ new Vector3();
  9019. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9020. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9021. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9022. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9023. /**
  9024. * Fires when the object has been added to its parent object.
  9025. *
  9026. * @event Object3D#added
  9027. * @type {Object}
  9028. */
  9029. const _addedEvent = { type: 'added' };
  9030. /**
  9031. * Fires when the object has been removed from its parent object.
  9032. *
  9033. * @event Object3D#removed
  9034. * @type {Object}
  9035. */
  9036. const _removedEvent = { type: 'removed' };
  9037. /**
  9038. * Fires when a new child object has been added.
  9039. *
  9040. * @event Object3D#childadded
  9041. * @type {Object}
  9042. */
  9043. const _childaddedEvent = { type: 'childadded', child: null };
  9044. /**
  9045. * Fires when a child object has been removed.
  9046. *
  9047. * @event Object3D#childremoved
  9048. * @type {Object}
  9049. */
  9050. const _childremovedEvent = { type: 'childremoved', child: null };
  9051. /**
  9052. * This is the base class for most objects in three.js and provides a set of
  9053. * properties and methods for manipulating objects in 3D space.
  9054. *
  9055. * @augments EventDispatcher
  9056. */
  9057. class Object3D extends EventDispatcher {
  9058. /**
  9059. * Constructs a new 3D object.
  9060. */
  9061. constructor() {
  9062. super();
  9063. /**
  9064. * This flag can be used for type testing.
  9065. *
  9066. * @type {boolean}
  9067. * @readonly
  9068. * @default true
  9069. */
  9070. this.isObject3D = true;
  9071. /**
  9072. * The ID of the 3D object.
  9073. *
  9074. * @name Object3D#id
  9075. * @type {number}
  9076. * @readonly
  9077. */
  9078. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  9079. /**
  9080. * The UUID of the 3D object.
  9081. *
  9082. * @type {string}
  9083. * @readonly
  9084. */
  9085. this.uuid = generateUUID();
  9086. /**
  9087. * The name of the 3D object.
  9088. *
  9089. * @type {string}
  9090. */
  9091. this.name = '';
  9092. /**
  9093. * The type property is used for detecting the object type
  9094. * in context of serialization/deserialization.
  9095. *
  9096. * @type {string}
  9097. * @readonly
  9098. */
  9099. this.type = 'Object3D';
  9100. /**
  9101. * A reference to the parent object.
  9102. *
  9103. * @type {?Object3D}
  9104. * @default null
  9105. */
  9106. this.parent = null;
  9107. /**
  9108. * An array holding the child 3D objects of this instance.
  9109. *
  9110. * @type {Array<Object3D>}
  9111. */
  9112. this.children = [];
  9113. /**
  9114. * Defines the `up` direction of the 3D object which influences
  9115. * the orientation via methods like {@link Object3D#lookAt}.
  9116. *
  9117. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  9118. *
  9119. * @type {Vector3}
  9120. */
  9121. this.up = Object3D.DEFAULT_UP.clone();
  9122. const position = new Vector3();
  9123. const rotation = new Euler();
  9124. const quaternion = new Quaternion();
  9125. const scale = new Vector3( 1, 1, 1 );
  9126. function onRotationChange() {
  9127. quaternion.setFromEuler( rotation, false );
  9128. }
  9129. function onQuaternionChange() {
  9130. rotation.setFromQuaternion( quaternion, undefined, false );
  9131. }
  9132. rotation._onChange( onRotationChange );
  9133. quaternion._onChange( onQuaternionChange );
  9134. Object.defineProperties( this, {
  9135. /**
  9136. * Represents the object's local position.
  9137. *
  9138. * @name Object3D#position
  9139. * @type {Vector3}
  9140. * @default (0,0,0)
  9141. */
  9142. position: {
  9143. configurable: true,
  9144. enumerable: true,
  9145. value: position
  9146. },
  9147. /**
  9148. * Represents the object's local rotation as Euler angles, in radians.
  9149. *
  9150. * @name Object3D#rotation
  9151. * @type {Euler}
  9152. * @default (0,0,0)
  9153. */
  9154. rotation: {
  9155. configurable: true,
  9156. enumerable: true,
  9157. value: rotation
  9158. },
  9159. /**
  9160. * Represents the object's local rotation as Quaternions.
  9161. *
  9162. * @name Object3D#quaternion
  9163. * @type {Quaternion}
  9164. */
  9165. quaternion: {
  9166. configurable: true,
  9167. enumerable: true,
  9168. value: quaternion
  9169. },
  9170. /**
  9171. * Represents the object's local scale.
  9172. *
  9173. * @name Object3D#scale
  9174. * @type {Vector3}
  9175. * @default (1,1,1)
  9176. */
  9177. scale: {
  9178. configurable: true,
  9179. enumerable: true,
  9180. value: scale
  9181. },
  9182. /**
  9183. * Represents the object's model-view matrix.
  9184. *
  9185. * @name Object3D#modelViewMatrix
  9186. * @type {Matrix4}
  9187. */
  9188. modelViewMatrix: {
  9189. value: new Matrix4()
  9190. },
  9191. /**
  9192. * Represents the object's normal matrix.
  9193. *
  9194. * @name Object3D#normalMatrix
  9195. * @type {Matrix3}
  9196. */
  9197. normalMatrix: {
  9198. value: new Matrix3()
  9199. }
  9200. } );
  9201. /**
  9202. * Represents the object's transformation matrix in local space.
  9203. *
  9204. * @type {Matrix4}
  9205. */
  9206. this.matrix = new Matrix4();
  9207. /**
  9208. * Represents the object's transformation matrix in world space.
  9209. * If the 3D object has no parent, then it's identical to the local transformation matrix
  9210. *
  9211. * @type {Matrix4}
  9212. */
  9213. this.matrixWorld = new Matrix4();
  9214. /**
  9215. * When set to `true`, the engine automatically computes the local matrix from position,
  9216. * rotation and scale every frame. If set to `false`, the app is responsible for recomputing
  9217. * the local matrix by calling `updateMatrix()`.
  9218. *
  9219. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  9220. *
  9221. * @type {boolean}
  9222. * @default true
  9223. */
  9224. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  9225. /**
  9226. * When set to `true`, the engine automatically computes the world matrix from the current local
  9227. * matrix and the object's transformation hierarchy. If set to `false`, the app is responsible for
  9228. * recomputing the world matrix by directly updating the `matrixWorld` property.
  9229. *
  9230. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  9231. *
  9232. * @type {boolean}
  9233. * @default true
  9234. */
  9235. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  9236. /**
  9237. * When set to `true`, it calculates the world matrix in that frame and resets this property
  9238. * to `false`.
  9239. *
  9240. * @type {boolean}
  9241. * @default false
  9242. */
  9243. this.matrixWorldNeedsUpdate = false;
  9244. /**
  9245. * The layer membership of the 3D object. The 3D object is only visible if it has
  9246. * at least one layer in common with the camera in use. This property can also be
  9247. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  9248. *
  9249. * @type {Layers}
  9250. */
  9251. this.layers = new Layers();
  9252. /**
  9253. * When set to `true`, the 3D object gets rendered.
  9254. *
  9255. * @type {boolean}
  9256. * @default true
  9257. */
  9258. this.visible = true;
  9259. /**
  9260. * When set to `true`, the 3D object gets rendered into shadow maps.
  9261. *
  9262. * @type {boolean}
  9263. * @default false
  9264. */
  9265. this.castShadow = false;
  9266. /**
  9267. * When set to `true`, the 3D object is affected by shadows in the scene.
  9268. *
  9269. * @type {boolean}
  9270. * @default false
  9271. */
  9272. this.receiveShadow = false;
  9273. /**
  9274. * When set to `true`, the 3D object is honored by view frustum culling.
  9275. *
  9276. * @type {boolean}
  9277. * @default true
  9278. */
  9279. this.frustumCulled = true;
  9280. /**
  9281. * This value allows the default rendering order of scene graph objects to be
  9282. * overridden although opaque and transparent objects remain sorted independently.
  9283. * When this property is set for an instance of {@link Group},all descendants
  9284. * objects will be sorted and rendered together. Sorting is from lowest to highest
  9285. * render order.
  9286. *
  9287. * @type {number}
  9288. * @default 0
  9289. */
  9290. this.renderOrder = 0;
  9291. /**
  9292. * An array holding the animation clips of the 3D object.
  9293. *
  9294. * @type {Array<AnimationClip>}
  9295. */
  9296. this.animations = [];
  9297. /**
  9298. * Custom depth material to be used when rendering to the depth map. Can only be used
  9299. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  9300. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  9301. * material for proper shadows.
  9302. *
  9303. * Only relevant in context of {@link WebGLRenderer}.
  9304. *
  9305. * @type {(Material|undefined)}
  9306. * @default undefined
  9307. */
  9308. this.customDepthMaterial = undefined;
  9309. /**
  9310. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  9311. *
  9312. * Only relevant in context of {@link WebGLRenderer}.
  9313. *
  9314. * @type {(Material|undefined)}
  9315. * @default undefined
  9316. */
  9317. this.customDistanceMaterial = undefined;
  9318. /**
  9319. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  9320. * the 3D object is not going to be changed after the initial renderer. This includes
  9321. * geometry and material settings. A static 3D object can be processed by the renderer
  9322. * slightly faster since certain state checks can be bypassed.
  9323. *
  9324. * Only relevant in context of {@link WebGPURenderer}.
  9325. *
  9326. * @type {boolean}
  9327. * @default false
  9328. */
  9329. this.static = false;
  9330. /**
  9331. * An object that can be used to store custom data about the 3D object. It
  9332. * should not hold references to functions as these will not be cloned.
  9333. *
  9334. * @type {Object}
  9335. */
  9336. this.userData = {};
  9337. /**
  9338. * The pivot point for rotation and scale transformations.
  9339. * When set, rotation and scale are applied around this point
  9340. * instead of the object's origin.
  9341. *
  9342. * @type {?Vector3}
  9343. * @default null
  9344. */
  9345. this.pivot = null;
  9346. }
  9347. /**
  9348. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  9349. *
  9350. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9351. * @param {Object3D} object - The 3D object.
  9352. * @param {Camera} camera - The camera that is used to render the scene.
  9353. * @param {Camera} shadowCamera - The shadow camera.
  9354. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9355. * @param {Material} depthMaterial - The depth material.
  9356. * @param {Object} group - The geometry group data.
  9357. */
  9358. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9359. /**
  9360. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  9361. *
  9362. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9363. * @param {Object3D} object - The 3D object.
  9364. * @param {Camera} camera - The camera that is used to render the scene.
  9365. * @param {Camera} shadowCamera - The shadow camera.
  9366. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9367. * @param {Material} depthMaterial - The depth material.
  9368. * @param {Object} group - The geometry group data.
  9369. */
  9370. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9371. /**
  9372. * A callback that is executed immediately before a 3D object is rendered.
  9373. *
  9374. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9375. * @param {Object3D} object - The 3D object.
  9376. * @param {Camera} camera - The camera that is used to render the scene.
  9377. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9378. * @param {Material} material - The 3D object's material.
  9379. * @param {Object} group - The geometry group data.
  9380. */
  9381. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9382. /**
  9383. * A callback that is executed immediately after a 3D object is rendered.
  9384. *
  9385. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9386. * @param {Object3D} object - The 3D object.
  9387. * @param {Camera} camera - The camera that is used to render the scene.
  9388. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9389. * @param {Material} material - The 3D object's material.
  9390. * @param {Object} group - The geometry group data.
  9391. */
  9392. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9393. /**
  9394. * Applies the given transformation matrix to the object and updates the object's position,
  9395. * rotation and scale.
  9396. *
  9397. * @param {Matrix4} matrix - The transformation matrix.
  9398. */
  9399. applyMatrix4( matrix ) {
  9400. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9401. this.matrix.premultiply( matrix );
  9402. this.matrix.decompose( this.position, this.quaternion, this.scale );
  9403. }
  9404. /**
  9405. * Applies a rotation represented by given the quaternion to the 3D object.
  9406. *
  9407. * @param {Quaternion} q - The quaternion.
  9408. * @return {Object3D} A reference to this instance.
  9409. */
  9410. applyQuaternion( q ) {
  9411. this.quaternion.premultiply( q );
  9412. return this;
  9413. }
  9414. /**
  9415. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  9416. *
  9417. * @param {Vector3} axis - The (normalized) axis vector.
  9418. * @param {number} angle - The angle in radians.
  9419. */
  9420. setRotationFromAxisAngle( axis, angle ) {
  9421. // assumes axis is normalized
  9422. this.quaternion.setFromAxisAngle( axis, angle );
  9423. }
  9424. /**
  9425. * Sets the given rotation represented as Euler angles to the 3D object.
  9426. *
  9427. * @param {Euler} euler - The Euler angles.
  9428. */
  9429. setRotationFromEuler( euler ) {
  9430. this.quaternion.setFromEuler( euler, true );
  9431. }
  9432. /**
  9433. * Sets the given rotation represented as rotation matrix to the 3D object.
  9434. *
  9435. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  9436. * a pure rotation matrix (i.e, unscaled).
  9437. */
  9438. setRotationFromMatrix( m ) {
  9439. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9440. this.quaternion.setFromRotationMatrix( m );
  9441. }
  9442. /**
  9443. * Sets the given rotation represented as a Quaternion to the 3D object.
  9444. *
  9445. * @param {Quaternion} q - The Quaternion
  9446. */
  9447. setRotationFromQuaternion( q ) {
  9448. // assumes q is normalized
  9449. this.quaternion.copy( q );
  9450. }
  9451. /**
  9452. * Rotates the 3D object along an axis in local space.
  9453. *
  9454. * @param {Vector3} axis - The (normalized) axis vector.
  9455. * @param {number} angle - The angle in radians.
  9456. * @return {Object3D} A reference to this instance.
  9457. */
  9458. rotateOnAxis( axis, angle ) {
  9459. // rotate object on axis in object space
  9460. // axis is assumed to be normalized
  9461. _q1.setFromAxisAngle( axis, angle );
  9462. this.quaternion.multiply( _q1 );
  9463. return this;
  9464. }
  9465. /**
  9466. * Rotates the 3D object along an axis in world space.
  9467. *
  9468. * @param {Vector3} axis - The (normalized) axis vector.
  9469. * @param {number} angle - The angle in radians.
  9470. * @return {Object3D} A reference to this instance.
  9471. */
  9472. rotateOnWorldAxis( axis, angle ) {
  9473. // rotate object on axis in world space
  9474. // axis is assumed to be normalized
  9475. // method assumes no rotated parent
  9476. _q1.setFromAxisAngle( axis, angle );
  9477. this.quaternion.premultiply( _q1 );
  9478. return this;
  9479. }
  9480. /**
  9481. * Rotates the 3D object around its X axis in local space.
  9482. *
  9483. * @param {number} angle - The angle in radians.
  9484. * @return {Object3D} A reference to this instance.
  9485. */
  9486. rotateX( angle ) {
  9487. return this.rotateOnAxis( _xAxis, angle );
  9488. }
  9489. /**
  9490. * Rotates the 3D object around its Y axis in local space.
  9491. *
  9492. * @param {number} angle - The angle in radians.
  9493. * @return {Object3D} A reference to this instance.
  9494. */
  9495. rotateY( angle ) {
  9496. return this.rotateOnAxis( _yAxis, angle );
  9497. }
  9498. /**
  9499. * Rotates the 3D object around its Z axis in local space.
  9500. *
  9501. * @param {number} angle - The angle in radians.
  9502. * @return {Object3D} A reference to this instance.
  9503. */
  9504. rotateZ( angle ) {
  9505. return this.rotateOnAxis( _zAxis, angle );
  9506. }
  9507. /**
  9508. * Translate the 3D object by a distance along the given axis in local space.
  9509. *
  9510. * @param {Vector3} axis - The (normalized) axis vector.
  9511. * @param {number} distance - The distance in world units.
  9512. * @return {Object3D} A reference to this instance.
  9513. */
  9514. translateOnAxis( axis, distance ) {
  9515. // translate object by distance along axis in object space
  9516. // axis is assumed to be normalized
  9517. _v1$6.copy( axis ).applyQuaternion( this.quaternion );
  9518. this.position.add( _v1$6.multiplyScalar( distance ) );
  9519. return this;
  9520. }
  9521. /**
  9522. * Translate the 3D object by a distance along its X-axis in local space.
  9523. *
  9524. * @param {number} distance - The distance in world units.
  9525. * @return {Object3D} A reference to this instance.
  9526. */
  9527. translateX( distance ) {
  9528. return this.translateOnAxis( _xAxis, distance );
  9529. }
  9530. /**
  9531. * Translate the 3D object by a distance along its Y-axis in local space.
  9532. *
  9533. * @param {number} distance - The distance in world units.
  9534. * @return {Object3D} A reference to this instance.
  9535. */
  9536. translateY( distance ) {
  9537. return this.translateOnAxis( _yAxis, distance );
  9538. }
  9539. /**
  9540. * Translate the 3D object by a distance along its Z-axis in local space.
  9541. *
  9542. * @param {number} distance - The distance in world units.
  9543. * @return {Object3D} A reference to this instance.
  9544. */
  9545. translateZ( distance ) {
  9546. return this.translateOnAxis( _zAxis, distance );
  9547. }
  9548. /**
  9549. * Converts the given vector from this 3D object's local space to world space.
  9550. *
  9551. * @param {Vector3} vector - The vector to convert.
  9552. * @return {Vector3} The converted vector.
  9553. */
  9554. localToWorld( vector ) {
  9555. this.updateWorldMatrix( true, false );
  9556. return vector.applyMatrix4( this.matrixWorld );
  9557. }
  9558. /**
  9559. * Converts the given vector from this 3D object's world space to local space.
  9560. *
  9561. * @param {Vector3} vector - The vector to convert.
  9562. * @return {Vector3} The converted vector.
  9563. */
  9564. worldToLocal( vector ) {
  9565. this.updateWorldMatrix( true, false );
  9566. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  9567. }
  9568. /**
  9569. * Rotates the object to face a point in world space.
  9570. *
  9571. * This method does not support objects having non-uniformly-scaled parent(s).
  9572. *
  9573. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  9574. * @param {number} [y] - The y coordinate in world space.
  9575. * @param {number} [z] - The z coordinate in world space.
  9576. */
  9577. lookAt( x, y, z ) {
  9578. // This method does not support objects having non-uniformly-scaled parent(s)
  9579. if ( x.isVector3 ) {
  9580. _target.copy( x );
  9581. } else {
  9582. _target.set( x, y, z );
  9583. }
  9584. const parent = this.parent;
  9585. this.updateWorldMatrix( true, false );
  9586. _position$4.setFromMatrixPosition( this.matrixWorld );
  9587. if ( this.isCamera || this.isLight ) {
  9588. _m1$1.lookAt( _position$4, _target, this.up );
  9589. } else {
  9590. _m1$1.lookAt( _target, _position$4, this.up );
  9591. }
  9592. this.quaternion.setFromRotationMatrix( _m1$1 );
  9593. if ( parent ) {
  9594. _m1$1.extractRotation( parent.matrixWorld );
  9595. _q1.setFromRotationMatrix( _m1$1 );
  9596. this.quaternion.premultiply( _q1.invert() );
  9597. }
  9598. }
  9599. /**
  9600. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  9601. * objects may be added. Any current parent on an object passed in here will be
  9602. * removed, since an object can have at most one parent.
  9603. *
  9604. * @fires Object3D#added
  9605. * @fires Object3D#childadded
  9606. * @param {Object3D} object - The 3D object to add.
  9607. * @return {Object3D} A reference to this instance.
  9608. */
  9609. add( object ) {
  9610. if ( arguments.length > 1 ) {
  9611. for ( let i = 0; i < arguments.length; i ++ ) {
  9612. this.add( arguments[ i ] );
  9613. }
  9614. return this;
  9615. }
  9616. if ( object === this ) {
  9617. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  9618. return this;
  9619. }
  9620. if ( object && object.isObject3D ) {
  9621. object.removeFromParent();
  9622. object.parent = this;
  9623. this.children.push( object );
  9624. object.dispatchEvent( _addedEvent );
  9625. _childaddedEvent.child = object;
  9626. this.dispatchEvent( _childaddedEvent );
  9627. _childaddedEvent.child = null;
  9628. } else {
  9629. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  9630. }
  9631. return this;
  9632. }
  9633. /**
  9634. * Removes the given 3D object as child from this 3D object.
  9635. * An arbitrary number of objects may be removed.
  9636. *
  9637. * @fires Object3D#removed
  9638. * @fires Object3D#childremoved
  9639. * @param {Object3D} object - The 3D object to remove.
  9640. * @return {Object3D} A reference to this instance.
  9641. */
  9642. remove( object ) {
  9643. if ( arguments.length > 1 ) {
  9644. for ( let i = 0; i < arguments.length; i ++ ) {
  9645. this.remove( arguments[ i ] );
  9646. }
  9647. return this;
  9648. }
  9649. const index = this.children.indexOf( object );
  9650. if ( index !== -1 ) {
  9651. object.parent = null;
  9652. this.children.splice( index, 1 );
  9653. object.dispatchEvent( _removedEvent );
  9654. _childremovedEvent.child = object;
  9655. this.dispatchEvent( _childremovedEvent );
  9656. _childremovedEvent.child = null;
  9657. }
  9658. return this;
  9659. }
  9660. /**
  9661. * Removes this 3D object from its current parent.
  9662. *
  9663. * @fires Object3D#removed
  9664. * @fires Object3D#childremoved
  9665. * @return {Object3D} A reference to this instance.
  9666. */
  9667. removeFromParent() {
  9668. const parent = this.parent;
  9669. if ( parent !== null ) {
  9670. parent.remove( this );
  9671. }
  9672. return this;
  9673. }
  9674. /**
  9675. * Removes all child objects.
  9676. *
  9677. * @fires Object3D#removed
  9678. * @fires Object3D#childremoved
  9679. * @return {Object3D} A reference to this instance.
  9680. */
  9681. clear() {
  9682. return this.remove( ... this.children );
  9683. }
  9684. /**
  9685. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  9686. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  9687. *
  9688. * @fires Object3D#added
  9689. * @fires Object3D#childadded
  9690. * @param {Object3D} object - The 3D object to attach.
  9691. * @return {Object3D} A reference to this instance.
  9692. */
  9693. attach( object ) {
  9694. // adds object as a child of this, while maintaining the object's world transform
  9695. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  9696. this.updateWorldMatrix( true, false );
  9697. _m1$1.copy( this.matrixWorld ).invert();
  9698. if ( object.parent !== null ) {
  9699. object.parent.updateWorldMatrix( true, false );
  9700. _m1$1.multiply( object.parent.matrixWorld );
  9701. }
  9702. object.applyMatrix4( _m1$1 );
  9703. object.removeFromParent();
  9704. object.parent = this;
  9705. this.children.push( object );
  9706. object.updateWorldMatrix( false, true );
  9707. object.dispatchEvent( _addedEvent );
  9708. _childaddedEvent.child = object;
  9709. this.dispatchEvent( _childaddedEvent );
  9710. _childaddedEvent.child = null;
  9711. return this;
  9712. }
  9713. /**
  9714. * Searches through the 3D object and its children, starting with the 3D object
  9715. * itself, and returns the first with a matching ID.
  9716. *
  9717. * @param {number} id - The id.
  9718. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9719. */
  9720. getObjectById( id ) {
  9721. return this.getObjectByProperty( 'id', id );
  9722. }
  9723. /**
  9724. * Searches through the 3D object and its children, starting with the 3D object
  9725. * itself, and returns the first with a matching name.
  9726. *
  9727. * @param {string} name - The name.
  9728. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9729. */
  9730. getObjectByName( name ) {
  9731. return this.getObjectByProperty( 'name', name );
  9732. }
  9733. /**
  9734. * Searches through the 3D object and its children, starting with the 3D object
  9735. * itself, and returns the first with a matching property value.
  9736. *
  9737. * @param {string} name - The name of the property.
  9738. * @param {any} value - The value.
  9739. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9740. */
  9741. getObjectByProperty( name, value ) {
  9742. if ( this[ name ] === value ) return this;
  9743. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  9744. const child = this.children[ i ];
  9745. const object = child.getObjectByProperty( name, value );
  9746. if ( object !== undefined ) {
  9747. return object;
  9748. }
  9749. }
  9750. return undefined;
  9751. }
  9752. /**
  9753. * Searches through the 3D object and its children, starting with the 3D object
  9754. * itself, and returns all 3D objects with a matching property value.
  9755. *
  9756. * @param {string} name - The name of the property.
  9757. * @param {any} value - The value.
  9758. * @param {Array<Object3D>} result - The method stores the result in this array.
  9759. * @return {Array<Object3D>} The found 3D objects.
  9760. */
  9761. getObjectsByProperty( name, value, result = [] ) {
  9762. if ( this[ name ] === value ) result.push( this );
  9763. const children = this.children;
  9764. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9765. children[ i ].getObjectsByProperty( name, value, result );
  9766. }
  9767. return result;
  9768. }
  9769. /**
  9770. * Returns a vector representing the position of the 3D object in world space.
  9771. *
  9772. * @param {Vector3} target - The target vector the result is stored to.
  9773. * @return {Vector3} The 3D object's position in world space.
  9774. */
  9775. getWorldPosition( target ) {
  9776. this.updateWorldMatrix( true, false );
  9777. return target.setFromMatrixPosition( this.matrixWorld );
  9778. }
  9779. /**
  9780. * Returns a Quaternion representing the position of the 3D object in world space.
  9781. *
  9782. * @param {Quaternion} target - The target Quaternion the result is stored to.
  9783. * @return {Quaternion} The 3D object's rotation in world space.
  9784. */
  9785. getWorldQuaternion( target ) {
  9786. this.updateWorldMatrix( true, false );
  9787. this.matrixWorld.decompose( _position$4, target, _scale$3 );
  9788. return target;
  9789. }
  9790. /**
  9791. * Returns a vector representing the scale of the 3D object in world space.
  9792. *
  9793. * @param {Vector3} target - The target vector the result is stored to.
  9794. * @return {Vector3} The 3D object's scale in world space.
  9795. */
  9796. getWorldScale( target ) {
  9797. this.updateWorldMatrix( true, false );
  9798. this.matrixWorld.decompose( _position$4, _quaternion$3, target );
  9799. return target;
  9800. }
  9801. /**
  9802. * Returns a vector representing the ("look") direction of the 3D object in world space.
  9803. *
  9804. * @param {Vector3} target - The target vector the result is stored to.
  9805. * @return {Vector3} The 3D object's direction in world space.
  9806. */
  9807. getWorldDirection( target ) {
  9808. this.updateWorldMatrix( true, false );
  9809. const e = this.matrixWorld.elements;
  9810. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9811. }
  9812. /**
  9813. * Abstract method to get intersections between a casted ray and this
  9814. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  9815. * implement this method in order to use raycasting.
  9816. *
  9817. * @abstract
  9818. * @param {Raycaster} raycaster - The raycaster.
  9819. * @param {Array<Object>} intersects - An array holding the result of the method.
  9820. */
  9821. raycast( /* raycaster, intersects */ ) {}
  9822. /**
  9823. * Executes the callback on this 3D object and all descendants.
  9824. *
  9825. * Note: Modifying the scene graph inside the callback is discouraged.
  9826. *
  9827. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9828. */
  9829. traverse( callback ) {
  9830. callback( this );
  9831. const children = this.children;
  9832. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9833. children[ i ].traverse( callback );
  9834. }
  9835. }
  9836. /**
  9837. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  9838. * Descendants of invisible 3D objects are not traversed.
  9839. *
  9840. * Note: Modifying the scene graph inside the callback is discouraged.
  9841. *
  9842. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9843. */
  9844. traverseVisible( callback ) {
  9845. if ( this.visible === false ) return;
  9846. callback( this );
  9847. const children = this.children;
  9848. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9849. children[ i ].traverseVisible( callback );
  9850. }
  9851. }
  9852. /**
  9853. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  9854. *
  9855. * Note: Modifying the scene graph inside the callback is discouraged.
  9856. *
  9857. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9858. */
  9859. traverseAncestors( callback ) {
  9860. const parent = this.parent;
  9861. if ( parent !== null ) {
  9862. callback( parent );
  9863. parent.traverseAncestors( callback );
  9864. }
  9865. }
  9866. /**
  9867. * Updates the transformation matrix in local space by computing it from the current
  9868. * position, rotation and scale values.
  9869. */
  9870. updateMatrix() {
  9871. this.matrix.compose( this.position, this.quaternion, this.scale );
  9872. const pivot = this.pivot;
  9873. if ( pivot !== null ) {
  9874. const px = pivot.x, py = pivot.y, pz = pivot.z;
  9875. const te = this.matrix.elements;
  9876. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  9877. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  9878. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  9879. }
  9880. this.matrixWorldNeedsUpdate = true;
  9881. }
  9882. /**
  9883. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  9884. *
  9885. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  9886. * local space. The computation of the local and world matrix can be controlled with the
  9887. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  9888. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  9889. *
  9890. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  9891. * when {@link Object3D#matrixWorldNeedsUpdate} is `false`.
  9892. */
  9893. updateMatrixWorld( force ) {
  9894. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9895. if ( this.matrixWorldNeedsUpdate || force ) {
  9896. if ( this.matrixWorldAutoUpdate === true ) {
  9897. if ( this.parent === null ) {
  9898. this.matrixWorld.copy( this.matrix );
  9899. } else {
  9900. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9901. }
  9902. }
  9903. this.matrixWorldNeedsUpdate = false;
  9904. force = true;
  9905. }
  9906. // make sure descendants are updated if required
  9907. const children = this.children;
  9908. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9909. const child = children[ i ];
  9910. child.updateMatrixWorld( force );
  9911. }
  9912. }
  9913. /**
  9914. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  9915. * update of ancestor and descendant nodes.
  9916. *
  9917. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  9918. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  9919. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  9920. * when {@link Object3D#matrixWorldNeedsUpdate} is `false`.
  9921. */
  9922. updateWorldMatrix( updateParents, updateChildren, force = false ) {
  9923. const parent = this.parent;
  9924. if ( updateParents === true && parent !== null ) {
  9925. parent.updateWorldMatrix( true, false );
  9926. }
  9927. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9928. if ( this.matrixWorldNeedsUpdate || force ) {
  9929. if ( this.matrixWorldAutoUpdate === true ) {
  9930. if ( this.parent === null ) {
  9931. this.matrixWorld.copy( this.matrix );
  9932. } else {
  9933. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9934. }
  9935. }
  9936. this.matrixWorldNeedsUpdate = false;
  9937. force = true;
  9938. }
  9939. // make sure descendants are updated
  9940. if ( updateChildren === true ) {
  9941. const children = this.children;
  9942. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9943. const child = children[ i ];
  9944. child.updateWorldMatrix( false, true, force );
  9945. }
  9946. }
  9947. }
  9948. /**
  9949. * Serializes the 3D object into JSON.
  9950. *
  9951. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  9952. * @return {Object} A JSON object representing the serialized 3D object.
  9953. * @see {@link ObjectLoader#parse}
  9954. */
  9955. toJSON( meta ) {
  9956. // meta is a string when called from JSON.stringify
  9957. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  9958. const output = {};
  9959. // meta is a hash used to collect geometries, materials.
  9960. // not providing it implies that this is the root object
  9961. // being serialized.
  9962. if ( isRootObject ) {
  9963. // initialize meta obj
  9964. meta = {
  9965. geometries: {},
  9966. materials: {},
  9967. textures: {},
  9968. images: {},
  9969. shapes: {},
  9970. skeletons: {},
  9971. animations: {},
  9972. nodes: {}
  9973. };
  9974. output.metadata = {
  9975. version: 4.7,
  9976. type: 'Object',
  9977. generator: 'Object3D.toJSON'
  9978. };
  9979. }
  9980. // standard Object3D serialization
  9981. const object = {};
  9982. object.uuid = this.uuid;
  9983. object.type = this.type;
  9984. if ( this.name !== '' ) object.name = this.name;
  9985. if ( this.castShadow === true ) object.castShadow = true;
  9986. if ( this.receiveShadow === true ) object.receiveShadow = true;
  9987. if ( this.visible === false ) object.visible = false;
  9988. if ( this.frustumCulled === false ) object.frustumCulled = false;
  9989. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  9990. if ( this.static !== false ) object.static = this.static;
  9991. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  9992. object.layers = this.layers.mask;
  9993. object.matrix = this.matrix.toArray();
  9994. object.up = this.up.toArray();
  9995. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  9996. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  9997. if ( this.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, this.morphTargetDictionary );
  9998. if ( this.morphTargetInfluences !== undefined ) object.morphTargetInfluences = this.morphTargetInfluences.slice();
  9999. // object specific properties
  10000. if ( this.isInstancedMesh ) {
  10001. object.type = 'InstancedMesh';
  10002. object.count = this.count;
  10003. object.instanceMatrix = this.instanceMatrix.toJSON();
  10004. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10005. }
  10006. if ( this.isBatchedMesh ) {
  10007. object.type = 'BatchedMesh';
  10008. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10009. object.sortObjects = this.sortObjects;
  10010. object.drawRanges = this._drawRanges;
  10011. object.reservedRanges = this._reservedRanges;
  10012. object.geometryInfo = this._geometryInfo.map( info => ( {
  10013. ...info,
  10014. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10015. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10016. } ) );
  10017. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10018. object.availableInstanceIds = this._availableInstanceIds.slice();
  10019. object.availableGeometryIds = this._availableGeometryIds.slice();
  10020. object.nextIndexStart = this._nextIndexStart;
  10021. object.nextVertexStart = this._nextVertexStart;
  10022. object.geometryCount = this._geometryCount;
  10023. object.maxInstanceCount = this._maxInstanceCount;
  10024. object.maxVertexCount = this._maxVertexCount;
  10025. object.maxIndexCount = this._maxIndexCount;
  10026. object.geometryInitialized = this._geometryInitialized;
  10027. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10028. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10029. if ( this._colorsTexture !== null ) {
  10030. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10031. }
  10032. if ( this.boundingSphere !== null ) {
  10033. object.boundingSphere = this.boundingSphere.toJSON();
  10034. }
  10035. if ( this.boundingBox !== null ) {
  10036. object.boundingBox = this.boundingBox.toJSON();
  10037. }
  10038. }
  10039. //
  10040. function serialize( library, element ) {
  10041. if ( library[ element.uuid ] === undefined ) {
  10042. library[ element.uuid ] = element.toJSON( meta );
  10043. }
  10044. return element.uuid;
  10045. }
  10046. if ( this.isScene ) {
  10047. if ( this.background ) {
  10048. if ( this.background.isColor ) {
  10049. object.background = this.background.toJSON();
  10050. } else if ( this.background.isTexture ) {
  10051. object.background = this.background.toJSON( meta ).uuid;
  10052. }
  10053. }
  10054. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10055. object.environment = this.environment.toJSON( meta ).uuid;
  10056. }
  10057. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10058. object.geometry = serialize( meta.geometries, this.geometry );
  10059. const parameters = this.geometry.parameters;
  10060. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10061. const shapes = parameters.shapes;
  10062. if ( Array.isArray( shapes ) ) {
  10063. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10064. const shape = shapes[ i ];
  10065. serialize( meta.shapes, shape );
  10066. }
  10067. } else {
  10068. serialize( meta.shapes, shapes );
  10069. }
  10070. }
  10071. }
  10072. if ( this.isSkinnedMesh ) {
  10073. object.bindMode = this.bindMode;
  10074. object.bindMatrix = this.bindMatrix.toArray();
  10075. if ( this.skeleton !== undefined ) {
  10076. serialize( meta.skeletons, this.skeleton );
  10077. object.skeleton = this.skeleton.uuid;
  10078. }
  10079. }
  10080. if ( this.material !== undefined ) {
  10081. if ( Array.isArray( this.material ) ) {
  10082. const uuids = [];
  10083. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  10084. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10085. }
  10086. object.material = uuids;
  10087. } else {
  10088. object.material = serialize( meta.materials, this.material );
  10089. }
  10090. }
  10091. //
  10092. if ( this.children.length > 0 ) {
  10093. object.children = [];
  10094. for ( let i = 0; i < this.children.length; i ++ ) {
  10095. object.children.push( this.children[ i ].toJSON( meta ).object );
  10096. }
  10097. }
  10098. //
  10099. if ( this.animations.length > 0 ) {
  10100. object.animations = [];
  10101. for ( let i = 0; i < this.animations.length; i ++ ) {
  10102. const animation = this.animations[ i ];
  10103. object.animations.push( serialize( meta.animations, animation ) );
  10104. }
  10105. }
  10106. if ( isRootObject ) {
  10107. const geometries = extractFromCache( meta.geometries );
  10108. const materials = extractFromCache( meta.materials );
  10109. const textures = extractFromCache( meta.textures );
  10110. const images = extractFromCache( meta.images );
  10111. const shapes = extractFromCache( meta.shapes );
  10112. const skeletons = extractFromCache( meta.skeletons );
  10113. const animations = extractFromCache( meta.animations );
  10114. const nodes = extractFromCache( meta.nodes );
  10115. if ( geometries.length > 0 ) output.geometries = geometries;
  10116. if ( materials.length > 0 ) output.materials = materials;
  10117. if ( textures.length > 0 ) output.textures = textures;
  10118. if ( images.length > 0 ) output.images = images;
  10119. if ( shapes.length > 0 ) output.shapes = shapes;
  10120. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  10121. if ( animations.length > 0 ) output.animations = animations;
  10122. if ( nodes.length > 0 ) output.nodes = nodes;
  10123. }
  10124. output.object = object;
  10125. return output;
  10126. // extract data from the cache hash
  10127. // remove metadata on each item
  10128. // and return as array
  10129. function extractFromCache( cache ) {
  10130. const values = [];
  10131. for ( const key in cache ) {
  10132. const data = cache[ key ];
  10133. delete data.metadata;
  10134. values.push( data );
  10135. }
  10136. return values;
  10137. }
  10138. }
  10139. /**
  10140. * Returns a new 3D object with copied values from this instance.
  10141. *
  10142. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  10143. * @return {Object3D} A clone of this instance.
  10144. */
  10145. clone( recursive ) {
  10146. return new this.constructor().copy( this, recursive );
  10147. }
  10148. /**
  10149. * Copies the values of the given 3D object to this instance.
  10150. *
  10151. * @param {Object3D} source - The 3D object to copy.
  10152. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  10153. * @return {Object3D} A reference to this instance.
  10154. */
  10155. copy( source, recursive = true ) {
  10156. this.name = source.name;
  10157. this.up.copy( source.up );
  10158. this.position.copy( source.position );
  10159. this.rotation.order = source.rotation.order;
  10160. this.quaternion.copy( source.quaternion );
  10161. this.scale.copy( source.scale );
  10162. this.pivot = ( source.pivot !== null ) ? source.pivot.clone() : null;
  10163. this.matrix.copy( source.matrix );
  10164. this.matrixWorld.copy( source.matrixWorld );
  10165. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10166. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  10167. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10168. this.layers.mask = source.layers.mask;
  10169. this.visible = source.visible;
  10170. this.castShadow = source.castShadow;
  10171. this.receiveShadow = source.receiveShadow;
  10172. this.frustumCulled = source.frustumCulled;
  10173. this.renderOrder = source.renderOrder;
  10174. this.static = source.static;
  10175. this.animations = source.animations.slice();
  10176. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10177. if ( recursive === true ) {
  10178. for ( let i = 0; i < source.children.length; i ++ ) {
  10179. const child = source.children[ i ];
  10180. this.add( child.clone() );
  10181. }
  10182. }
  10183. return this;
  10184. }
  10185. }
  10186. /**
  10187. * The default up direction for objects, also used as the default
  10188. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  10189. *
  10190. * @static
  10191. * @type {Vector3}
  10192. * @default (0,1,0)
  10193. */
  10194. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10195. /**
  10196. * The default setting for {@link Object3D#matrixAutoUpdate} for
  10197. * newly created 3D objects.
  10198. *
  10199. * @static
  10200. * @type {boolean}
  10201. * @default true
  10202. */
  10203. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  10204. /**
  10205. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  10206. * newly created 3D objects.
  10207. *
  10208. * @static
  10209. * @type {boolean}
  10210. * @default true
  10211. */
  10212. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  10213. /**
  10214. * This is almost identical to an {@link Object3D}. Its purpose is to
  10215. * make working with groups of objects syntactically clearer.
  10216. *
  10217. * ```js
  10218. * // Create a group and add the two cubes.
  10219. * // These cubes can now be rotated / scaled etc as a group.
  10220. * const group = new THREE.Group();
  10221. *
  10222. * group.add( meshA );
  10223. * group.add( meshB );
  10224. *
  10225. * scene.add( group );
  10226. * ```
  10227. *
  10228. * @augments Object3D
  10229. */
  10230. class Group extends Object3D {
  10231. constructor() {
  10232. super();
  10233. /**
  10234. * This flag can be used for type testing.
  10235. *
  10236. * @type {boolean}
  10237. * @readonly
  10238. * @default true
  10239. */
  10240. this.isGroup = true;
  10241. this.type = 'Group';
  10242. }
  10243. }
  10244. const _moveEvent = { type: 'move' };
  10245. /**
  10246. * Class for representing a XR controller with its
  10247. * different coordinate systems.
  10248. *
  10249. * @private
  10250. */
  10251. class WebXRController {
  10252. /**
  10253. * Constructs a new XR controller.
  10254. */
  10255. constructor() {
  10256. /**
  10257. * A group representing the target ray space
  10258. * of the XR controller.
  10259. *
  10260. * @private
  10261. * @type {?Group}
  10262. * @default null
  10263. */
  10264. this._targetRay = null;
  10265. /**
  10266. * A group representing the grip space
  10267. * of the XR controller.
  10268. *
  10269. * @private
  10270. * @type {?Group}
  10271. * @default null
  10272. */
  10273. this._grip = null;
  10274. /**
  10275. * A group representing the hand space
  10276. * of the XR controller.
  10277. *
  10278. * @private
  10279. * @type {?Group}
  10280. * @default null
  10281. */
  10282. this._hand = null;
  10283. }
  10284. /**
  10285. * Returns a group representing the hand space of the XR controller.
  10286. *
  10287. * @return {Group} A group representing the hand space of the XR controller.
  10288. */
  10289. getHandSpace() {
  10290. if ( this._hand === null ) {
  10291. this._hand = new Group();
  10292. this._hand.matrixAutoUpdate = false;
  10293. this._hand.visible = false;
  10294. this._hand.joints = {};
  10295. this._hand.inputState = { pinching: false };
  10296. }
  10297. return this._hand;
  10298. }
  10299. /**
  10300. * Returns a group representing the target ray space of the XR controller.
  10301. *
  10302. * @return {Group} A group representing the target ray space of the XR controller.
  10303. */
  10304. getTargetRaySpace() {
  10305. if ( this._targetRay === null ) {
  10306. this._targetRay = new Group();
  10307. this._targetRay.matrixAutoUpdate = false;
  10308. this._targetRay.visible = false;
  10309. this._targetRay.hasLinearVelocity = false;
  10310. this._targetRay.linearVelocity = new Vector3();
  10311. this._targetRay.hasAngularVelocity = false;
  10312. this._targetRay.angularVelocity = new Vector3();
  10313. }
  10314. return this._targetRay;
  10315. }
  10316. /**
  10317. * Returns a group representing the grip space of the XR controller.
  10318. *
  10319. * @return {Group} A group representing the grip space of the XR controller.
  10320. */
  10321. getGripSpace() {
  10322. if ( this._grip === null ) {
  10323. this._grip = new Group();
  10324. this._grip.matrixAutoUpdate = false;
  10325. this._grip.visible = false;
  10326. this._grip.hasLinearVelocity = false;
  10327. this._grip.linearVelocity = new Vector3();
  10328. this._grip.hasAngularVelocity = false;
  10329. this._grip.angularVelocity = new Vector3();
  10330. this._grip.eventsEnabled = false;
  10331. }
  10332. return this._grip;
  10333. }
  10334. /**
  10335. * Dispatches the given event to the groups representing
  10336. * the different coordinate spaces of the XR controller.
  10337. *
  10338. * @param {Object} event - The event to dispatch.
  10339. * @return {WebXRController} A reference to this instance.
  10340. */
  10341. dispatchEvent( event ) {
  10342. if ( this._targetRay !== null ) {
  10343. this._targetRay.dispatchEvent( event );
  10344. }
  10345. if ( this._grip !== null ) {
  10346. this._grip.dispatchEvent( event );
  10347. }
  10348. if ( this._hand !== null ) {
  10349. this._hand.dispatchEvent( event );
  10350. }
  10351. return this;
  10352. }
  10353. /**
  10354. * Connects the controller with the given XR input source.
  10355. *
  10356. * @param {XRInputSource} inputSource - The input source.
  10357. * @return {WebXRController} A reference to this instance.
  10358. */
  10359. connect( inputSource ) {
  10360. if ( inputSource && inputSource.hand ) {
  10361. const hand = this._hand;
  10362. if ( hand ) {
  10363. for ( const inputjoint of inputSource.hand.values() ) {
  10364. // Initialize hand with joints when connected
  10365. this._getHandJoint( hand, inputjoint );
  10366. }
  10367. }
  10368. }
  10369. this.dispatchEvent( { type: 'connected', data: inputSource } );
  10370. return this;
  10371. }
  10372. /**
  10373. * Disconnects the controller from the given XR input source.
  10374. *
  10375. * @param {XRInputSource} inputSource - The input source.
  10376. * @return {WebXRController} A reference to this instance.
  10377. */
  10378. disconnect( inputSource ) {
  10379. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  10380. if ( this._targetRay !== null ) {
  10381. this._targetRay.visible = false;
  10382. }
  10383. if ( this._grip !== null ) {
  10384. this._grip.visible = false;
  10385. }
  10386. if ( this._hand !== null ) {
  10387. this._hand.visible = false;
  10388. }
  10389. return this;
  10390. }
  10391. /**
  10392. * Updates the controller with the given input source, XR frame and reference space.
  10393. * This updates the transformations of the groups that represent the different
  10394. * coordinate systems of the controller.
  10395. *
  10396. * @param {XRInputSource} inputSource - The input source.
  10397. * @param {XRFrame} frame - The XR frame.
  10398. * @param {XRReferenceSpace} referenceSpace - The reference space.
  10399. * @return {WebXRController} A reference to this instance.
  10400. */
  10401. update( inputSource, frame, referenceSpace ) {
  10402. let inputPose = null;
  10403. let gripPose = null;
  10404. let handPose = null;
  10405. const targetRay = this._targetRay;
  10406. const grip = this._grip;
  10407. const hand = this._hand;
  10408. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  10409. if ( hand && inputSource.hand ) {
  10410. handPose = true;
  10411. for ( const inputjoint of inputSource.hand.values() ) {
  10412. // Update the joints groups with the XRJoint poses
  10413. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  10414. // The transform of this joint will be updated with the joint pose on each frame
  10415. const joint = this._getHandJoint( hand, inputjoint );
  10416. if ( jointPose !== null ) {
  10417. joint.matrix.fromArray( jointPose.transform.matrix );
  10418. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  10419. joint.matrixWorldNeedsUpdate = true;
  10420. joint.jointRadius = jointPose.radius;
  10421. }
  10422. joint.visible = jointPose !== null;
  10423. }
  10424. // Custom events
  10425. // Check pinchz
  10426. const indexTip = hand.joints[ 'index-finger-tip' ];
  10427. const thumbTip = hand.joints[ 'thumb-tip' ];
  10428. const distance = indexTip.position.distanceTo( thumbTip.position );
  10429. const distanceToPinch = 0.02;
  10430. const threshold = 0.005;
  10431. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  10432. hand.inputState.pinching = false;
  10433. this.dispatchEvent( {
  10434. type: 'pinchend',
  10435. handedness: inputSource.handedness,
  10436. target: this
  10437. } );
  10438. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  10439. hand.inputState.pinching = true;
  10440. this.dispatchEvent( {
  10441. type: 'pinchstart',
  10442. handedness: inputSource.handedness,
  10443. target: this
  10444. } );
  10445. }
  10446. } else {
  10447. if ( grip !== null && inputSource.gripSpace ) {
  10448. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  10449. if ( gripPose !== null ) {
  10450. grip.matrix.fromArray( gripPose.transform.matrix );
  10451. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  10452. grip.matrixWorldNeedsUpdate = true;
  10453. if ( gripPose.linearVelocity ) {
  10454. grip.hasLinearVelocity = true;
  10455. grip.linearVelocity.copy( gripPose.linearVelocity );
  10456. } else {
  10457. grip.hasLinearVelocity = false;
  10458. }
  10459. if ( gripPose.angularVelocity ) {
  10460. grip.hasAngularVelocity = true;
  10461. grip.angularVelocity.copy( gripPose.angularVelocity );
  10462. } else {
  10463. grip.hasAngularVelocity = false;
  10464. }
  10465. // grip update event if enabled
  10466. if ( grip.eventsEnabled ) {
  10467. grip.dispatchEvent( {
  10468. type: 'gripUpdated',
  10469. data: inputSource,
  10470. target: this
  10471. } );
  10472. }
  10473. }
  10474. }
  10475. }
  10476. if ( targetRay !== null ) {
  10477. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  10478. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  10479. if ( inputPose === null && gripPose !== null ) {
  10480. inputPose = gripPose;
  10481. }
  10482. if ( inputPose !== null ) {
  10483. targetRay.matrix.fromArray( inputPose.transform.matrix );
  10484. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  10485. targetRay.matrixWorldNeedsUpdate = true;
  10486. if ( inputPose.linearVelocity ) {
  10487. targetRay.hasLinearVelocity = true;
  10488. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  10489. } else {
  10490. targetRay.hasLinearVelocity = false;
  10491. }
  10492. if ( inputPose.angularVelocity ) {
  10493. targetRay.hasAngularVelocity = true;
  10494. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  10495. } else {
  10496. targetRay.hasAngularVelocity = false;
  10497. }
  10498. this.dispatchEvent( _moveEvent );
  10499. }
  10500. }
  10501. }
  10502. if ( targetRay !== null ) {
  10503. targetRay.visible = ( inputPose !== null );
  10504. }
  10505. if ( grip !== null ) {
  10506. grip.visible = ( gripPose !== null );
  10507. }
  10508. if ( hand !== null ) {
  10509. hand.visible = ( handPose !== null );
  10510. }
  10511. return this;
  10512. }
  10513. /**
  10514. * Returns a group representing the hand joint for the given input joint.
  10515. *
  10516. * @private
  10517. * @param {Group} hand - The group representing the hand space.
  10518. * @param {XRJointSpace} inputjoint - The hand joint data.
  10519. * @return {Group} A group representing the hand joint for the given input joint.
  10520. */
  10521. _getHandJoint( hand, inputjoint ) {
  10522. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  10523. const joint = new Group();
  10524. joint.matrixAutoUpdate = false;
  10525. joint.visible = false;
  10526. hand.joints[ inputjoint.jointName ] = joint;
  10527. hand.add( joint );
  10528. }
  10529. return hand.joints[ inputjoint.jointName ];
  10530. }
  10531. }
  10532. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  10533. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  10534. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  10535. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  10536. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  10537. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  10538. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  10539. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  10540. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  10541. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  10542. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  10543. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  10544. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  10545. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  10546. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  10547. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  10548. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  10549. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  10550. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  10551. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  10552. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  10553. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  10554. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  10555. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  10556. const _hslA = { h: 0, s: 0, l: 0 };
  10557. const _hslB = { h: 0, s: 0, l: 0 };
  10558. function hue2rgb( p, q, t ) {
  10559. if ( t < 0 ) t += 1;
  10560. if ( t > 1 ) t -= 1;
  10561. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  10562. if ( t < 1 / 2 ) return q;
  10563. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  10564. return p;
  10565. }
  10566. /**
  10567. * A Color instance is represented by RGB components in the linear <i>working
  10568. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  10569. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  10570. * strings) are converted to the working color space automatically.
  10571. *
  10572. * ```js
  10573. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  10574. * const color = new THREE.Color().setHex( 0x112233 );
  10575. * ```
  10576. * Source color spaces may be specified explicitly, to ensure correct conversions.
  10577. * ```js
  10578. * // assumed already LinearSRGBColorSpace; no conversion
  10579. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  10580. *
  10581. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  10582. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  10583. * ```
  10584. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  10585. * see <i>Color management</i>. Iterating through a Color instance will yield
  10586. * its components (r, g, b) in the corresponding order. A Color can be initialised
  10587. * in any of the following ways:
  10588. * ```js
  10589. * //empty constructor - will default white
  10590. * const color1 = new THREE.Color();
  10591. *
  10592. * //Hexadecimal color (recommended)
  10593. * const color2 = new THREE.Color( 0xff0000 );
  10594. *
  10595. * //RGB string
  10596. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  10597. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  10598. *
  10599. * //X11 color name - all 140 color names are supported.
  10600. * //Note the lack of CamelCase in the name
  10601. * const color5 = new THREE.Color( 'skyblue' );
  10602. * //HSL string
  10603. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  10604. *
  10605. * //Separate RGB values between 0 and 1
  10606. * const color7 = new THREE.Color( 1, 0, 0 );
  10607. * ```
  10608. */
  10609. class Color {
  10610. /**
  10611. * Constructs a new color.
  10612. *
  10613. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  10614. * and that method is used throughout the rest of the documentation.
  10615. *
  10616. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10617. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10618. * @param {number} [g] - The green component.
  10619. * @param {number} [b] - The blue component.
  10620. */
  10621. constructor( r, g, b ) {
  10622. /**
  10623. * This flag can be used for type testing.
  10624. *
  10625. * @type {boolean}
  10626. * @readonly
  10627. * @default true
  10628. */
  10629. this.isColor = true;
  10630. /**
  10631. * The red component.
  10632. *
  10633. * @type {number}
  10634. * @default 1
  10635. */
  10636. this.r = 1;
  10637. /**
  10638. * The green component.
  10639. *
  10640. * @type {number}
  10641. * @default 1
  10642. */
  10643. this.g = 1;
  10644. /**
  10645. * The blue component.
  10646. *
  10647. * @type {number}
  10648. * @default 1
  10649. */
  10650. this.b = 1;
  10651. return this.set( r, g, b );
  10652. }
  10653. /**
  10654. * Sets the colors's components from the given values.
  10655. *
  10656. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10657. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10658. * @param {number} [g] - The green component.
  10659. * @param {number} [b] - The blue component.
  10660. * @return {Color} A reference to this color.
  10661. */
  10662. set( r, g, b ) {
  10663. if ( g === undefined && b === undefined ) {
  10664. // r is THREE.Color, hex or string
  10665. const value = r;
  10666. if ( value && value.isColor ) {
  10667. this.copy( value );
  10668. } else if ( typeof value === 'number' ) {
  10669. this.setHex( value );
  10670. } else if ( typeof value === 'string' ) {
  10671. this.setStyle( value );
  10672. }
  10673. } else {
  10674. this.setRGB( r, g, b );
  10675. }
  10676. return this;
  10677. }
  10678. /**
  10679. * Sets the colors's components to the given scalar value.
  10680. *
  10681. * @param {number} scalar - The scalar value.
  10682. * @return {Color} A reference to this color.
  10683. */
  10684. setScalar( scalar ) {
  10685. this.r = scalar;
  10686. this.g = scalar;
  10687. this.b = scalar;
  10688. return this;
  10689. }
  10690. /**
  10691. * Sets this color from a hexadecimal value.
  10692. *
  10693. * @param {number} hex - The hexadecimal value.
  10694. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10695. * @return {Color} A reference to this color.
  10696. */
  10697. setHex( hex, colorSpace = SRGBColorSpace ) {
  10698. hex = Math.floor( hex );
  10699. this.r = ( hex >> 16 & 255 ) / 255;
  10700. this.g = ( hex >> 8 & 255 ) / 255;
  10701. this.b = ( hex & 255 ) / 255;
  10702. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10703. return this;
  10704. }
  10705. /**
  10706. * Sets this color from RGB values.
  10707. *
  10708. * @param {number} r - Red channel value between `0.0` and `1.0`.
  10709. * @param {number} g - Green channel value between `0.0` and `1.0`.
  10710. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  10711. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10712. * @return {Color} A reference to this color.
  10713. */
  10714. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  10715. this.r = r;
  10716. this.g = g;
  10717. this.b = b;
  10718. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10719. return this;
  10720. }
  10721. /**
  10722. * Sets this color from RGB values.
  10723. *
  10724. * @param {number} h - Hue value between `0.0` and `1.0`.
  10725. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10726. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10727. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10728. * @return {Color} A reference to this color.
  10729. */
  10730. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  10731. // h,s,l ranges are in 0.0 - 1.0
  10732. h = euclideanModulo( h, 1 );
  10733. s = clamp( s, 0, 1 );
  10734. l = clamp( l, 0, 1 );
  10735. if ( s === 0 ) {
  10736. this.r = this.g = this.b = l;
  10737. } else {
  10738. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  10739. const q = ( 2 * l ) - p;
  10740. this.r = hue2rgb( q, p, h + 1 / 3 );
  10741. this.g = hue2rgb( q, p, h );
  10742. this.b = hue2rgb( q, p, h - 1 / 3 );
  10743. }
  10744. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10745. return this;
  10746. }
  10747. /**
  10748. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  10749. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  10750. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  10751. * all 140 color names are supported).
  10752. *
  10753. * @param {string} style - Color as a CSS-style string.
  10754. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10755. * @return {Color} A reference to this color.
  10756. */
  10757. setStyle( style, colorSpace = SRGBColorSpace ) {
  10758. function handleAlpha( string ) {
  10759. if ( string === undefined ) return;
  10760. if ( parseFloat( string ) < 1 ) {
  10761. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  10762. }
  10763. }
  10764. let m;
  10765. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  10766. // rgb / hsl
  10767. let color;
  10768. const name = m[ 1 ];
  10769. const components = m[ 2 ];
  10770. switch ( name ) {
  10771. case 'rgb':
  10772. case 'rgba':
  10773. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10774. // rgb(255,0,0) rgba(255,0,0,0.5)
  10775. handleAlpha( color[ 4 ] );
  10776. return this.setRGB(
  10777. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  10778. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  10779. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  10780. colorSpace
  10781. );
  10782. }
  10783. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10784. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10785. handleAlpha( color[ 4 ] );
  10786. return this.setRGB(
  10787. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  10788. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  10789. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  10790. colorSpace
  10791. );
  10792. }
  10793. break;
  10794. case 'hsl':
  10795. case 'hsla':
  10796. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10797. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10798. handleAlpha( color[ 4 ] );
  10799. return this.setHSL(
  10800. parseFloat( color[ 1 ] ) / 360,
  10801. parseFloat( color[ 2 ] ) / 100,
  10802. parseFloat( color[ 3 ] ) / 100,
  10803. colorSpace
  10804. );
  10805. }
  10806. break;
  10807. default:
  10808. warn( 'Color: Unknown color model ' + style );
  10809. }
  10810. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  10811. // hex color
  10812. const hex = m[ 1 ];
  10813. const size = hex.length;
  10814. if ( size === 3 ) {
  10815. // #ff0
  10816. return this.setRGB(
  10817. parseInt( hex.charAt( 0 ), 16 ) / 15,
  10818. parseInt( hex.charAt( 1 ), 16 ) / 15,
  10819. parseInt( hex.charAt( 2 ), 16 ) / 15,
  10820. colorSpace
  10821. );
  10822. } else if ( size === 6 ) {
  10823. // #ff0000
  10824. return this.setHex( parseInt( hex, 16 ), colorSpace );
  10825. } else {
  10826. warn( 'Color: Invalid hex color ' + style );
  10827. }
  10828. } else if ( style && style.length > 0 ) {
  10829. return this.setColorName( style, colorSpace );
  10830. }
  10831. return this;
  10832. }
  10833. /**
  10834. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  10835. * you don't need the other CSS-style formats.
  10836. *
  10837. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  10838. * ```js
  10839. * Color.NAMES.aliceblue // returns 0xF0F8FF
  10840. * ```
  10841. *
  10842. * @param {string} style - The color name.
  10843. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10844. * @return {Color} A reference to this color.
  10845. */
  10846. setColorName( style, colorSpace = SRGBColorSpace ) {
  10847. // color keywords
  10848. const hex = _colorKeywords[ style.toLowerCase() ];
  10849. if ( hex !== undefined ) {
  10850. // red
  10851. this.setHex( hex, colorSpace );
  10852. } else {
  10853. // unknown color
  10854. warn( 'Color: Unknown color ' + style );
  10855. }
  10856. return this;
  10857. }
  10858. /**
  10859. * Returns a new color with copied values from this instance.
  10860. *
  10861. * @return {Color} A clone of this instance.
  10862. */
  10863. clone() {
  10864. return new this.constructor( this.r, this.g, this.b );
  10865. }
  10866. /**
  10867. * Copies the values of the given color to this instance.
  10868. *
  10869. * @param {Color} color - The color to copy.
  10870. * @return {Color} A reference to this color.
  10871. */
  10872. copy( color ) {
  10873. this.r = color.r;
  10874. this.g = color.g;
  10875. this.b = color.b;
  10876. return this;
  10877. }
  10878. /**
  10879. * Copies the given color into this color, and then converts this color from
  10880. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10881. *
  10882. * @param {Color} color - The color to copy/convert.
  10883. * @return {Color} A reference to this color.
  10884. */
  10885. copySRGBToLinear( color ) {
  10886. this.r = SRGBToLinear( color.r );
  10887. this.g = SRGBToLinear( color.g );
  10888. this.b = SRGBToLinear( color.b );
  10889. return this;
  10890. }
  10891. /**
  10892. * Copies the given color into this color, and then converts this color from
  10893. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10894. *
  10895. * @param {Color} color - The color to copy/convert.
  10896. * @return {Color} A reference to this color.
  10897. */
  10898. copyLinearToSRGB( color ) {
  10899. this.r = LinearToSRGB( color.r );
  10900. this.g = LinearToSRGB( color.g );
  10901. this.b = LinearToSRGB( color.b );
  10902. return this;
  10903. }
  10904. /**
  10905. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10906. *
  10907. * @return {Color} A reference to this color.
  10908. */
  10909. convertSRGBToLinear() {
  10910. this.copySRGBToLinear( this );
  10911. return this;
  10912. }
  10913. /**
  10914. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10915. *
  10916. * @return {Color} A reference to this color.
  10917. */
  10918. convertLinearToSRGB() {
  10919. this.copyLinearToSRGB( this );
  10920. return this;
  10921. }
  10922. /**
  10923. * Returns the hexadecimal value of this color.
  10924. *
  10925. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10926. * @return {number} The hexadecimal value.
  10927. */
  10928. getHex( colorSpace = SRGBColorSpace ) {
  10929. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10930. 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 ) );
  10931. }
  10932. /**
  10933. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  10934. *
  10935. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10936. * @return {string} The hexadecimal value as a string.
  10937. */
  10938. getHexString( colorSpace = SRGBColorSpace ) {
  10939. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  10940. }
  10941. /**
  10942. * Converts the colors RGB values into the HSL format and stores them into the
  10943. * given target object.
  10944. *
  10945. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  10946. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10947. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  10948. */
  10949. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  10950. // h,s,l ranges are in 0.0 - 1.0
  10951. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10952. const r = _color.r, g = _color.g, b = _color.b;
  10953. const max = Math.max( r, g, b );
  10954. const min = Math.min( r, g, b );
  10955. let hue, saturation;
  10956. const lightness = ( min + max ) / 2.0;
  10957. if ( min === max ) {
  10958. hue = 0;
  10959. saturation = 0;
  10960. } else {
  10961. const delta = max - min;
  10962. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  10963. switch ( max ) {
  10964. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  10965. case g: hue = ( b - r ) / delta + 2; break;
  10966. case b: hue = ( r - g ) / delta + 4; break;
  10967. }
  10968. hue /= 6;
  10969. }
  10970. target.h = hue;
  10971. target.s = saturation;
  10972. target.l = lightness;
  10973. return target;
  10974. }
  10975. /**
  10976. * Returns the RGB values of this color and stores them into the given target object.
  10977. *
  10978. * @param {Color} target - The target color that is used to store the method's result.
  10979. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10980. * @return {Color} The RGB representation of this color.
  10981. */
  10982. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  10983. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10984. target.r = _color.r;
  10985. target.g = _color.g;
  10986. target.b = _color.b;
  10987. return target;
  10988. }
  10989. /**
  10990. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  10991. *
  10992. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10993. * @return {string} The CSS representation of this color.
  10994. */
  10995. getStyle( colorSpace = SRGBColorSpace ) {
  10996. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10997. const r = _color.r, g = _color.g, b = _color.b;
  10998. if ( colorSpace !== SRGBColorSpace ) {
  10999. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  11000. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  11001. }
  11002. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  11003. }
  11004. /**
  11005. * Adds the given HSL values to this color's values.
  11006. * Internally, this converts the color's RGB values to HSL, adds HSL
  11007. * and then converts the color back to RGB.
  11008. *
  11009. * @param {number} h - Hue value between `0.0` and `1.0`.
  11010. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11011. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11012. * @return {Color} A reference to this color.
  11013. */
  11014. offsetHSL( h, s, l ) {
  11015. this.getHSL( _hslA );
  11016. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  11017. }
  11018. /**
  11019. * Adds the RGB values of the given color to the RGB values of this color.
  11020. *
  11021. * @param {Color} color - The color to add.
  11022. * @return {Color} A reference to this color.
  11023. */
  11024. add( color ) {
  11025. this.r += color.r;
  11026. this.g += color.g;
  11027. this.b += color.b;
  11028. return this;
  11029. }
  11030. /**
  11031. * Adds the RGB values of the given colors and stores the result in this instance.
  11032. *
  11033. * @param {Color} color1 - The first color.
  11034. * @param {Color} color2 - The second color.
  11035. * @return {Color} A reference to this color.
  11036. */
  11037. addColors( color1, color2 ) {
  11038. this.r = color1.r + color2.r;
  11039. this.g = color1.g + color2.g;
  11040. this.b = color1.b + color2.b;
  11041. return this;
  11042. }
  11043. /**
  11044. * Adds the given scalar value to the RGB values of this color.
  11045. *
  11046. * @param {number} s - The scalar to add.
  11047. * @return {Color} A reference to this color.
  11048. */
  11049. addScalar( s ) {
  11050. this.r += s;
  11051. this.g += s;
  11052. this.b += s;
  11053. return this;
  11054. }
  11055. /**
  11056. * Subtracts the RGB values of the given color from the RGB values of this color.
  11057. *
  11058. * @param {Color} color - The color to subtract.
  11059. * @return {Color} A reference to this color.
  11060. */
  11061. sub( color ) {
  11062. this.r = Math.max( 0, this.r - color.r );
  11063. this.g = Math.max( 0, this.g - color.g );
  11064. this.b = Math.max( 0, this.b - color.b );
  11065. return this;
  11066. }
  11067. /**
  11068. * Multiplies the RGB values of the given color with the RGB values of this color.
  11069. *
  11070. * @param {Color} color - The color to multiply.
  11071. * @return {Color} A reference to this color.
  11072. */
  11073. multiply( color ) {
  11074. this.r *= color.r;
  11075. this.g *= color.g;
  11076. this.b *= color.b;
  11077. return this;
  11078. }
  11079. /**
  11080. * Multiplies the given scalar value with the RGB values of this color.
  11081. *
  11082. * @param {number} s - The scalar to multiply.
  11083. * @return {Color} A reference to this color.
  11084. */
  11085. multiplyScalar( s ) {
  11086. this.r *= s;
  11087. this.g *= s;
  11088. this.b *= s;
  11089. return this;
  11090. }
  11091. /**
  11092. * Linearly interpolates this color's RGB values toward the RGB values of the
  11093. * given color. The alpha argument can be thought of as the ratio between
  11094. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  11095. *
  11096. * @param {Color} color - The color to converge on.
  11097. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11098. * @return {Color} A reference to this color.
  11099. */
  11100. lerp( color, alpha ) {
  11101. this.r += ( color.r - this.r ) * alpha;
  11102. this.g += ( color.g - this.g ) * alpha;
  11103. this.b += ( color.b - this.b ) * alpha;
  11104. return this;
  11105. }
  11106. /**
  11107. * Linearly interpolates between the given colors and stores the result in this instance.
  11108. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  11109. * is the first and `1.0` is the second color.
  11110. *
  11111. * @param {Color} color1 - The first color.
  11112. * @param {Color} color2 - The second color.
  11113. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11114. * @return {Color} A reference to this color.
  11115. */
  11116. lerpColors( color1, color2, alpha ) {
  11117. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  11118. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  11119. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  11120. return this;
  11121. }
  11122. /**
  11123. * Linearly interpolates this color's HSL values toward the HSL values of the
  11124. * given color. It differs from {@link Color#lerp} by not interpolating straight
  11125. * from one color to the other, but instead going through all the hues in between
  11126. * those two colors. The alpha argument can be thought of as the ratio between
  11127. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  11128. *
  11129. * @param {Color} color - The color to converge on.
  11130. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11131. * @return {Color} A reference to this color.
  11132. */
  11133. lerpHSL( color, alpha ) {
  11134. this.getHSL( _hslA );
  11135. color.getHSL( _hslB );
  11136. const h = lerp( _hslA.h, _hslB.h, alpha );
  11137. const s = lerp( _hslA.s, _hslB.s, alpha );
  11138. const l = lerp( _hslA.l, _hslB.l, alpha );
  11139. this.setHSL( h, s, l );
  11140. return this;
  11141. }
  11142. /**
  11143. * Sets the color's RGB components from the given 3D vector.
  11144. *
  11145. * @param {Vector3} v - The vector to set.
  11146. * @return {Color} A reference to this color.
  11147. */
  11148. setFromVector3( v ) {
  11149. this.r = v.x;
  11150. this.g = v.y;
  11151. this.b = v.z;
  11152. return this;
  11153. }
  11154. /**
  11155. * Transforms this color with the given 3x3 matrix.
  11156. *
  11157. * @param {Matrix3} m - The matrix.
  11158. * @return {Color} A reference to this color.
  11159. */
  11160. applyMatrix3( m ) {
  11161. const r = this.r, g = this.g, b = this.b;
  11162. const e = m.elements;
  11163. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  11164. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  11165. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  11166. return this;
  11167. }
  11168. /**
  11169. * Returns `true` if this color is equal with the given one.
  11170. *
  11171. * @param {Color} c - The color to test for equality.
  11172. * @return {boolean} Whether this bounding color is equal with the given one.
  11173. */
  11174. equals( c ) {
  11175. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  11176. }
  11177. /**
  11178. * Sets this color's RGB components from the given array.
  11179. *
  11180. * @param {Array<number>} array - An array holding the RGB values.
  11181. * @param {number} [offset=0] - The offset into the array.
  11182. * @return {Color} A reference to this color.
  11183. */
  11184. fromArray( array, offset = 0 ) {
  11185. this.r = array[ offset ];
  11186. this.g = array[ offset + 1 ];
  11187. this.b = array[ offset + 2 ];
  11188. return this;
  11189. }
  11190. /**
  11191. * Writes the RGB components of this color to the given array. If no array is provided,
  11192. * the method returns a new instance.
  11193. *
  11194. * @param {Array<number>} [array=[]] - The target array holding the color components.
  11195. * @param {number} [offset=0] - Index of the first element in the array.
  11196. * @return {Array<number>} The color components.
  11197. */
  11198. toArray( array = [], offset = 0 ) {
  11199. array[ offset ] = this.r;
  11200. array[ offset + 1 ] = this.g;
  11201. array[ offset + 2 ] = this.b;
  11202. return array;
  11203. }
  11204. /**
  11205. * Sets the components of this color from the given buffer attribute.
  11206. *
  11207. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  11208. * @param {number} index - The index into the attribute.
  11209. * @return {Color} A reference to this color.
  11210. */
  11211. fromBufferAttribute( attribute, index ) {
  11212. this.r = attribute.getX( index );
  11213. this.g = attribute.getY( index );
  11214. this.b = attribute.getZ( index );
  11215. return this;
  11216. }
  11217. /**
  11218. * This methods defines the serialization result of this class. Returns the color
  11219. * as a hexadecimal value.
  11220. *
  11221. * @return {number} The hexadecimal value.
  11222. */
  11223. toJSON() {
  11224. return this.getHex();
  11225. }
  11226. *[ Symbol.iterator ]() {
  11227. yield this.r;
  11228. yield this.g;
  11229. yield this.b;
  11230. }
  11231. }
  11232. const _color = /*@__PURE__*/ new Color();
  11233. /**
  11234. * A dictionary with X11 color names.
  11235. *
  11236. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  11237. *
  11238. * @static
  11239. * @type {Object}
  11240. */
  11241. Color.NAMES = _colorKeywords;
  11242. /**
  11243. * This class can be used to define an exponential squared fog,
  11244. * which gives a clear view near the camera and a faster than exponentially
  11245. * densening fog farther from the camera.
  11246. *
  11247. * ```js
  11248. * const scene = new THREE.Scene();
  11249. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  11250. * ```
  11251. */
  11252. class FogExp2 {
  11253. /**
  11254. * Constructs a new fog.
  11255. *
  11256. * @param {number|Color} color - The fog's color.
  11257. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  11258. */
  11259. constructor( color, density = 0.00025 ) {
  11260. /**
  11261. * This flag can be used for type testing.
  11262. *
  11263. * @type {boolean}
  11264. * @readonly
  11265. * @default true
  11266. */
  11267. this.isFogExp2 = true;
  11268. /**
  11269. * The name of the fog.
  11270. *
  11271. * @type {string}
  11272. */
  11273. this.name = '';
  11274. /**
  11275. * The fog's color.
  11276. *
  11277. * @type {Color}
  11278. */
  11279. this.color = new Color( color );
  11280. /**
  11281. * Defines how fast the fog will grow dense.
  11282. *
  11283. * @type {number}
  11284. * @default 0.00025
  11285. */
  11286. this.density = density;
  11287. }
  11288. /**
  11289. * Returns a new fog with copied values from this instance.
  11290. *
  11291. * @return {FogExp2} A clone of this instance.
  11292. */
  11293. clone() {
  11294. return new FogExp2( this.color, this.density );
  11295. }
  11296. /**
  11297. * Serializes the fog into JSON.
  11298. *
  11299. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11300. * @return {Object} A JSON object representing the serialized fog
  11301. */
  11302. toJSON( /* meta */ ) {
  11303. return {
  11304. type: 'FogExp2',
  11305. name: this.name,
  11306. color: this.color.getHex(),
  11307. density: this.density
  11308. };
  11309. }
  11310. }
  11311. /**
  11312. * This class can be used to define a linear fog that grows linearly denser
  11313. * with the distance.
  11314. *
  11315. * ```js
  11316. * const scene = new THREE.Scene();
  11317. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  11318. * ```
  11319. */
  11320. class Fog {
  11321. /**
  11322. * Constructs a new fog.
  11323. *
  11324. * @param {number|Color} color - The fog's color.
  11325. * @param {number} [near=1] - The minimum distance to start applying fog.
  11326. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  11327. */
  11328. constructor( color, near = 1, far = 1000 ) {
  11329. /**
  11330. * This flag can be used for type testing.
  11331. *
  11332. * @type {boolean}
  11333. * @readonly
  11334. * @default true
  11335. */
  11336. this.isFog = true;
  11337. /**
  11338. * The name of the fog.
  11339. *
  11340. * @type {string}
  11341. */
  11342. this.name = '';
  11343. /**
  11344. * The fog's color.
  11345. *
  11346. * @type {Color}
  11347. */
  11348. this.color = new Color( color );
  11349. /**
  11350. * The minimum distance to start applying fog. Objects that are less than
  11351. * `near` units from the active camera won't be affected by fog.
  11352. *
  11353. * @type {number}
  11354. * @default 1
  11355. */
  11356. this.near = near;
  11357. /**
  11358. * The maximum distance at which fog stops being calculated and applied.
  11359. * Objects that are more than `far` units away from the active camera won't
  11360. * be affected by fog.
  11361. *
  11362. * @type {number}
  11363. * @default 1000
  11364. */
  11365. this.far = far;
  11366. }
  11367. /**
  11368. * Returns a new fog with copied values from this instance.
  11369. *
  11370. * @return {Fog} A clone of this instance.
  11371. */
  11372. clone() {
  11373. return new Fog( this.color, this.near, this.far );
  11374. }
  11375. /**
  11376. * Serializes the fog into JSON.
  11377. *
  11378. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11379. * @return {Object} A JSON object representing the serialized fog
  11380. */
  11381. toJSON( /* meta */ ) {
  11382. return {
  11383. type: 'Fog',
  11384. name: this.name,
  11385. color: this.color.getHex(),
  11386. near: this.near,
  11387. far: this.far
  11388. };
  11389. }
  11390. }
  11391. /**
  11392. * Scenes allow you to set up what is to be rendered and where by three.js.
  11393. * This is where you place 3D objects like meshes, lines or lights.
  11394. *
  11395. * @augments Object3D
  11396. */
  11397. class Scene extends Object3D {
  11398. /**
  11399. * Constructs a new scene.
  11400. */
  11401. constructor() {
  11402. super();
  11403. /**
  11404. * This flag can be used for type testing.
  11405. *
  11406. * @type {boolean}
  11407. * @readonly
  11408. * @default true
  11409. */
  11410. this.isScene = true;
  11411. this.type = 'Scene';
  11412. /**
  11413. * Defines the background of the scene. Valid inputs are:
  11414. *
  11415. * - A color for defining a uniform colored background.
  11416. * - A texture for defining a (flat) textured background.
  11417. * - Cube textures or equirectangular textures for defining a skybox.
  11418. *
  11419. * @type {?(Color|Texture)}
  11420. * @default null
  11421. */
  11422. this.background = null;
  11423. /**
  11424. * Sets the environment map for all physical materials in the scene. However,
  11425. * it's not possible to overwrite an existing texture assigned to the `envMap`
  11426. * material property.
  11427. *
  11428. * @type {?Texture}
  11429. * @default null
  11430. */
  11431. this.environment = null;
  11432. /**
  11433. * A fog instance defining the type of fog that affects everything
  11434. * rendered in the scene.
  11435. *
  11436. * @type {?(Fog|FogExp2)}
  11437. * @default null
  11438. */
  11439. this.fog = null;
  11440. /**
  11441. * Sets the blurriness of the background. Only influences environment maps
  11442. * assigned to {@link Scene#background}. Valid input is a float between `0`
  11443. * and `1`.
  11444. *
  11445. * @type {number}
  11446. * @default 0
  11447. */
  11448. this.backgroundBlurriness = 0;
  11449. /**
  11450. * Attenuates the color of the background. Only applies to background textures.
  11451. *
  11452. * @type {number}
  11453. * @default 1
  11454. */
  11455. this.backgroundIntensity = 1;
  11456. /**
  11457. * The rotation of the background in radians. Only influences environment maps
  11458. * assigned to {@link Scene#background}.
  11459. *
  11460. * @type {Euler}
  11461. * @default (0,0,0)
  11462. */
  11463. this.backgroundRotation = new Euler();
  11464. /**
  11465. * Attenuates the color of the environment. Only influences environment maps
  11466. * assigned to {@link Scene#environment}.
  11467. *
  11468. * @type {number}
  11469. * @default 1
  11470. */
  11471. this.environmentIntensity = 1;
  11472. /**
  11473. * The rotation of the environment map in radians. Only influences physical materials
  11474. * in the scene when {@link Scene#environment} is used.
  11475. *
  11476. * @type {Euler}
  11477. * @default (0,0,0)
  11478. */
  11479. this.environmentRotation = new Euler();
  11480. /**
  11481. * Forces everything in the scene to be rendered with the defined material. It is possible
  11482. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  11483. *
  11484. * @type {?Material}
  11485. * @default null
  11486. */
  11487. this.overrideMaterial = null;
  11488. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  11489. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  11490. }
  11491. }
  11492. copy( source, recursive ) {
  11493. super.copy( source, recursive );
  11494. if ( source.background !== null ) this.background = source.background.clone();
  11495. if ( source.environment !== null ) this.environment = source.environment.clone();
  11496. if ( source.fog !== null ) this.fog = source.fog.clone();
  11497. this.backgroundBlurriness = source.backgroundBlurriness;
  11498. this.backgroundIntensity = source.backgroundIntensity;
  11499. this.backgroundRotation.copy( source.backgroundRotation );
  11500. this.environmentIntensity = source.environmentIntensity;
  11501. this.environmentRotation.copy( source.environmentRotation );
  11502. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  11503. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11504. return this;
  11505. }
  11506. toJSON( meta ) {
  11507. const data = super.toJSON( meta );
  11508. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  11509. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  11510. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  11511. data.object.backgroundRotation = this.backgroundRotation.toArray();
  11512. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  11513. data.object.environmentRotation = this.environmentRotation.toArray();
  11514. return data;
  11515. }
  11516. }
  11517. const _v0$2 = /*@__PURE__*/ new Vector3();
  11518. const _v1$5 = /*@__PURE__*/ new Vector3();
  11519. const _v2$4 = /*@__PURE__*/ new Vector3();
  11520. const _v3$2 = /*@__PURE__*/ new Vector3();
  11521. const _vab = /*@__PURE__*/ new Vector3();
  11522. const _vac = /*@__PURE__*/ new Vector3();
  11523. const _vbc = /*@__PURE__*/ new Vector3();
  11524. const _vap = /*@__PURE__*/ new Vector3();
  11525. const _vbp = /*@__PURE__*/ new Vector3();
  11526. const _vcp = /*@__PURE__*/ new Vector3();
  11527. const _v40 = /*@__PURE__*/ new Vector4();
  11528. const _v41 = /*@__PURE__*/ new Vector4();
  11529. const _v42 = /*@__PURE__*/ new Vector4();
  11530. /**
  11531. * A geometric triangle as defined by three vectors representing its three corners.
  11532. */
  11533. class Triangle {
  11534. /**
  11535. * Constructs a new triangle.
  11536. *
  11537. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11538. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11539. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11540. */
  11541. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11542. /**
  11543. * The first corner of the triangle.
  11544. *
  11545. * @type {Vector3}
  11546. */
  11547. this.a = a;
  11548. /**
  11549. * The second corner of the triangle.
  11550. *
  11551. * @type {Vector3}
  11552. */
  11553. this.b = b;
  11554. /**
  11555. * The third corner of the triangle.
  11556. *
  11557. * @type {Vector3}
  11558. */
  11559. this.c = c;
  11560. }
  11561. /**
  11562. * Computes the normal vector of a triangle.
  11563. *
  11564. * @param {Vector3} a - The first corner of the triangle.
  11565. * @param {Vector3} b - The second corner of the triangle.
  11566. * @param {Vector3} c - The third corner of the triangle.
  11567. * @param {Vector3} target - The target vector that is used to store the method's result.
  11568. * @return {Vector3} The triangle's normal.
  11569. */
  11570. static getNormal( a, b, c, target ) {
  11571. target.subVectors( c, b );
  11572. _v0$2.subVectors( a, b );
  11573. target.cross( _v0$2 );
  11574. const targetLengthSq = target.lengthSq();
  11575. if ( targetLengthSq > 0 ) {
  11576. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11577. }
  11578. return target.set( 0, 0, 0 );
  11579. }
  11580. /**
  11581. * Computes a barycentric coordinates from the given vector.
  11582. * Returns `null` if the triangle is degenerate.
  11583. *
  11584. * @param {Vector3} point - A point in 3D space.
  11585. * @param {Vector3} a - The first corner of the triangle.
  11586. * @param {Vector3} b - The second corner of the triangle.
  11587. * @param {Vector3} c - The third corner of the triangle.
  11588. * @param {Vector3} target - The target vector that is used to store the method's result.
  11589. * @return {?Vector3} The barycentric coordinates for the given point
  11590. */
  11591. static getBarycoord( point, a, b, c, target ) {
  11592. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11593. _v0$2.subVectors( c, a );
  11594. _v1$5.subVectors( b, a );
  11595. _v2$4.subVectors( point, a );
  11596. const dot00 = _v0$2.dot( _v0$2 );
  11597. const dot01 = _v0$2.dot( _v1$5 );
  11598. const dot02 = _v0$2.dot( _v2$4 );
  11599. const dot11 = _v1$5.dot( _v1$5 );
  11600. const dot12 = _v1$5.dot( _v2$4 );
  11601. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11602. // collinear or singular triangle
  11603. if ( denom === 0 ) {
  11604. target.set( 0, 0, 0 );
  11605. return null;
  11606. }
  11607. const invDenom = 1 / denom;
  11608. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11609. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11610. // barycentric coordinates must always sum to 1
  11611. return target.set( 1 - u - v, v, u );
  11612. }
  11613. /**
  11614. * Returns `true` if the given point, when projected onto the plane of the
  11615. * triangle, lies within the triangle.
  11616. *
  11617. * @param {Vector3} point - The point in 3D space to test.
  11618. * @param {Vector3} a - The first corner of the triangle.
  11619. * @param {Vector3} b - The second corner of the triangle.
  11620. * @param {Vector3} c - The third corner of the triangle.
  11621. * @return {boolean} Whether the given point, when projected onto the plane of the
  11622. * triangle, lies within the triangle or not.
  11623. */
  11624. static containsPoint( point, a, b, c ) {
  11625. // if the triangle is degenerate then we can't contain a point
  11626. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11627. return false;
  11628. }
  11629. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11630. }
  11631. /**
  11632. * Computes the value barycentrically interpolated for the given point on the
  11633. * triangle. Returns `null` if the triangle is degenerate.
  11634. *
  11635. * @param {Vector3} point - Position of interpolated point.
  11636. * @param {Vector3} p1 - The first corner of the triangle.
  11637. * @param {Vector3} p2 - The second corner of the triangle.
  11638. * @param {Vector3} p3 - The third corner of the triangle.
  11639. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11640. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11641. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11642. * @param {Vector3} target - The target vector that is used to store the method's result.
  11643. * @return {?Vector3} The interpolated value.
  11644. */
  11645. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11646. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11647. target.x = 0;
  11648. target.y = 0;
  11649. if ( 'z' in target ) target.z = 0;
  11650. if ( 'w' in target ) target.w = 0;
  11651. return null;
  11652. }
  11653. target.setScalar( 0 );
  11654. target.addScaledVector( v1, _v3$2.x );
  11655. target.addScaledVector( v2, _v3$2.y );
  11656. target.addScaledVector( v3, _v3$2.z );
  11657. return target;
  11658. }
  11659. /**
  11660. * Computes the value barycentrically interpolated for the given attribute and indices.
  11661. *
  11662. * @param {BufferAttribute} attr - The attribute to interpolate.
  11663. * @param {number} i1 - Index of first vertex.
  11664. * @param {number} i2 - Index of second vertex.
  11665. * @param {number} i3 - Index of third vertex.
  11666. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11667. * @param {Vector3} target - The target vector that is used to store the method's result.
  11668. * @return {Vector3} The interpolated attribute value.
  11669. */
  11670. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11671. _v40.setScalar( 0 );
  11672. _v41.setScalar( 0 );
  11673. _v42.setScalar( 0 );
  11674. _v40.fromBufferAttribute( attr, i1 );
  11675. _v41.fromBufferAttribute( attr, i2 );
  11676. _v42.fromBufferAttribute( attr, i3 );
  11677. target.setScalar( 0 );
  11678. target.addScaledVector( _v40, barycoord.x );
  11679. target.addScaledVector( _v41, barycoord.y );
  11680. target.addScaledVector( _v42, barycoord.z );
  11681. return target;
  11682. }
  11683. /**
  11684. * Returns `true` if the triangle is oriented towards the given direction.
  11685. *
  11686. * @param {Vector3} a - The first corner of the triangle.
  11687. * @param {Vector3} b - The second corner of the triangle.
  11688. * @param {Vector3} c - The third corner of the triangle.
  11689. * @param {Vector3} direction - The (normalized) direction vector.
  11690. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11691. */
  11692. static isFrontFacing( a, b, c, direction ) {
  11693. _v0$2.subVectors( c, b );
  11694. _v1$5.subVectors( a, b );
  11695. // strictly front facing
  11696. return _v0$2.cross( _v1$5 ).dot( direction ) < 0;
  11697. }
  11698. /**
  11699. * Sets the triangle's vertices by copying the given values.
  11700. *
  11701. * @param {Vector3} a - The first corner of the triangle.
  11702. * @param {Vector3} b - The second corner of the triangle.
  11703. * @param {Vector3} c - The third corner of the triangle.
  11704. * @return {Triangle} A reference to this triangle.
  11705. */
  11706. set( a, b, c ) {
  11707. this.a.copy( a );
  11708. this.b.copy( b );
  11709. this.c.copy( c );
  11710. return this;
  11711. }
  11712. /**
  11713. * Sets the triangle's vertices by copying the given array values.
  11714. *
  11715. * @param {Array<Vector3>} points - An array with 3D points.
  11716. * @param {number} i0 - The array index representing the first corner of the triangle.
  11717. * @param {number} i1 - The array index representing the second corner of the triangle.
  11718. * @param {number} i2 - The array index representing the third corner of the triangle.
  11719. * @return {Triangle} A reference to this triangle.
  11720. */
  11721. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11722. this.a.copy( points[ i0 ] );
  11723. this.b.copy( points[ i1 ] );
  11724. this.c.copy( points[ i2 ] );
  11725. return this;
  11726. }
  11727. /**
  11728. * Sets the triangle's vertices by copying the given attribute values.
  11729. *
  11730. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11731. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11732. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11733. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11734. * @return {Triangle} A reference to this triangle.
  11735. */
  11736. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11737. this.a.fromBufferAttribute( attribute, i0 );
  11738. this.b.fromBufferAttribute( attribute, i1 );
  11739. this.c.fromBufferAttribute( attribute, i2 );
  11740. return this;
  11741. }
  11742. /**
  11743. * Returns a new triangle with copied values from this instance.
  11744. *
  11745. * @return {Triangle} A clone of this instance.
  11746. */
  11747. clone() {
  11748. return new this.constructor().copy( this );
  11749. }
  11750. /**
  11751. * Copies the values of the given triangle to this instance.
  11752. *
  11753. * @param {Triangle} triangle - The triangle to copy.
  11754. * @return {Triangle} A reference to this triangle.
  11755. */
  11756. copy( triangle ) {
  11757. this.a.copy( triangle.a );
  11758. this.b.copy( triangle.b );
  11759. this.c.copy( triangle.c );
  11760. return this;
  11761. }
  11762. /**
  11763. * Computes the area of the triangle.
  11764. *
  11765. * @return {number} The triangle's area.
  11766. */
  11767. getArea() {
  11768. _v0$2.subVectors( this.c, this.b );
  11769. _v1$5.subVectors( this.a, this.b );
  11770. return _v0$2.cross( _v1$5 ).length() * 0.5;
  11771. }
  11772. /**
  11773. * Computes the midpoint of the triangle.
  11774. *
  11775. * @param {Vector3} target - The target vector that is used to store the method's result.
  11776. * @return {Vector3} The triangle's midpoint.
  11777. */
  11778. getMidpoint( target ) {
  11779. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11780. }
  11781. /**
  11782. * Computes the normal of the triangle.
  11783. *
  11784. * @param {Vector3} target - The target vector that is used to store the method's result.
  11785. * @return {Vector3} The triangle's normal.
  11786. */
  11787. getNormal( target ) {
  11788. return Triangle.getNormal( this.a, this.b, this.c, target );
  11789. }
  11790. /**
  11791. * Computes a plane the triangle lies within.
  11792. *
  11793. * @param {Plane} target - The target vector that is used to store the method's result.
  11794. * @return {Plane} The plane the triangle lies within.
  11795. */
  11796. getPlane( target ) {
  11797. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11798. }
  11799. /**
  11800. * Computes a barycentric coordinates from the given vector.
  11801. * Returns `null` if the triangle is degenerate.
  11802. *
  11803. * @param {Vector3} point - A point in 3D space.
  11804. * @param {Vector3} target - The target vector that is used to store the method's result.
  11805. * @return {?Vector3} The barycentric coordinates for the given point
  11806. */
  11807. getBarycoord( point, target ) {
  11808. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11809. }
  11810. /**
  11811. * Computes the value barycentrically interpolated for the given point on the
  11812. * triangle. Returns `null` if the triangle is degenerate.
  11813. *
  11814. * @param {Vector3} point - Position of interpolated point.
  11815. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11816. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11817. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11818. * @param {Vector3} target - The target vector that is used to store the method's result.
  11819. * @return {?Vector3} The interpolated value.
  11820. */
  11821. getInterpolation( point, v1, v2, v3, target ) {
  11822. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11823. }
  11824. /**
  11825. * Returns `true` if the given point, when projected onto the plane of the
  11826. * triangle, lies within the triangle.
  11827. *
  11828. * @param {Vector3} point - The point in 3D space to test.
  11829. * @return {boolean} Whether the given point, when projected onto the plane of the
  11830. * triangle, lies within the triangle or not.
  11831. */
  11832. containsPoint( point ) {
  11833. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11834. }
  11835. /**
  11836. * Returns `true` if the triangle is oriented towards the given direction.
  11837. *
  11838. * @param {Vector3} direction - The (normalized) direction vector.
  11839. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11840. */
  11841. isFrontFacing( direction ) {
  11842. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11843. }
  11844. /**
  11845. * Returns `true` if this triangle intersects with the given box.
  11846. *
  11847. * @param {Box3} box - The box to intersect.
  11848. * @return {boolean} Whether this triangle intersects with the given box or not.
  11849. */
  11850. intersectsBox( box ) {
  11851. return box.intersectsTriangle( this );
  11852. }
  11853. /**
  11854. * Returns the closest point on the triangle to the given point.
  11855. *
  11856. * @param {Vector3} p - The point to compute the closest point for.
  11857. * @param {Vector3} target - The target vector that is used to store the method's result.
  11858. * @return {Vector3} The closest point on the triangle.
  11859. */
  11860. closestPointToPoint( p, target ) {
  11861. const a = this.a, b = this.b, c = this.c;
  11862. let v, w;
  11863. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11864. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11865. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11866. // basically, we're distinguishing which of the voronoi regions of the triangle
  11867. // the point lies in with the minimum amount of redundant computation.
  11868. _vab.subVectors( b, a );
  11869. _vac.subVectors( c, a );
  11870. _vap.subVectors( p, a );
  11871. const d1 = _vab.dot( _vap );
  11872. const d2 = _vac.dot( _vap );
  11873. if ( d1 <= 0 && d2 <= 0 ) {
  11874. // vertex region of A; barycentric coords (1, 0, 0)
  11875. return target.copy( a );
  11876. }
  11877. _vbp.subVectors( p, b );
  11878. const d3 = _vab.dot( _vbp );
  11879. const d4 = _vac.dot( _vbp );
  11880. if ( d3 >= 0 && d4 <= d3 ) {
  11881. // vertex region of B; barycentric coords (0, 1, 0)
  11882. return target.copy( b );
  11883. }
  11884. const vc = d1 * d4 - d3 * d2;
  11885. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11886. v = d1 / ( d1 - d3 );
  11887. // edge region of AB; barycentric coords (1-v, v, 0)
  11888. return target.copy( a ).addScaledVector( _vab, v );
  11889. }
  11890. _vcp.subVectors( p, c );
  11891. const d5 = _vab.dot( _vcp );
  11892. const d6 = _vac.dot( _vcp );
  11893. if ( d6 >= 0 && d5 <= d6 ) {
  11894. // vertex region of C; barycentric coords (0, 0, 1)
  11895. return target.copy( c );
  11896. }
  11897. const vb = d5 * d2 - d1 * d6;
  11898. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11899. w = d2 / ( d2 - d6 );
  11900. // edge region of AC; barycentric coords (1-w, 0, w)
  11901. return target.copy( a ).addScaledVector( _vac, w );
  11902. }
  11903. const va = d3 * d6 - d5 * d4;
  11904. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11905. _vbc.subVectors( c, b );
  11906. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11907. // edge region of BC; barycentric coords (0, 1-w, w)
  11908. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11909. }
  11910. // face region
  11911. const denom = 1 / ( va + vb + vc );
  11912. // u = va * denom
  11913. v = vb * denom;
  11914. w = vc * denom;
  11915. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11916. }
  11917. /**
  11918. * Returns `true` if this triangle is equal with the given one.
  11919. *
  11920. * @param {Triangle} triangle - The triangle to test for equality.
  11921. * @return {boolean} Whether this triangle is equal with the given one.
  11922. */
  11923. equals( triangle ) {
  11924. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11925. }
  11926. }
  11927. /**
  11928. * Represents an axis-aligned bounding box (AABB) in 3D space.
  11929. */
  11930. class Box3 {
  11931. /**
  11932. * Constructs a new bounding box.
  11933. *
  11934. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  11935. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  11936. */
  11937. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  11938. /**
  11939. * This flag can be used for type testing.
  11940. *
  11941. * @type {boolean}
  11942. * @readonly
  11943. * @default true
  11944. */
  11945. this.isBox3 = true;
  11946. /**
  11947. * The lower boundary of the box.
  11948. *
  11949. * @type {Vector3}
  11950. */
  11951. this.min = min;
  11952. /**
  11953. * The upper boundary of the box.
  11954. *
  11955. * @type {Vector3}
  11956. */
  11957. this.max = max;
  11958. }
  11959. /**
  11960. * Sets the lower and upper boundaries of this box.
  11961. * Please note that this method only copies the values from the given objects.
  11962. *
  11963. * @param {Vector3} min - The lower boundary of the box.
  11964. * @param {Vector3} max - The upper boundary of the box.
  11965. * @return {Box3} A reference to this bounding box.
  11966. */
  11967. set( min, max ) {
  11968. this.min.copy( min );
  11969. this.max.copy( max );
  11970. return this;
  11971. }
  11972. /**
  11973. * Sets the upper and lower bounds of this box so it encloses the position data
  11974. * in the given array.
  11975. *
  11976. * @param {Array<number>} array - An array holding 3D position data.
  11977. * @return {Box3} A reference to this bounding box.
  11978. */
  11979. setFromArray( array ) {
  11980. this.makeEmpty();
  11981. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  11982. this.expandByPoint( _vector$b.fromArray( array, i ) );
  11983. }
  11984. return this;
  11985. }
  11986. /**
  11987. * Sets the upper and lower bounds of this box so it encloses the position data
  11988. * in the given buffer attribute.
  11989. *
  11990. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  11991. * @return {Box3} A reference to this bounding box.
  11992. */
  11993. setFromBufferAttribute( attribute ) {
  11994. this.makeEmpty();
  11995. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  11996. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  11997. }
  11998. return this;
  11999. }
  12000. /**
  12001. * Sets the upper and lower bounds of this box so it encloses the position data
  12002. * in the given array.
  12003. *
  12004. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  12005. * @return {Box3} A reference to this bounding box.
  12006. */
  12007. setFromPoints( points ) {
  12008. this.makeEmpty();
  12009. for ( let i = 0, il = points.length; i < il; i ++ ) {
  12010. this.expandByPoint( points[ i ] );
  12011. }
  12012. return this;
  12013. }
  12014. /**
  12015. * Centers this box on the given center vector and sets this box's width, height and
  12016. * depth to the given size values.
  12017. *
  12018. * @param {Vector3} center - The center of the box.
  12019. * @param {Vector3} size - The x, y and z dimensions of the box.
  12020. * @return {Box3} A reference to this bounding box.
  12021. */
  12022. setFromCenterAndSize( center, size ) {
  12023. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  12024. this.min.copy( center ).sub( halfSize );
  12025. this.max.copy( center ).add( halfSize );
  12026. return this;
  12027. }
  12028. /**
  12029. * Computes the world-axis-aligned bounding box for the given 3D object
  12030. * (including its children), accounting for the object's, and children's,
  12031. * world transforms. The function may result in a larger box than strictly necessary.
  12032. *
  12033. * Note: To compute the correct bounding box, make sure the given 3D object
  12034. * has an up-to-date world matrix that reflects the current transformation of its
  12035. * ancestor nodes. Call `object.updateWorldMatrix( true, false )` beforehand if
  12036. * you're unsure.
  12037. *
  12038. * @param {Object3D} object - The 3D object to compute the bounding box for.
  12039. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  12040. * world-axis-aligned bounding box at the expense of more computation.
  12041. * @return {Box3} A reference to this bounding box.
  12042. */
  12043. setFromObject( object, precise = false ) {
  12044. this.makeEmpty();
  12045. return this.expandByObject( object, precise );
  12046. }
  12047. /**
  12048. * Returns a new box with copied values from this instance.
  12049. *
  12050. * @return {Box3} A clone of this instance.
  12051. */
  12052. clone() {
  12053. return new this.constructor().copy( this );
  12054. }
  12055. /**
  12056. * Copies the values of the given box to this instance.
  12057. *
  12058. * @param {Box3} box - The box to copy.
  12059. * @return {Box3} A reference to this bounding box.
  12060. */
  12061. copy( box ) {
  12062. this.min.copy( box.min );
  12063. this.max.copy( box.max );
  12064. return this;
  12065. }
  12066. /**
  12067. * Makes this box empty which means in encloses a zero space in 3D.
  12068. *
  12069. * @return {Box3} A reference to this bounding box.
  12070. */
  12071. makeEmpty() {
  12072. this.min.x = this.min.y = this.min.z = + Infinity;
  12073. this.max.x = this.max.y = this.max.z = - Infinity;
  12074. return this;
  12075. }
  12076. /**
  12077. * Returns true if this box includes zero points within its bounds.
  12078. * Note that a box with equal lower and upper bounds still includes one
  12079. * point, the one both bounds share.
  12080. *
  12081. * @return {boolean} Whether this box is empty or not.
  12082. */
  12083. isEmpty() {
  12084. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  12085. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  12086. }
  12087. /**
  12088. * Returns the center point of this box.
  12089. *
  12090. * @param {Vector3} target - The target vector that is used to store the method's result.
  12091. * @return {Vector3} The center point.
  12092. */
  12093. getCenter( target ) {
  12094. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  12095. }
  12096. /**
  12097. * Returns the dimensions of this box.
  12098. *
  12099. * @param {Vector3} target - The target vector that is used to store the method's result.
  12100. * @return {Vector3} The size.
  12101. */
  12102. getSize( target ) {
  12103. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  12104. }
  12105. /**
  12106. * Expands the boundaries of this box to include the given point.
  12107. *
  12108. * @param {Vector3} point - The point that should be included by the bounding box.
  12109. * @return {Box3} A reference to this bounding box.
  12110. */
  12111. expandByPoint( point ) {
  12112. this.min.min( point );
  12113. this.max.max( point );
  12114. return this;
  12115. }
  12116. /**
  12117. * Expands this box equilaterally by the given vector. The width of this
  12118. * box will be expanded by the x component of the vector in both
  12119. * directions. The height of this box will be expanded by the y component of
  12120. * the vector in both directions. The depth of this box will be
  12121. * expanded by the z component of the vector in both directions.
  12122. *
  12123. * @param {Vector3} vector - The vector that should expand the bounding box.
  12124. * @return {Box3} A reference to this bounding box.
  12125. */
  12126. expandByVector( vector ) {
  12127. this.min.sub( vector );
  12128. this.max.add( vector );
  12129. return this;
  12130. }
  12131. /**
  12132. * Expands each dimension of the box by the given scalar. If negative, the
  12133. * dimensions of the box will be contracted.
  12134. *
  12135. * @param {number} scalar - The scalar value that should expand the bounding box.
  12136. * @return {Box3} A reference to this bounding box.
  12137. */
  12138. expandByScalar( scalar ) {
  12139. this.min.addScalar( - scalar );
  12140. this.max.addScalar( scalar );
  12141. return this;
  12142. }
  12143. /**
  12144. * Expands the boundaries of this box to include the given 3D object and
  12145. * its children, accounting for the object's, and children's, world
  12146. * transforms. The function may result in a larger box than strictly
  12147. * necessary (unless the precise parameter is set to true).
  12148. *
  12149. * @param {Object3D} object - The 3D object that should expand the bounding box.
  12150. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  12151. * as little as necessary at the expense of more computation.
  12152. * @return {Box3} A reference to this bounding box.
  12153. */
  12154. expandByObject( object, precise = false ) {
  12155. // Computes the world-axis-aligned bounding box of an object (including its children),
  12156. // accounting for both the object's, and children's, world transforms
  12157. object.updateWorldMatrix( false, false );
  12158. const geometry = object.geometry;
  12159. if ( geometry !== undefined ) {
  12160. const positionAttribute = geometry.getAttribute( 'position' );
  12161. // precise AABB computation based on vertex data requires at least a position attribute.
  12162. // instancing isn't supported so far and uses the normal (conservative) code path.
  12163. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  12164. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  12165. if ( object.isMesh === true ) {
  12166. object.getVertexPosition( i, _vector$b );
  12167. } else {
  12168. _vector$b.fromBufferAttribute( positionAttribute, i );
  12169. }
  12170. _vector$b.applyMatrix4( object.matrixWorld );
  12171. this.expandByPoint( _vector$b );
  12172. }
  12173. } else {
  12174. if ( object.boundingBox !== undefined ) {
  12175. // object-level bounding box
  12176. if ( object.boundingBox === null ) {
  12177. object.computeBoundingBox();
  12178. }
  12179. _box$4.copy( object.boundingBox );
  12180. } else {
  12181. // geometry-level bounding box
  12182. if ( geometry.boundingBox === null ) {
  12183. geometry.computeBoundingBox();
  12184. }
  12185. _box$4.copy( geometry.boundingBox );
  12186. }
  12187. _box$4.applyMatrix4( object.matrixWorld );
  12188. this.union( _box$4 );
  12189. }
  12190. }
  12191. const children = object.children;
  12192. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12193. this.expandByObject( children[ i ], precise );
  12194. }
  12195. return this;
  12196. }
  12197. /**
  12198. * Returns `true` if the given point lies within or on the boundaries of this box.
  12199. *
  12200. * @param {Vector3} point - The point to test.
  12201. * @return {boolean} Whether the bounding box contains the given point or not.
  12202. */
  12203. containsPoint( point ) {
  12204. return point.x >= this.min.x && point.x <= this.max.x &&
  12205. point.y >= this.min.y && point.y <= this.max.y &&
  12206. point.z >= this.min.z && point.z <= this.max.z;
  12207. }
  12208. /**
  12209. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  12210. * If this box and the given one are identical, this function also returns `true`.
  12211. *
  12212. * @param {Box3} box - The bounding box to test.
  12213. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  12214. */
  12215. containsBox( box ) {
  12216. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  12217. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  12218. this.min.z <= box.min.z && box.max.z <= this.max.z;
  12219. }
  12220. /**
  12221. * Returns a point as a proportion of this box's width, height and depth.
  12222. *
  12223. * @param {Vector3} point - A point in 3D space.
  12224. * @param {Vector3} target - The target vector that is used to store the method's result.
  12225. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  12226. */
  12227. getParameter( point, target ) {
  12228. // This can potentially have a divide by zero if the box
  12229. // has a size dimension of 0.
  12230. return target.set(
  12231. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  12232. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  12233. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  12234. );
  12235. }
  12236. /**
  12237. * Returns `true` if the given bounding box intersects with this bounding box.
  12238. *
  12239. * @param {Box3} box - The bounding box to test.
  12240. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  12241. */
  12242. intersectsBox( box ) {
  12243. // using 6 splitting planes to rule out intersections.
  12244. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  12245. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  12246. box.max.z >= this.min.z && box.min.z <= this.max.z;
  12247. }
  12248. /**
  12249. * Returns `true` if the given bounding sphere intersects with this bounding box.
  12250. *
  12251. * @param {Sphere} sphere - The bounding sphere to test.
  12252. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  12253. */
  12254. intersectsSphere( sphere ) {
  12255. // Find the point on the AABB closest to the sphere center.
  12256. this.clampPoint( sphere.center, _vector$b );
  12257. // If that point is inside the sphere, the AABB and sphere intersect.
  12258. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  12259. }
  12260. /**
  12261. * Returns `true` if the given plane intersects with this bounding box.
  12262. *
  12263. * @param {Plane} plane - The plane to test.
  12264. * @return {boolean} Whether the given plane intersects with this bounding box.
  12265. */
  12266. intersectsPlane( plane ) {
  12267. // We compute the minimum and maximum dot product values. If those values
  12268. // are on the same side (back or front) of the plane, then there is no intersection.
  12269. let min, max;
  12270. if ( plane.normal.x > 0 ) {
  12271. min = plane.normal.x * this.min.x;
  12272. max = plane.normal.x * this.max.x;
  12273. } else {
  12274. min = plane.normal.x * this.max.x;
  12275. max = plane.normal.x * this.min.x;
  12276. }
  12277. if ( plane.normal.y > 0 ) {
  12278. min += plane.normal.y * this.min.y;
  12279. max += plane.normal.y * this.max.y;
  12280. } else {
  12281. min += plane.normal.y * this.max.y;
  12282. max += plane.normal.y * this.min.y;
  12283. }
  12284. if ( plane.normal.z > 0 ) {
  12285. min += plane.normal.z * this.min.z;
  12286. max += plane.normal.z * this.max.z;
  12287. } else {
  12288. min += plane.normal.z * this.max.z;
  12289. max += plane.normal.z * this.min.z;
  12290. }
  12291. return ( min <= - plane.constant && max >= - plane.constant );
  12292. }
  12293. /**
  12294. * Returns `true` if the given triangle intersects with this bounding box.
  12295. *
  12296. * @param {Triangle} triangle - The triangle to test.
  12297. * @return {boolean} Whether the given triangle intersects with this bounding box.
  12298. */
  12299. intersectsTriangle( triangle ) {
  12300. if ( this.isEmpty() ) {
  12301. return false;
  12302. }
  12303. // compute box center and extents
  12304. this.getCenter( _center );
  12305. _extents.subVectors( this.max, _center );
  12306. // translate triangle to aabb origin
  12307. _v0$1.subVectors( triangle.a, _center );
  12308. _v1$4.subVectors( triangle.b, _center );
  12309. _v2$3.subVectors( triangle.c, _center );
  12310. // compute edge vectors for triangle
  12311. _f0.subVectors( _v1$4, _v0$1 );
  12312. _f1.subVectors( _v2$3, _v1$4 );
  12313. _f2.subVectors( _v0$1, _v2$3 );
  12314. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  12315. // 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
  12316. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  12317. let axes = [
  12318. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  12319. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  12320. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  12321. ];
  12322. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12323. return false;
  12324. }
  12325. // test 3 face normals from the aabb
  12326. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  12327. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12328. return false;
  12329. }
  12330. // finally testing the face normal of the triangle
  12331. // use already existing triangle edge vectors here
  12332. _triangleNormal.crossVectors( _f0, _f1 );
  12333. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  12334. return satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents );
  12335. }
  12336. /**
  12337. * Clamps the given point within the bounds of this box.
  12338. *
  12339. * @param {Vector3} point - The point to clamp.
  12340. * @param {Vector3} target - The target vector that is used to store the method's result.
  12341. * @return {Vector3} The clamped point.
  12342. */
  12343. clampPoint( point, target ) {
  12344. return target.copy( point ).clamp( this.min, this.max );
  12345. }
  12346. /**
  12347. * Returns the euclidean distance from any edge of this box to the specified point. If
  12348. * the given point lies inside of this box, the distance will be `0`.
  12349. *
  12350. * @param {Vector3} point - The point to compute the distance to.
  12351. * @return {number} The euclidean distance.
  12352. */
  12353. distanceToPoint( point ) {
  12354. return this.clampPoint( point, _vector$b ).distanceTo( point );
  12355. }
  12356. /**
  12357. * Returns a bounding sphere that encloses this bounding box.
  12358. *
  12359. * @param {Sphere} target - The target sphere that is used to store the method's result.
  12360. * @return {Sphere} The bounding sphere that encloses this bounding box.
  12361. */
  12362. getBoundingSphere( target ) {
  12363. if ( this.isEmpty() ) {
  12364. target.makeEmpty();
  12365. } else {
  12366. this.getCenter( target.center );
  12367. target.radius = this.getSize( _vector$b ).length() * 0.5;
  12368. }
  12369. return target;
  12370. }
  12371. /**
  12372. * Computes the intersection of this bounding box and the given one, setting the upper
  12373. * bound of this box to the lesser of the two boxes' upper bounds and the
  12374. * lower bound of this box to the greater of the two boxes' lower bounds. If
  12375. * there's no overlap, makes this box empty.
  12376. *
  12377. * @param {Box3} box - The bounding box to intersect with.
  12378. * @return {Box3} A reference to this bounding box.
  12379. */
  12380. intersect( box ) {
  12381. this.min.max( box.min );
  12382. this.max.min( box.max );
  12383. // 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.
  12384. if ( this.isEmpty() ) this.makeEmpty();
  12385. return this;
  12386. }
  12387. /**
  12388. * Computes the union of this box and another and the given one, setting the upper
  12389. * bound of this box to the greater of the two boxes' upper bounds and the
  12390. * lower bound of this box to the lesser of the two boxes' lower bounds.
  12391. *
  12392. * @param {Box3} box - The bounding box that will be unioned with this instance.
  12393. * @return {Box3} A reference to this bounding box.
  12394. */
  12395. union( box ) {
  12396. this.min.min( box.min );
  12397. this.max.max( box.max );
  12398. return this;
  12399. }
  12400. /**
  12401. * Transforms this bounding box by the given 4x4 transformation matrix.
  12402. *
  12403. * @param {Matrix4} matrix - The transformation matrix.
  12404. * @return {Box3} A reference to this bounding box.
  12405. */
  12406. applyMatrix4( matrix ) {
  12407. // transform of empty box is an empty box.
  12408. if ( this.isEmpty() ) return this;
  12409. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  12410. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  12411. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  12412. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  12413. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  12414. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  12415. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  12416. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  12417. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  12418. this.setFromPoints( _points );
  12419. return this;
  12420. }
  12421. /**
  12422. * Adds the given offset to both the upper and lower bounds of this bounding box,
  12423. * effectively moving it in 3D space.
  12424. *
  12425. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  12426. * @return {Box3} A reference to this bounding box.
  12427. */
  12428. translate( offset ) {
  12429. this.min.add( offset );
  12430. this.max.add( offset );
  12431. return this;
  12432. }
  12433. /**
  12434. * Returns `true` if this bounding box is equal with the given one.
  12435. *
  12436. * @param {Box3} box - The box to test for equality.
  12437. * @return {boolean} Whether this bounding box is equal with the given one.
  12438. */
  12439. equals( box ) {
  12440. return box.min.equals( this.min ) && box.max.equals( this.max );
  12441. }
  12442. /**
  12443. * Returns a serialized structure of the bounding box.
  12444. *
  12445. * @return {Object} Serialized structure with fields representing the object state.
  12446. */
  12447. toJSON() {
  12448. return {
  12449. min: this.min.toArray(),
  12450. max: this.max.toArray()
  12451. };
  12452. }
  12453. /**
  12454. * Returns a serialized structure of the bounding box.
  12455. *
  12456. * @param {Object} json - The serialized json to set the box from.
  12457. * @return {Box3} A reference to this bounding box.
  12458. */
  12459. fromJSON( json ) {
  12460. this.min.fromArray( json.min );
  12461. this.max.fromArray( json.max );
  12462. return this;
  12463. }
  12464. }
  12465. const _points = [
  12466. /*@__PURE__*/ new Vector3(),
  12467. /*@__PURE__*/ new Vector3(),
  12468. /*@__PURE__*/ new Vector3(),
  12469. /*@__PURE__*/ new Vector3(),
  12470. /*@__PURE__*/ new Vector3(),
  12471. /*@__PURE__*/ new Vector3(),
  12472. /*@__PURE__*/ new Vector3(),
  12473. /*@__PURE__*/ new Vector3()
  12474. ];
  12475. const _vector$b = /*@__PURE__*/ new Vector3();
  12476. const _box$4 = /*@__PURE__*/ new Box3();
  12477. // triangle centered vertices
  12478. const _v0$1 = /*@__PURE__*/ new Vector3();
  12479. const _v1$4 = /*@__PURE__*/ new Vector3();
  12480. const _v2$3 = /*@__PURE__*/ new Vector3();
  12481. // triangle edge vectors
  12482. const _f0 = /*@__PURE__*/ new Vector3();
  12483. const _f1 = /*@__PURE__*/ new Vector3();
  12484. const _f2 = /*@__PURE__*/ new Vector3();
  12485. const _center = /*@__PURE__*/ new Vector3();
  12486. const _extents = /*@__PURE__*/ new Vector3();
  12487. const _triangleNormal = /*@__PURE__*/ new Vector3();
  12488. const _testAxis = /*@__PURE__*/ new Vector3();
  12489. function satForAxes( axes, v0, v1, v2, extents ) {
  12490. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  12491. _testAxis.fromArray( axes, i );
  12492. // project the aabb onto the separating axis
  12493. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  12494. // project all 3 vertices of the triangle onto the separating axis
  12495. const p0 = v0.dot( _testAxis );
  12496. const p1 = v1.dot( _testAxis );
  12497. const p2 = v2.dot( _testAxis );
  12498. // actual test, basically see if either of the most extreme of the triangle points intersects r
  12499. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  12500. // points of the projected triangle are outside the projected half-length of the aabb
  12501. // the axis is separating and we can exit
  12502. return false;
  12503. }
  12504. }
  12505. return true;
  12506. }
  12507. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  12508. const _tables = /*@__PURE__*/ _generateTables();
  12509. function _generateTables() {
  12510. // float32 to float16 helpers
  12511. const buffer = new ArrayBuffer( 4 );
  12512. const floatView = new Float32Array( buffer );
  12513. const uint32View = new Uint32Array( buffer );
  12514. const baseTable = new Uint32Array( 512 );
  12515. const shiftTable = new Uint32Array( 512 );
  12516. for ( let i = 0; i < 256; ++ i ) {
  12517. const e = i - 127;
  12518. // very small number (0, -0)
  12519. if ( e < -27 ) {
  12520. baseTable[ i ] = 0x0000;
  12521. baseTable[ i | 0x100 ] = 0x8000;
  12522. shiftTable[ i ] = 24;
  12523. shiftTable[ i | 0x100 ] = 24;
  12524. // small number (denorm)
  12525. } else if ( e < -14 ) {
  12526. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  12527. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  12528. shiftTable[ i ] = - e - 1;
  12529. shiftTable[ i | 0x100 ] = - e - 1;
  12530. // normal number
  12531. } else if ( e <= 15 ) {
  12532. baseTable[ i ] = ( e + 15 ) << 10;
  12533. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  12534. shiftTable[ i ] = 13;
  12535. shiftTable[ i | 0x100 ] = 13;
  12536. // large number (Infinity, -Infinity)
  12537. } else if ( e < 128 ) {
  12538. baseTable[ i ] = 0x7c00;
  12539. baseTable[ i | 0x100 ] = 0xfc00;
  12540. shiftTable[ i ] = 24;
  12541. shiftTable[ i | 0x100 ] = 24;
  12542. // stay (NaN, Infinity, -Infinity)
  12543. } else {
  12544. baseTable[ i ] = 0x7c00;
  12545. baseTable[ i | 0x100 ] = 0xfc00;
  12546. shiftTable[ i ] = 13;
  12547. shiftTable[ i | 0x100 ] = 13;
  12548. }
  12549. }
  12550. // float16 to float32 helpers
  12551. const mantissaTable = new Uint32Array( 2048 );
  12552. const exponentTable = new Uint32Array( 64 );
  12553. const offsetTable = new Uint32Array( 64 );
  12554. for ( let i = 1; i < 1024; ++ i ) {
  12555. let m = i << 13; // zero pad mantissa bits
  12556. let e = 0; // zero exponent
  12557. // normalized
  12558. while ( ( m & 0x00800000 ) === 0 ) {
  12559. m <<= 1;
  12560. e -= 0x00800000; // decrement exponent
  12561. }
  12562. m &= -8388609; // clear leading 1 bit
  12563. e += 0x38800000; // adjust bias
  12564. mantissaTable[ i ] = m | e;
  12565. }
  12566. for ( let i = 1024; i < 2048; ++ i ) {
  12567. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  12568. }
  12569. for ( let i = 1; i < 31; ++ i ) {
  12570. exponentTable[ i ] = i << 23;
  12571. }
  12572. exponentTable[ 31 ] = 0x47800000;
  12573. exponentTable[ 32 ] = 0x80000000;
  12574. for ( let i = 33; i < 63; ++ i ) {
  12575. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  12576. }
  12577. exponentTable[ 63 ] = 0xc7800000;
  12578. for ( let i = 1; i < 64; ++ i ) {
  12579. if ( i !== 32 ) {
  12580. offsetTable[ i ] = 1024;
  12581. }
  12582. }
  12583. return {
  12584. floatView: floatView,
  12585. uint32View: uint32View,
  12586. baseTable: baseTable,
  12587. shiftTable: shiftTable,
  12588. mantissaTable: mantissaTable,
  12589. exponentTable: exponentTable,
  12590. offsetTable: offsetTable
  12591. };
  12592. }
  12593. /**
  12594. * Returns a half precision floating point value (FP16) from the given single
  12595. * precision floating point value (FP32).
  12596. *
  12597. * @param {number} val - A single precision floating point value.
  12598. * @return {number} The FP16 value.
  12599. */
  12600. function toHalfFloat( val ) {
  12601. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  12602. val = clamp( val, -65504, 65504 );
  12603. _tables.floatView[ 0 ] = val;
  12604. const f = _tables.uint32View[ 0 ];
  12605. const e = ( f >> 23 ) & 0x1ff;
  12606. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  12607. }
  12608. /**
  12609. * Returns a single precision floating point value (FP32) from the given half
  12610. * precision floating point value (FP16).
  12611. *
  12612. * @param {number} val - A half precision floating point value.
  12613. * @return {number} The FP32 value.
  12614. */
  12615. function fromHalfFloat( val ) {
  12616. const m = val >> 10;
  12617. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  12618. return _tables.floatView[ 0 ];
  12619. }
  12620. /**
  12621. * A class containing utility functions for data.
  12622. *
  12623. * @hideconstructor
  12624. */
  12625. class DataUtils {
  12626. /**
  12627. * Returns a half precision floating point value (FP16) from the given single
  12628. * precision floating point value (FP32).
  12629. *
  12630. * @param {number} val - A single precision floating point value.
  12631. * @return {number} The FP16 value.
  12632. */
  12633. static toHalfFloat( val ) {
  12634. return toHalfFloat( val );
  12635. }
  12636. /**
  12637. * Returns a single precision floating point value (FP32) from the given half
  12638. * precision floating point value (FP16).
  12639. *
  12640. * @param {number} val - A half precision floating point value.
  12641. * @return {number} The FP32 value.
  12642. */
  12643. static fromHalfFloat( val ) {
  12644. return fromHalfFloat( val );
  12645. }
  12646. }
  12647. const _vector$a = /*@__PURE__*/ new Vector3();
  12648. const _vector2$1 = /*@__PURE__*/ new Vector2();
  12649. let _id$2 = 0;
  12650. /**
  12651. * This class stores data for an attribute (such as vertex positions, face
  12652. * indices, normals, colors, UVs, and any custom attributes ) associated with
  12653. * a geometry, which allows for more efficient passing of data to the GPU.
  12654. *
  12655. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  12656. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  12657. */
  12658. class BufferAttribute extends EventDispatcher {
  12659. /**
  12660. * Constructs a new buffer attribute.
  12661. *
  12662. * @param {TypedArray} array - The array holding the attribute data.
  12663. * @param {number} itemSize - The item size.
  12664. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  12665. */
  12666. constructor( array, itemSize, normalized = false ) {
  12667. super();
  12668. if ( Array.isArray( array ) ) {
  12669. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12670. }
  12671. /**
  12672. * This flag can be used for type testing.
  12673. *
  12674. * @type {boolean}
  12675. * @readonly
  12676. * @default true
  12677. */
  12678. this.isBufferAttribute = true;
  12679. /**
  12680. * The ID of the buffer attribute.
  12681. *
  12682. * @name BufferAttribute#id
  12683. * @type {number}
  12684. * @readonly
  12685. */
  12686. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  12687. /**
  12688. * The name of the buffer attribute.
  12689. *
  12690. * @type {string}
  12691. */
  12692. this.name = '';
  12693. /**
  12694. * The array holding the attribute data. It should have `itemSize * numVertices`
  12695. * elements, where `numVertices` is the number of vertices in the associated geometry.
  12696. *
  12697. * @type {TypedArray}
  12698. */
  12699. this.array = array;
  12700. /**
  12701. * The number of values of the array that should be associated with a particular vertex.
  12702. * For instance, if this attribute is storing a 3-component vector (such as a position,
  12703. * normal, or color), then the value should be `3`.
  12704. *
  12705. * @type {number}
  12706. */
  12707. this.itemSize = itemSize;
  12708. /**
  12709. * Represents the number of items this buffer attribute stores. It is internally computed
  12710. * by dividing the `array` length by the `itemSize`.
  12711. *
  12712. * @type {number}
  12713. * @readonly
  12714. */
  12715. this.count = array !== undefined ? array.length / itemSize : 0;
  12716. /**
  12717. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  12718. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  12719. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  12720. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  12721. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  12722. *
  12723. * @type {boolean}
  12724. */
  12725. this.normalized = normalized;
  12726. /**
  12727. * Defines the intended usage pattern of the data store for optimization purposes.
  12728. *
  12729. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  12730. * instantiate a new one and set the desired usage before the next render.
  12731. *
  12732. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  12733. * @default StaticDrawUsage
  12734. */
  12735. this.usage = StaticDrawUsage;
  12736. /**
  12737. * This can be used to only update some components of stored vectors (for example, just the
  12738. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  12739. *
  12740. * @type {Array<Object>}
  12741. */
  12742. this.updateRanges = [];
  12743. /**
  12744. * Configures the bound GPU type for use in shaders.
  12745. *
  12746. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  12747. * For lower precision float types, use `Float16BufferAttribute`.
  12748. *
  12749. * @type {(FloatType|IntType)}
  12750. * @default FloatType
  12751. */
  12752. this.gpuType = FloatType;
  12753. /**
  12754. * A version number, incremented every time the `needsUpdate` is set to `true`.
  12755. *
  12756. * @type {number}
  12757. */
  12758. this.version = 0;
  12759. }
  12760. /**
  12761. * A callback function that is executed after the renderer has transferred the attribute
  12762. * array data to the GPU.
  12763. */
  12764. onUploadCallback() {}
  12765. /**
  12766. * Flag to indicate that this attribute has changed and should be re-sent to
  12767. * the GPU. Set this to `true` when you modify the value of the array.
  12768. *
  12769. * @type {number}
  12770. * @default false
  12771. * @param {boolean} value
  12772. */
  12773. set needsUpdate( value ) {
  12774. if ( value === true ) this.version ++;
  12775. }
  12776. /**
  12777. * Sets the usage of this buffer attribute.
  12778. *
  12779. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  12780. * @return {BufferAttribute} A reference to this buffer attribute.
  12781. */
  12782. setUsage( value ) {
  12783. this.usage = value;
  12784. return this;
  12785. }
  12786. /**
  12787. * Adds a range of data in the data array to be updated on the GPU.
  12788. *
  12789. * @param {number} start - Position at which to start update.
  12790. * @param {number} count - The number of components to update.
  12791. */
  12792. addUpdateRange( start, count ) {
  12793. this.updateRanges.push( { start, count } );
  12794. }
  12795. /**
  12796. * Clears the update ranges.
  12797. */
  12798. clearUpdateRanges() {
  12799. this.updateRanges.length = 0;
  12800. }
  12801. /**
  12802. * Copies the values of the given buffer attribute to this instance.
  12803. *
  12804. * @param {BufferAttribute} source - The buffer attribute to copy.
  12805. * @return {BufferAttribute} A reference to this instance.
  12806. */
  12807. copy( source ) {
  12808. this.name = source.name;
  12809. this.array = new source.array.constructor( source.array );
  12810. this.itemSize = source.itemSize;
  12811. this.count = source.count;
  12812. this.normalized = source.normalized;
  12813. this.usage = source.usage;
  12814. this.gpuType = source.gpuType;
  12815. return this;
  12816. }
  12817. /**
  12818. * Copies a vector from the given buffer attribute to this one. The start
  12819. * and destination position in the attribute buffers are represented by the
  12820. * given indices.
  12821. *
  12822. * @param {number} index1 - The destination index into this buffer attribute.
  12823. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  12824. * @param {number} index2 - The source index into the given buffer attribute.
  12825. * @return {BufferAttribute} A reference to this instance.
  12826. */
  12827. copyAt( index1, attribute, index2 ) {
  12828. index1 *= this.itemSize;
  12829. index2 *= attribute.itemSize;
  12830. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  12831. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  12832. }
  12833. return this;
  12834. }
  12835. /**
  12836. * Copies the given array data into this buffer attribute.
  12837. *
  12838. * @param {(TypedArray|Array)} array - The array to copy.
  12839. * @return {BufferAttribute} A reference to this instance.
  12840. */
  12841. copyArray( array ) {
  12842. this.array.set( array );
  12843. return this;
  12844. }
  12845. /**
  12846. * Applies the given 3x3 matrix to the given attribute. Works with
  12847. * item size `2` and `3`.
  12848. *
  12849. * @param {Matrix3} m - The matrix to apply.
  12850. * @return {BufferAttribute} A reference to this instance.
  12851. */
  12852. applyMatrix3( m ) {
  12853. if ( this.itemSize === 2 ) {
  12854. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12855. _vector2$1.fromBufferAttribute( this, i );
  12856. _vector2$1.applyMatrix3( m );
  12857. this.setXY( i, _vector2$1.x, _vector2$1.y );
  12858. }
  12859. } else if ( this.itemSize === 3 ) {
  12860. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12861. _vector$a.fromBufferAttribute( this, i );
  12862. _vector$a.applyMatrix3( m );
  12863. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12864. }
  12865. }
  12866. return this;
  12867. }
  12868. /**
  12869. * Applies the given 4x4 matrix to the given attribute. Only works with
  12870. * item size `3`.
  12871. *
  12872. * @param {Matrix4} m - The matrix to apply.
  12873. * @return {BufferAttribute} A reference to this instance.
  12874. */
  12875. applyMatrix4( m ) {
  12876. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12877. _vector$a.fromBufferAttribute( this, i );
  12878. _vector$a.applyMatrix4( m );
  12879. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12880. }
  12881. return this;
  12882. }
  12883. /**
  12884. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  12885. * item size `3`.
  12886. *
  12887. * @param {Matrix3} m - The normal matrix to apply.
  12888. * @return {BufferAttribute} A reference to this instance.
  12889. */
  12890. applyNormalMatrix( m ) {
  12891. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12892. _vector$a.fromBufferAttribute( this, i );
  12893. _vector$a.applyNormalMatrix( m );
  12894. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12895. }
  12896. return this;
  12897. }
  12898. /**
  12899. * Applies the given 4x4 matrix to the given attribute. Only works with
  12900. * item size `3` and with direction vectors.
  12901. *
  12902. * @param {Matrix4} m - The matrix to apply.
  12903. * @return {BufferAttribute} A reference to this instance.
  12904. */
  12905. transformDirection( m ) {
  12906. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12907. _vector$a.fromBufferAttribute( this, i );
  12908. _vector$a.transformDirection( m );
  12909. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12910. }
  12911. return this;
  12912. }
  12913. /**
  12914. * Sets the given array data in the buffer attribute.
  12915. *
  12916. * @param {(TypedArray|Array)} value - The array data to set.
  12917. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  12918. * @return {BufferAttribute} A reference to this instance.
  12919. */
  12920. set( value, offset = 0 ) {
  12921. // Matching BufferAttribute constructor, do not normalize the array.
  12922. this.array.set( value, offset );
  12923. return this;
  12924. }
  12925. /**
  12926. * Returns the given component of the vector at the given index.
  12927. *
  12928. * @param {number} index - The index into the buffer attribute.
  12929. * @param {number} component - The component index.
  12930. * @return {number} The returned value.
  12931. */
  12932. getComponent( index, component ) {
  12933. let value = this.array[ index * this.itemSize + component ];
  12934. if ( this.normalized ) value = denormalize( value, this.array );
  12935. return value;
  12936. }
  12937. /**
  12938. * Sets the given value to the given component of the vector at the given index.
  12939. *
  12940. * @param {number} index - The index into the buffer attribute.
  12941. * @param {number} component - The component index.
  12942. * @param {number} value - The value to set.
  12943. * @return {BufferAttribute} A reference to this instance.
  12944. */
  12945. setComponent( index, component, value ) {
  12946. if ( this.normalized ) value = normalize( value, this.array );
  12947. this.array[ index * this.itemSize + component ] = value;
  12948. return this;
  12949. }
  12950. /**
  12951. * Returns the x component of the vector at the given index.
  12952. *
  12953. * @param {number} index - The index into the buffer attribute.
  12954. * @return {number} The x component.
  12955. */
  12956. getX( index ) {
  12957. let x = this.array[ index * this.itemSize ];
  12958. if ( this.normalized ) x = denormalize( x, this.array );
  12959. return x;
  12960. }
  12961. /**
  12962. * Sets the x component of the vector at the given index.
  12963. *
  12964. * @param {number} index - The index into the buffer attribute.
  12965. * @param {number} x - The value to set.
  12966. * @return {BufferAttribute} A reference to this instance.
  12967. */
  12968. setX( index, x ) {
  12969. if ( this.normalized ) x = normalize( x, this.array );
  12970. this.array[ index * this.itemSize ] = x;
  12971. return this;
  12972. }
  12973. /**
  12974. * Returns the y component of the vector at the given index.
  12975. *
  12976. * @param {number} index - The index into the buffer attribute.
  12977. * @return {number} The y component.
  12978. */
  12979. getY( index ) {
  12980. let y = this.array[ index * this.itemSize + 1 ];
  12981. if ( this.normalized ) y = denormalize( y, this.array );
  12982. return y;
  12983. }
  12984. /**
  12985. * Sets the y component of the vector at the given index.
  12986. *
  12987. * @param {number} index - The index into the buffer attribute.
  12988. * @param {number} y - The value to set.
  12989. * @return {BufferAttribute} A reference to this instance.
  12990. */
  12991. setY( index, y ) {
  12992. if ( this.normalized ) y = normalize( y, this.array );
  12993. this.array[ index * this.itemSize + 1 ] = y;
  12994. return this;
  12995. }
  12996. /**
  12997. * Returns the z component of the vector at the given index.
  12998. *
  12999. * @param {number} index - The index into the buffer attribute.
  13000. * @return {number} The z component.
  13001. */
  13002. getZ( index ) {
  13003. let z = this.array[ index * this.itemSize + 2 ];
  13004. if ( this.normalized ) z = denormalize( z, this.array );
  13005. return z;
  13006. }
  13007. /**
  13008. * Sets the z component of the vector at the given index.
  13009. *
  13010. * @param {number} index - The index into the buffer attribute.
  13011. * @param {number} z - The value to set.
  13012. * @return {BufferAttribute} A reference to this instance.
  13013. */
  13014. setZ( index, z ) {
  13015. if ( this.normalized ) z = normalize( z, this.array );
  13016. this.array[ index * this.itemSize + 2 ] = z;
  13017. return this;
  13018. }
  13019. /**
  13020. * Returns the w component of the vector at the given index.
  13021. *
  13022. * @param {number} index - The index into the buffer attribute.
  13023. * @return {number} The w component.
  13024. */
  13025. getW( index ) {
  13026. let w = this.array[ index * this.itemSize + 3 ];
  13027. if ( this.normalized ) w = denormalize( w, this.array );
  13028. return w;
  13029. }
  13030. /**
  13031. * Sets the w component of the vector at the given index.
  13032. *
  13033. * @param {number} index - The index into the buffer attribute.
  13034. * @param {number} w - The value to set.
  13035. * @return {BufferAttribute} A reference to this instance.
  13036. */
  13037. setW( index, w ) {
  13038. if ( this.normalized ) w = normalize( w, this.array );
  13039. this.array[ index * this.itemSize + 3 ] = w;
  13040. return this;
  13041. }
  13042. /**
  13043. * Sets the x and y component of the vector at the given index.
  13044. *
  13045. * @param {number} index - The index into the buffer attribute.
  13046. * @param {number} x - The value for the x component to set.
  13047. * @param {number} y - The value for the y component to set.
  13048. * @return {BufferAttribute} A reference to this instance.
  13049. */
  13050. setXY( index, x, y ) {
  13051. index *= this.itemSize;
  13052. if ( this.normalized ) {
  13053. x = normalize( x, this.array );
  13054. y = normalize( y, this.array );
  13055. }
  13056. this.array[ index + 0 ] = x;
  13057. this.array[ index + 1 ] = y;
  13058. return this;
  13059. }
  13060. /**
  13061. * Sets the x, y and z component of the vector at the given index.
  13062. *
  13063. * @param {number} index - The index into the buffer attribute.
  13064. * @param {number} x - The value for the x component to set.
  13065. * @param {number} y - The value for the y component to set.
  13066. * @param {number} z - The value for the z component to set.
  13067. * @return {BufferAttribute} A reference to this instance.
  13068. */
  13069. setXYZ( index, x, y, z ) {
  13070. index *= this.itemSize;
  13071. if ( this.normalized ) {
  13072. x = normalize( x, this.array );
  13073. y = normalize( y, this.array );
  13074. z = normalize( z, this.array );
  13075. }
  13076. this.array[ index + 0 ] = x;
  13077. this.array[ index + 1 ] = y;
  13078. this.array[ index + 2 ] = z;
  13079. return this;
  13080. }
  13081. /**
  13082. * Sets the x, y, z and w component of the vector at the given index.
  13083. *
  13084. * @param {number} index - The index into the buffer attribute.
  13085. * @param {number} x - The value for the x component to set.
  13086. * @param {number} y - The value for the y component to set.
  13087. * @param {number} z - The value for the z component to set.
  13088. * @param {number} w - The value for the w component to set.
  13089. * @return {BufferAttribute} A reference to this instance.
  13090. */
  13091. setXYZW( index, x, y, z, w ) {
  13092. index *= this.itemSize;
  13093. if ( this.normalized ) {
  13094. x = normalize( x, this.array );
  13095. y = normalize( y, this.array );
  13096. z = normalize( z, this.array );
  13097. w = normalize( w, this.array );
  13098. }
  13099. this.array[ index + 0 ] = x;
  13100. this.array[ index + 1 ] = y;
  13101. this.array[ index + 2 ] = z;
  13102. this.array[ index + 3 ] = w;
  13103. return this;
  13104. }
  13105. /**
  13106. * Sets the given callback function that is executed after the Renderer has transferred
  13107. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13108. * the upload when attribute data are not needed anymore on the CPU side.
  13109. *
  13110. * @param {Function} callback - The `onUpload()` callback.
  13111. * @return {BufferAttribute} A reference to this instance.
  13112. */
  13113. onUpload( callback ) {
  13114. this.onUploadCallback = callback;
  13115. return this;
  13116. }
  13117. /**
  13118. * Returns a new buffer attribute with copied values from this instance.
  13119. *
  13120. * @return {BufferAttribute} A clone of this instance.
  13121. */
  13122. clone() {
  13123. return new this.constructor( this.array, this.itemSize ).copy( this );
  13124. }
  13125. /**
  13126. * Serializes the buffer attribute into JSON.
  13127. *
  13128. * @return {Object} A JSON object representing the serialized buffer attribute.
  13129. */
  13130. toJSON() {
  13131. const data = {
  13132. itemSize: this.itemSize,
  13133. type: this.array.constructor.name,
  13134. array: Array.from( this.array ),
  13135. normalized: this.normalized
  13136. };
  13137. if ( this.name !== '' ) data.name = this.name;
  13138. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13139. return data;
  13140. }
  13141. /**
  13142. * Disposes of the buffer attribute. Available only in {@link WebGPURenderer}.
  13143. */
  13144. dispose() {
  13145. this.dispatchEvent( { type: 'dispose' } );
  13146. }
  13147. }
  13148. /**
  13149. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13150. * a plain `Array` instance.
  13151. *
  13152. * @augments BufferAttribute
  13153. */
  13154. class Int8BufferAttribute extends BufferAttribute {
  13155. /**
  13156. * Constructs a new buffer attribute.
  13157. *
  13158. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13159. * @param {number} itemSize - The item size.
  13160. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13161. */
  13162. constructor( array, itemSize, normalized ) {
  13163. super( new Int8Array( array ), itemSize, normalized );
  13164. }
  13165. }
  13166. /**
  13167. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13168. * a plain `Array` instance.
  13169. *
  13170. * @augments BufferAttribute
  13171. */
  13172. class Uint8BufferAttribute extends BufferAttribute {
  13173. /**
  13174. * Constructs a new buffer attribute.
  13175. *
  13176. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13177. * @param {number} itemSize - The item size.
  13178. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13179. */
  13180. constructor( array, itemSize, normalized ) {
  13181. super( new Uint8Array( array ), itemSize, normalized );
  13182. }
  13183. }
  13184. /**
  13185. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13186. * a plain `Array` instance.
  13187. *
  13188. * @augments BufferAttribute
  13189. */
  13190. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13191. /**
  13192. * Constructs a new buffer attribute.
  13193. *
  13194. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13195. * @param {number} itemSize - The item size.
  13196. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13197. */
  13198. constructor( array, itemSize, normalized ) {
  13199. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13200. }
  13201. }
  13202. /**
  13203. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13204. * a plain `Array` instance.
  13205. *
  13206. * @augments BufferAttribute
  13207. */
  13208. class Int16BufferAttribute extends BufferAttribute {
  13209. /**
  13210. * Constructs a new buffer attribute.
  13211. *
  13212. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13213. * @param {number} itemSize - The item size.
  13214. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13215. */
  13216. constructor( array, itemSize, normalized ) {
  13217. super( new Int16Array( array ), itemSize, normalized );
  13218. }
  13219. }
  13220. /**
  13221. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13222. * a plain `Array` instance.
  13223. *
  13224. * @augments BufferAttribute
  13225. */
  13226. class Uint16BufferAttribute extends BufferAttribute {
  13227. /**
  13228. * Constructs a new buffer attribute.
  13229. *
  13230. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13231. * @param {number} itemSize - The item size.
  13232. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13233. */
  13234. constructor( array, itemSize, normalized ) {
  13235. super( new Uint16Array( array ), itemSize, normalized );
  13236. }
  13237. }
  13238. /**
  13239. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13240. * a plain `Array` instance.
  13241. *
  13242. * @augments BufferAttribute
  13243. */
  13244. class Int32BufferAttribute extends BufferAttribute {
  13245. /**
  13246. * Constructs a new buffer attribute.
  13247. *
  13248. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13249. * @param {number} itemSize - The item size.
  13250. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13251. */
  13252. constructor( array, itemSize, normalized ) {
  13253. super( new Int32Array( array ), itemSize, normalized );
  13254. }
  13255. }
  13256. /**
  13257. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13258. * a plain `Array` instance.
  13259. *
  13260. * @augments BufferAttribute
  13261. */
  13262. class Uint32BufferAttribute extends BufferAttribute {
  13263. /**
  13264. * Constructs a new buffer attribute.
  13265. *
  13266. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13267. * @param {number} itemSize - The item size.
  13268. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13269. */
  13270. constructor( array, itemSize, normalized ) {
  13271. super( new Uint32Array( array ), itemSize, normalized );
  13272. }
  13273. }
  13274. /**
  13275. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13276. * a plain `Array` instance.
  13277. *
  13278. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  13279. * browser support is still problematic.
  13280. *
  13281. * @augments BufferAttribute
  13282. */
  13283. class Float16BufferAttribute extends BufferAttribute {
  13284. /**
  13285. * Constructs a new buffer attribute.
  13286. *
  13287. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13288. * @param {number} itemSize - The item size.
  13289. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13290. */
  13291. constructor( array, itemSize, normalized ) {
  13292. super( new Uint16Array( array ), itemSize, normalized );
  13293. this.isFloat16BufferAttribute = true;
  13294. }
  13295. getX( index ) {
  13296. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  13297. if ( this.normalized ) x = denormalize( x, this.array );
  13298. return x;
  13299. }
  13300. setX( index, x ) {
  13301. if ( this.normalized ) x = normalize( x, this.array );
  13302. this.array[ index * this.itemSize ] = toHalfFloat( x );
  13303. return this;
  13304. }
  13305. getY( index ) {
  13306. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  13307. if ( this.normalized ) y = denormalize( y, this.array );
  13308. return y;
  13309. }
  13310. setY( index, y ) {
  13311. if ( this.normalized ) y = normalize( y, this.array );
  13312. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  13313. return this;
  13314. }
  13315. getZ( index ) {
  13316. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  13317. if ( this.normalized ) z = denormalize( z, this.array );
  13318. return z;
  13319. }
  13320. setZ( index, z ) {
  13321. if ( this.normalized ) z = normalize( z, this.array );
  13322. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  13323. return this;
  13324. }
  13325. getW( index ) {
  13326. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  13327. if ( this.normalized ) w = denormalize( w, this.array );
  13328. return w;
  13329. }
  13330. setW( index, w ) {
  13331. if ( this.normalized ) w = normalize( w, this.array );
  13332. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  13333. return this;
  13334. }
  13335. setXY( index, x, y ) {
  13336. index *= this.itemSize;
  13337. if ( this.normalized ) {
  13338. x = normalize( x, this.array );
  13339. y = normalize( y, this.array );
  13340. }
  13341. this.array[ index + 0 ] = toHalfFloat( x );
  13342. this.array[ index + 1 ] = toHalfFloat( y );
  13343. return this;
  13344. }
  13345. setXYZ( index, x, y, z ) {
  13346. index *= this.itemSize;
  13347. if ( this.normalized ) {
  13348. x = normalize( x, this.array );
  13349. y = normalize( y, this.array );
  13350. z = normalize( z, this.array );
  13351. }
  13352. this.array[ index + 0 ] = toHalfFloat( x );
  13353. this.array[ index + 1 ] = toHalfFloat( y );
  13354. this.array[ index + 2 ] = toHalfFloat( z );
  13355. return this;
  13356. }
  13357. setXYZW( index, x, y, z, w ) {
  13358. index *= this.itemSize;
  13359. if ( this.normalized ) {
  13360. x = normalize( x, this.array );
  13361. y = normalize( y, this.array );
  13362. z = normalize( z, this.array );
  13363. w = normalize( w, this.array );
  13364. }
  13365. this.array[ index + 0 ] = toHalfFloat( x );
  13366. this.array[ index + 1 ] = toHalfFloat( y );
  13367. this.array[ index + 2 ] = toHalfFloat( z );
  13368. this.array[ index + 3 ] = toHalfFloat( w );
  13369. return this;
  13370. }
  13371. }
  13372. /**
  13373. * Convenient class that can be used when creating a `Float32` buffer attribute with
  13374. * a plain `Array` instance.
  13375. *
  13376. * @augments BufferAttribute
  13377. */
  13378. class Float32BufferAttribute extends BufferAttribute {
  13379. /**
  13380. * Constructs a new buffer attribute.
  13381. *
  13382. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  13383. * @param {number} itemSize - The item size.
  13384. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13385. */
  13386. constructor( array, itemSize, normalized ) {
  13387. super( new Float32Array( array ), itemSize, normalized );
  13388. }
  13389. }
  13390. const _box$3 = /*@__PURE__*/ new Box3();
  13391. const _v1$3 = /*@__PURE__*/ new Vector3();
  13392. const _v2$2 = /*@__PURE__*/ new Vector3();
  13393. /**
  13394. * An analytical 3D sphere defined by a center and radius. This class is mainly
  13395. * used as a Bounding Sphere for 3D objects.
  13396. */
  13397. class Sphere {
  13398. /**
  13399. * Constructs a new sphere.
  13400. *
  13401. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  13402. * @param {number} [radius=-1] - The radius of the sphere.
  13403. */
  13404. constructor( center = new Vector3(), radius = -1 ) {
  13405. /**
  13406. * This flag can be used for type testing.
  13407. *
  13408. * @type {boolean}
  13409. * @readonly
  13410. * @default true
  13411. */
  13412. this.isSphere = true;
  13413. /**
  13414. * The center of the sphere
  13415. *
  13416. * @type {Vector3}
  13417. */
  13418. this.center = center;
  13419. /**
  13420. * The radius of the sphere.
  13421. *
  13422. * @type {number}
  13423. */
  13424. this.radius = radius;
  13425. }
  13426. /**
  13427. * Sets the sphere's components by copying the given values.
  13428. *
  13429. * @param {Vector3} center - The center.
  13430. * @param {number} radius - The radius.
  13431. * @return {Sphere} A reference to this sphere.
  13432. */
  13433. set( center, radius ) {
  13434. this.center.copy( center );
  13435. this.radius = radius;
  13436. return this;
  13437. }
  13438. /**
  13439. * Computes the minimum bounding sphere for list of points.
  13440. * If the optional center point is given, it is used as the sphere's
  13441. * center. Otherwise, the center of the axis-aligned bounding box
  13442. * encompassing the points is calculated.
  13443. *
  13444. * @param {Array<Vector3>} points - A list of points in 3D space.
  13445. * @param {Vector3} [optionalCenter] - The center of the sphere.
  13446. * @return {Sphere} A reference to this sphere.
  13447. */
  13448. setFromPoints( points, optionalCenter ) {
  13449. const center = this.center;
  13450. if ( optionalCenter !== undefined ) {
  13451. center.copy( optionalCenter );
  13452. } else {
  13453. _box$3.setFromPoints( points ).getCenter( center );
  13454. }
  13455. let maxRadiusSq = 0;
  13456. for ( let i = 0, il = points.length; i < il; i ++ ) {
  13457. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  13458. }
  13459. this.radius = Math.sqrt( maxRadiusSq );
  13460. return this;
  13461. }
  13462. /**
  13463. * Copies the values of the given sphere to this instance.
  13464. *
  13465. * @param {Sphere} sphere - The sphere to copy.
  13466. * @return {Sphere} A reference to this sphere.
  13467. */
  13468. copy( sphere ) {
  13469. this.center.copy( sphere.center );
  13470. this.radius = sphere.radius;
  13471. return this;
  13472. }
  13473. /**
  13474. * Returns `true` if the sphere is empty (the radius set to a negative number).
  13475. *
  13476. * Spheres with a radius of `0` contain only their center point and are not
  13477. * considered to be empty.
  13478. *
  13479. * @return {boolean} Whether this sphere is empty or not.
  13480. */
  13481. isEmpty() {
  13482. return ( this.radius < 0 );
  13483. }
  13484. /**
  13485. * Makes this sphere empty which means in encloses a zero space in 3D.
  13486. *
  13487. * @return {Sphere} A reference to this sphere.
  13488. */
  13489. makeEmpty() {
  13490. this.center.set( 0, 0, 0 );
  13491. this.radius = -1;
  13492. return this;
  13493. }
  13494. /**
  13495. * Returns `true` if this sphere contains the given point inclusive of
  13496. * the surface of the sphere.
  13497. *
  13498. * @param {Vector3} point - The point to check.
  13499. * @return {boolean} Whether this sphere contains the given point or not.
  13500. */
  13501. containsPoint( point ) {
  13502. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  13503. }
  13504. /**
  13505. * Returns the closest distance from the boundary of the sphere to the
  13506. * given point. If the sphere contains the point, the distance will
  13507. * be negative.
  13508. *
  13509. * @param {Vector3} point - The point to compute the distance to.
  13510. * @return {number} The distance to the point.
  13511. */
  13512. distanceToPoint( point ) {
  13513. return ( point.distanceTo( this.center ) - this.radius );
  13514. }
  13515. /**
  13516. * Returns `true` if this sphere intersects with the given one.
  13517. *
  13518. * @param {Sphere} sphere - The sphere to test.
  13519. * @return {boolean} Whether this sphere intersects with the given one or not.
  13520. */
  13521. intersectsSphere( sphere ) {
  13522. const radiusSum = this.radius + sphere.radius;
  13523. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  13524. }
  13525. /**
  13526. * Returns `true` if this sphere intersects with the given box.
  13527. *
  13528. * @param {Box3} box - The box to test.
  13529. * @return {boolean} Whether this sphere intersects with the given box or not.
  13530. */
  13531. intersectsBox( box ) {
  13532. return box.intersectsSphere( this );
  13533. }
  13534. /**
  13535. * Returns `true` if this sphere intersects with the given plane.
  13536. *
  13537. * @param {Plane} plane - The plane to test.
  13538. * @return {boolean} Whether this sphere intersects with the given plane or not.
  13539. */
  13540. intersectsPlane( plane ) {
  13541. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  13542. }
  13543. /**
  13544. * Clamps a point within the sphere. If the point is outside the sphere, it
  13545. * will clamp it to the closest point on the edge of the sphere. Points
  13546. * already inside the sphere will not be affected.
  13547. *
  13548. * @param {Vector3} point - The plane to clamp.
  13549. * @param {Vector3} target - The target vector that is used to store the method's result.
  13550. * @return {Vector3} The clamped point.
  13551. */
  13552. clampPoint( point, target ) {
  13553. const deltaLengthSq = this.center.distanceToSquared( point );
  13554. target.copy( point );
  13555. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  13556. target.sub( this.center ).normalize();
  13557. target.multiplyScalar( this.radius ).add( this.center );
  13558. }
  13559. return target;
  13560. }
  13561. /**
  13562. * Returns a bounding box that encloses this sphere.
  13563. *
  13564. * @param {Box3} target - The target box that is used to store the method's result.
  13565. * @return {Box3} The bounding box that encloses this sphere.
  13566. */
  13567. getBoundingBox( target ) {
  13568. if ( this.isEmpty() ) {
  13569. // Empty sphere produces empty bounding box
  13570. target.makeEmpty();
  13571. return target;
  13572. }
  13573. target.set( this.center, this.center );
  13574. target.expandByScalar( this.radius );
  13575. return target;
  13576. }
  13577. /**
  13578. * Transforms this sphere with the given 4x4 transformation matrix.
  13579. *
  13580. * @param {Matrix4} matrix - The transformation matrix.
  13581. * @return {Sphere} A reference to this sphere.
  13582. */
  13583. applyMatrix4( matrix ) {
  13584. this.center.applyMatrix4( matrix );
  13585. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  13586. return this;
  13587. }
  13588. /**
  13589. * Translates the sphere's center by the given offset.
  13590. *
  13591. * @param {Vector3} offset - The offset.
  13592. * @return {Sphere} A reference to this sphere.
  13593. */
  13594. translate( offset ) {
  13595. this.center.add( offset );
  13596. return this;
  13597. }
  13598. /**
  13599. * Expands the boundaries of this sphere to include the given point.
  13600. *
  13601. * @param {Vector3} point - The point to include.
  13602. * @return {Sphere} A reference to this sphere.
  13603. */
  13604. expandByPoint( point ) {
  13605. if ( this.isEmpty() ) {
  13606. this.center.copy( point );
  13607. this.radius = 0;
  13608. return this;
  13609. }
  13610. _v1$3.subVectors( point, this.center );
  13611. const lengthSq = _v1$3.lengthSq();
  13612. if ( lengthSq > ( this.radius * this.radius ) ) {
  13613. // calculate the minimal sphere
  13614. const length = Math.sqrt( lengthSq );
  13615. const delta = ( length - this.radius ) * 0.5;
  13616. this.center.addScaledVector( _v1$3, delta / length );
  13617. this.radius += delta;
  13618. }
  13619. return this;
  13620. }
  13621. /**
  13622. * Expands this sphere to enclose both the original sphere and the given sphere.
  13623. *
  13624. * @param {Sphere} sphere - The sphere to include.
  13625. * @return {Sphere} A reference to this sphere.
  13626. */
  13627. union( sphere ) {
  13628. if ( sphere.isEmpty() ) {
  13629. return this;
  13630. }
  13631. if ( this.isEmpty() ) {
  13632. this.copy( sphere );
  13633. return this;
  13634. }
  13635. if ( this.center.equals( sphere.center ) === true ) {
  13636. this.radius = Math.max( this.radius, sphere.radius );
  13637. } else {
  13638. _v2$2.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  13639. this.expandByPoint( _v1$3.copy( sphere.center ).add( _v2$2 ) );
  13640. this.expandByPoint( _v1$3.copy( sphere.center ).sub( _v2$2 ) );
  13641. }
  13642. return this;
  13643. }
  13644. /**
  13645. * Returns `true` if this sphere is equal with the given one.
  13646. *
  13647. * @param {Sphere} sphere - The sphere to test for equality.
  13648. * @return {boolean} Whether this bounding sphere is equal with the given one.
  13649. */
  13650. equals( sphere ) {
  13651. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  13652. }
  13653. /**
  13654. * Returns a new sphere with copied values from this instance.
  13655. *
  13656. * @return {Sphere} A clone of this instance.
  13657. */
  13658. clone() {
  13659. return new this.constructor().copy( this );
  13660. }
  13661. /**
  13662. * Returns a serialized structure of the bounding sphere.
  13663. *
  13664. * @return {Object} Serialized structure with fields representing the object state.
  13665. */
  13666. toJSON() {
  13667. return {
  13668. radius: this.radius,
  13669. center: this.center.toArray()
  13670. };
  13671. }
  13672. /**
  13673. * Returns a serialized structure of the bounding sphere.
  13674. *
  13675. * @param {Object} json - The serialized json to set the sphere from.
  13676. * @return {Sphere} A reference to this bounding sphere.
  13677. */
  13678. fromJSON( json ) {
  13679. this.radius = json.radius;
  13680. this.center.fromArray( json.center );
  13681. return this;
  13682. }
  13683. }
  13684. let _id$1 = 0;
  13685. const _m1 = /*@__PURE__*/ new Matrix4();
  13686. const _obj = /*@__PURE__*/ new Object3D();
  13687. const _offset = /*@__PURE__*/ new Vector3();
  13688. const _box$2 = /*@__PURE__*/ new Box3();
  13689. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  13690. const _vector$9 = /*@__PURE__*/ new Vector3();
  13691. /**
  13692. * A representation of mesh, line, or point geometry. Includes vertex
  13693. * positions, face indices, normals, colors, UVs, and custom attributes
  13694. * within buffers, reducing the cost of passing all this data to the GPU.
  13695. *
  13696. * ```js
  13697. * const geometry = new THREE.BufferGeometry();
  13698. * // create a simple square shape. We duplicate the top left and bottom right
  13699. * // vertices because each vertex needs to appear once per triangle.
  13700. * const vertices = new Float32Array( [
  13701. * -1.0, -1.0, 1.0, // v0
  13702. * 1.0, -1.0, 1.0, // v1
  13703. * 1.0, 1.0, 1.0, // v2
  13704. *
  13705. * 1.0, 1.0, 1.0, // v3
  13706. * -1.0, 1.0, 1.0, // v4
  13707. * -1.0, -1.0, 1.0 // v5
  13708. * ] );
  13709. * // itemSize = 3 because there are 3 values (components) per vertex
  13710. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13711. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  13712. * const mesh = new THREE.Mesh( geometry, material );
  13713. * ```
  13714. *
  13715. * @augments EventDispatcher
  13716. */
  13717. class BufferGeometry extends EventDispatcher {
  13718. /**
  13719. * Constructs a new geometry.
  13720. */
  13721. constructor() {
  13722. super();
  13723. /**
  13724. * This flag can be used for type testing.
  13725. *
  13726. * @type {boolean}
  13727. * @readonly
  13728. * @default true
  13729. */
  13730. this.isBufferGeometry = true;
  13731. /**
  13732. * The ID of the geometry.
  13733. *
  13734. * @name BufferGeometry#id
  13735. * @type {number}
  13736. * @readonly
  13737. */
  13738. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  13739. /**
  13740. * The UUID of the geometry.
  13741. *
  13742. * @type {string}
  13743. * @readonly
  13744. */
  13745. this.uuid = generateUUID();
  13746. /**
  13747. * The name of the geometry.
  13748. *
  13749. * @type {string}
  13750. */
  13751. this.name = '';
  13752. this.type = 'BufferGeometry';
  13753. /**
  13754. * Allows for vertices to be re-used across multiple triangles; this is
  13755. * called using "indexed triangles". Each triangle is associated with the
  13756. * indices of three vertices. This attribute therefore stores the index of
  13757. * each vertex for each triangular face. If this attribute is not set, the
  13758. * renderer assumes that each three contiguous positions represent a single triangle.
  13759. *
  13760. * @type {?BufferAttribute}
  13761. * @default null
  13762. */
  13763. this.index = null;
  13764. /**
  13765. * A (storage) buffer attribute which was generated with a compute shader and
  13766. * now defines indirect draw calls.
  13767. *
  13768. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13769. *
  13770. * @type {?BufferAttribute}
  13771. * @default null
  13772. */
  13773. this.indirect = null;
  13774. /**
  13775. * 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.
  13776. *
  13777. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13778. *
  13779. * @type {number|Array<number>}
  13780. * @default 0
  13781. */
  13782. this.indirectOffset = 0;
  13783. /**
  13784. * This dictionary has as id the name of the attribute to be set and as value
  13785. * the buffer attribute to set it to. Rather than accessing this property directly,
  13786. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  13787. *
  13788. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  13789. */
  13790. this.attributes = {};
  13791. /**
  13792. * This dictionary holds the morph targets of the geometry.
  13793. *
  13794. * Note: Once the geometry has been rendered, the morph attribute data cannot
  13795. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  13796. *
  13797. * @type {Object}
  13798. */
  13799. this.morphAttributes = {};
  13800. /**
  13801. * Used to control the morph target behavior; when set to `true`, the morph
  13802. * target data is treated as relative offsets, rather than as absolute
  13803. * positions/normals.
  13804. *
  13805. * @type {boolean}
  13806. * @default false
  13807. */
  13808. this.morphTargetsRelative = false;
  13809. /**
  13810. * Split the geometry into groups, each of which will be rendered in a
  13811. * separate draw call. This allows an array of materials to be used with the geometry.
  13812. *
  13813. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  13814. *
  13815. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  13816. * indices, and must not leave vertices or indices unused.
  13817. *
  13818. * @type {Array<Object>}
  13819. */
  13820. this.groups = [];
  13821. /**
  13822. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  13823. *
  13824. * @type {?Box3}
  13825. * @default null
  13826. */
  13827. this.boundingBox = null;
  13828. /**
  13829. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  13830. *
  13831. * @type {?Sphere}
  13832. * @default null
  13833. */
  13834. this.boundingSphere = null;
  13835. /**
  13836. * Determines the part of the geometry to render. This should not be set directly,
  13837. * instead use `setDrawRange()`.
  13838. *
  13839. * @type {{start:number,count:number}}
  13840. */
  13841. this.drawRange = { start: 0, count: Infinity };
  13842. /**
  13843. * An object that can be used to store custom data about the geometry.
  13844. * It should not hold references to functions as these will not be cloned.
  13845. *
  13846. * @type {Object}
  13847. */
  13848. this.userData = {};
  13849. /**
  13850. * `true` when the geometry has been transformed since construction
  13851. * (e.g. via {@link BufferGeometry#applyMatrix4}). Only relevant for
  13852. * geometry generators (subclasses that populate `parameters`): when set,
  13853. * {@link BufferGeometry#toJSON} omits `parameters` since they no longer
  13854. * describe the geometry.
  13855. *
  13856. * @private
  13857. * @type {boolean}
  13858. * @default false
  13859. */
  13860. this._transformed = false;
  13861. }
  13862. /**
  13863. * Returns the index of this geometry.
  13864. *
  13865. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  13866. */
  13867. getIndex() {
  13868. return this.index;
  13869. }
  13870. /**
  13871. * Sets the given index to this geometry.
  13872. *
  13873. * @param {Array<number>|BufferAttribute} index - The index to set.
  13874. * @return {BufferGeometry} A reference to this instance.
  13875. */
  13876. setIndex( index ) {
  13877. if ( Array.isArray( index ) ) {
  13878. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  13879. } else {
  13880. this.index = index;
  13881. }
  13882. return this;
  13883. }
  13884. /**
  13885. * Sets the given indirect attribute to this geometry.
  13886. *
  13887. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  13888. * @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.
  13889. * @return {BufferGeometry} A reference to this instance.
  13890. */
  13891. setIndirect( indirect, indirectOffset = 0 ) {
  13892. this.indirect = indirect;
  13893. this.indirectOffset = indirectOffset;
  13894. return this;
  13895. }
  13896. /**
  13897. * Returns the indirect attribute of this geometry.
  13898. *
  13899. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  13900. */
  13901. getIndirect() {
  13902. return this.indirect;
  13903. }
  13904. /**
  13905. * Returns the buffer attribute for the given name.
  13906. *
  13907. * @param {string} name - The attribute name.
  13908. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  13909. * Returns `undefined` if not attribute has been found.
  13910. */
  13911. getAttribute( name ) {
  13912. return this.attributes[ name ];
  13913. }
  13914. /**
  13915. * Sets the given attribute for the given name.
  13916. *
  13917. * @param {string} name - The attribute name.
  13918. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  13919. * @return {BufferGeometry} A reference to this instance.
  13920. */
  13921. setAttribute( name, attribute ) {
  13922. this.attributes[ name ] = attribute;
  13923. return this;
  13924. }
  13925. /**
  13926. * Deletes the attribute for the given name.
  13927. *
  13928. * @param {string} name - The attribute name to delete.
  13929. * @return {BufferGeometry} A reference to this instance.
  13930. */
  13931. deleteAttribute( name ) {
  13932. delete this.attributes[ name ];
  13933. return this;
  13934. }
  13935. /**
  13936. * Returns `true` if this geometry has an attribute for the given name.
  13937. *
  13938. * @param {string} name - The attribute name.
  13939. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  13940. */
  13941. hasAttribute( name ) {
  13942. return this.attributes[ name ] !== undefined;
  13943. }
  13944. /**
  13945. * Adds a group to this geometry.
  13946. *
  13947. * @param {number} start - The first element in this draw call. That is the first
  13948. * vertex for non-indexed geometry, otherwise the first triangle index.
  13949. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  13950. * @param {number} [materialIndex=0] - The material array index to use.
  13951. */
  13952. addGroup( start, count, materialIndex = 0 ) {
  13953. this.groups.push( {
  13954. start: start,
  13955. count: count,
  13956. materialIndex: materialIndex
  13957. } );
  13958. }
  13959. /**
  13960. * Clears all groups.
  13961. */
  13962. clearGroups() {
  13963. this.groups = [];
  13964. }
  13965. /**
  13966. * Sets the draw range for this geometry.
  13967. *
  13968. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  13969. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  13970. * For indexed BufferGeometry, `count` is the number of indices to render.
  13971. */
  13972. setDrawRange( start, count ) {
  13973. this.drawRange.start = start;
  13974. this.drawRange.count = count;
  13975. }
  13976. /**
  13977. * Applies the given 4x4 transformation matrix to the geometry.
  13978. *
  13979. * @param {Matrix4} matrix - The matrix to apply.
  13980. * @return {BufferGeometry} A reference to this instance.
  13981. */
  13982. applyMatrix4( matrix ) {
  13983. const position = this.attributes.position;
  13984. if ( position !== undefined ) {
  13985. position.applyMatrix4( matrix );
  13986. position.needsUpdate = true;
  13987. }
  13988. const normal = this.attributes.normal;
  13989. if ( normal !== undefined ) {
  13990. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  13991. normal.applyNormalMatrix( normalMatrix );
  13992. normal.needsUpdate = true;
  13993. }
  13994. const tangent = this.attributes.tangent;
  13995. if ( tangent !== undefined ) {
  13996. tangent.transformDirection( matrix );
  13997. tangent.needsUpdate = true;
  13998. }
  13999. if ( this.boundingBox !== null ) {
  14000. this.computeBoundingBox();
  14001. }
  14002. if ( this.boundingSphere !== null ) {
  14003. this.computeBoundingSphere();
  14004. }
  14005. this._transformed = true;
  14006. return this;
  14007. }
  14008. /**
  14009. * Applies the rotation represented by the Quaternion to the geometry.
  14010. *
  14011. * @param {Quaternion} q - The Quaternion to apply.
  14012. * @return {BufferGeometry} A reference to this instance.
  14013. */
  14014. applyQuaternion( q ) {
  14015. _m1.makeRotationFromQuaternion( q );
  14016. this.applyMatrix4( _m1 );
  14017. return this;
  14018. }
  14019. /**
  14020. * Rotates the geometry about the X axis. This is typically done as a one time
  14021. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14022. * real-time mesh rotation.
  14023. *
  14024. * @param {number} angle - The angle in radians.
  14025. * @return {BufferGeometry} A reference to this instance.
  14026. */
  14027. rotateX( angle ) {
  14028. // rotate geometry around world x-axis
  14029. _m1.makeRotationX( angle );
  14030. this.applyMatrix4( _m1 );
  14031. return this;
  14032. }
  14033. /**
  14034. * Rotates the geometry about the Y axis. This is typically done as a one time
  14035. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14036. * real-time mesh rotation.
  14037. *
  14038. * @param {number} angle - The angle in radians.
  14039. * @return {BufferGeometry} A reference to this instance.
  14040. */
  14041. rotateY( angle ) {
  14042. // rotate geometry around world y-axis
  14043. _m1.makeRotationY( angle );
  14044. this.applyMatrix4( _m1 );
  14045. return this;
  14046. }
  14047. /**
  14048. * Rotates the geometry about the Z axis. This is typically done as a one time
  14049. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14050. * real-time mesh rotation.
  14051. *
  14052. * @param {number} angle - The angle in radians.
  14053. * @return {BufferGeometry} A reference to this instance.
  14054. */
  14055. rotateZ( angle ) {
  14056. // rotate geometry around world z-axis
  14057. _m1.makeRotationZ( angle );
  14058. this.applyMatrix4( _m1 );
  14059. return this;
  14060. }
  14061. /**
  14062. * Translates the geometry. This is typically done as a one time
  14063. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14064. * real-time mesh rotation.
  14065. *
  14066. * @param {number} x - The x offset.
  14067. * @param {number} y - The y offset.
  14068. * @param {number} z - The z offset.
  14069. * @return {BufferGeometry} A reference to this instance.
  14070. */
  14071. translate( x, y, z ) {
  14072. // translate geometry
  14073. _m1.makeTranslation( x, y, z );
  14074. this.applyMatrix4( _m1 );
  14075. return this;
  14076. }
  14077. /**
  14078. * Scales the geometry. This is typically done as a one time
  14079. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14080. * real-time mesh rotation.
  14081. *
  14082. * @param {number} x - The x scale.
  14083. * @param {number} y - The y scale.
  14084. * @param {number} z - The z scale.
  14085. * @return {BufferGeometry} A reference to this instance.
  14086. */
  14087. scale( x, y, z ) {
  14088. // scale geometry
  14089. _m1.makeScale( x, y, z );
  14090. this.applyMatrix4( _m1 );
  14091. return this;
  14092. }
  14093. /**
  14094. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14095. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14096. * real-time mesh rotation.
  14097. *
  14098. * @param {Vector3} vector - The target point.
  14099. * @return {BufferGeometry} A reference to this instance.
  14100. */
  14101. lookAt( vector ) {
  14102. _obj.lookAt( vector );
  14103. _obj.updateMatrix();
  14104. this.applyMatrix4( _obj.matrix );
  14105. return this;
  14106. }
  14107. /**
  14108. * Center the geometry based on its bounding box.
  14109. *
  14110. * @return {BufferGeometry} A reference to this instance.
  14111. */
  14112. center() {
  14113. this.computeBoundingBox();
  14114. this.boundingBox.getCenter( _offset ).negate();
  14115. this.translate( _offset.x, _offset.y, _offset.z );
  14116. return this;
  14117. }
  14118. /**
  14119. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14120. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14121. * set to `0`.
  14122. *
  14123. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14124. * data from the array. The length of the array must match the vertex count.
  14125. *
  14126. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14127. * @return {BufferGeometry} A reference to this instance.
  14128. */
  14129. setFromPoints( points ) {
  14130. const positionAttribute = this.getAttribute( 'position' );
  14131. if ( positionAttribute === undefined ) {
  14132. const position = [];
  14133. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14134. const point = points[ i ];
  14135. position.push( point.x, point.y, point.z || 0 );
  14136. }
  14137. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14138. } else {
  14139. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14140. for ( let i = 0; i < l; i ++ ) {
  14141. const point = points[ i ];
  14142. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14143. }
  14144. if ( points.length > positionAttribute.count ) {
  14145. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14146. }
  14147. positionAttribute.needsUpdate = true;
  14148. }
  14149. return this;
  14150. }
  14151. /**
  14152. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14153. * The bounding box is not computed by the engine; it must be computed by your app.
  14154. * You may need to recompute the bounding box if the geometry vertices are modified.
  14155. */
  14156. computeBoundingBox() {
  14157. if ( this.boundingBox === null ) {
  14158. this.boundingBox = new Box3();
  14159. }
  14160. const position = this.attributes.position;
  14161. const morphAttributesPosition = this.morphAttributes.position;
  14162. if ( position && position.isGLBufferAttribute ) {
  14163. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14164. this.boundingBox.set(
  14165. new Vector3( - Infinity, - Infinity, - Infinity ),
  14166. new Vector3( + Infinity, + Infinity, + Infinity )
  14167. );
  14168. return;
  14169. }
  14170. if ( position !== undefined ) {
  14171. this.boundingBox.setFromBufferAttribute( position );
  14172. // process morph attributes if present
  14173. if ( morphAttributesPosition ) {
  14174. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14175. const morphAttribute = morphAttributesPosition[ i ];
  14176. _box$2.setFromBufferAttribute( morphAttribute );
  14177. if ( this.morphTargetsRelative ) {
  14178. _vector$9.addVectors( this.boundingBox.min, _box$2.min );
  14179. this.boundingBox.expandByPoint( _vector$9 );
  14180. _vector$9.addVectors( this.boundingBox.max, _box$2.max );
  14181. this.boundingBox.expandByPoint( _vector$9 );
  14182. } else {
  14183. this.boundingBox.expandByPoint( _box$2.min );
  14184. this.boundingBox.expandByPoint( _box$2.max );
  14185. }
  14186. }
  14187. }
  14188. } else {
  14189. this.boundingBox.makeEmpty();
  14190. }
  14191. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14192. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14193. }
  14194. }
  14195. /**
  14196. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14197. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14198. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14199. */
  14200. computeBoundingSphere() {
  14201. if ( this.boundingSphere === null ) {
  14202. this.boundingSphere = new Sphere();
  14203. }
  14204. const position = this.attributes.position;
  14205. const morphAttributesPosition = this.morphAttributes.position;
  14206. if ( position && position.isGLBufferAttribute ) {
  14207. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14208. this.boundingSphere.set( new Vector3(), Infinity );
  14209. return;
  14210. }
  14211. if ( position ) {
  14212. // first, find the center of the bounding sphere
  14213. const center = this.boundingSphere.center;
  14214. _box$2.setFromBufferAttribute( position );
  14215. // process morph attributes if present
  14216. if ( morphAttributesPosition ) {
  14217. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14218. const morphAttribute = morphAttributesPosition[ i ];
  14219. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14220. if ( this.morphTargetsRelative ) {
  14221. _vector$9.addVectors( _box$2.min, _boxMorphTargets.min );
  14222. _box$2.expandByPoint( _vector$9 );
  14223. _vector$9.addVectors( _box$2.max, _boxMorphTargets.max );
  14224. _box$2.expandByPoint( _vector$9 );
  14225. } else {
  14226. _box$2.expandByPoint( _boxMorphTargets.min );
  14227. _box$2.expandByPoint( _boxMorphTargets.max );
  14228. }
  14229. }
  14230. }
  14231. _box$2.getCenter( center );
  14232. // second, try to find a boundingSphere with a radius smaller than the
  14233. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14234. let maxRadiusSq = 0;
  14235. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14236. _vector$9.fromBufferAttribute( position, i );
  14237. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14238. }
  14239. // process morph attributes if present
  14240. if ( morphAttributesPosition ) {
  14241. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14242. const morphAttribute = morphAttributesPosition[ i ];
  14243. const morphTargetsRelative = this.morphTargetsRelative;
  14244. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14245. _vector$9.fromBufferAttribute( morphAttribute, j );
  14246. if ( morphTargetsRelative ) {
  14247. _offset.fromBufferAttribute( position, j );
  14248. _vector$9.add( _offset );
  14249. }
  14250. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14251. }
  14252. }
  14253. }
  14254. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14255. if ( isNaN( this.boundingSphere.radius ) ) {
  14256. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14257. }
  14258. }
  14259. }
  14260. /**
  14261. * Calculates and adds a tangent attribute to this geometry.
  14262. *
  14263. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14264. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14265. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14266. */
  14267. computeTangents() {
  14268. const index = this.index;
  14269. const attributes = this.attributes;
  14270. // based on http://www.terathon.com/code/tangent.html
  14271. // (per vertex tangents)
  14272. if ( index === null ||
  14273. attributes.position === undefined ||
  14274. attributes.normal === undefined ||
  14275. attributes.uv === undefined ) {
  14276. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14277. return;
  14278. }
  14279. const positionAttribute = attributes.position;
  14280. const normalAttribute = attributes.normal;
  14281. const uvAttribute = attributes.uv;
  14282. let tangentAttribute = this.getAttribute( 'tangent' );
  14283. if ( tangentAttribute === undefined || tangentAttribute.count !== positionAttribute.count ) {
  14284. tangentAttribute = new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 );
  14285. this.setAttribute( 'tangent', tangentAttribute );
  14286. }
  14287. const tan1 = [], tan2 = [];
  14288. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14289. tan1[ i ] = new Vector3();
  14290. tan2[ i ] = new Vector3();
  14291. }
  14292. const vA = new Vector3(),
  14293. vB = new Vector3(),
  14294. vC = new Vector3(),
  14295. uvA = new Vector2(),
  14296. uvB = new Vector2(),
  14297. uvC = new Vector2(),
  14298. sdir = new Vector3(),
  14299. tdir = new Vector3();
  14300. function handleTriangle( a, b, c ) {
  14301. vA.fromBufferAttribute( positionAttribute, a );
  14302. vB.fromBufferAttribute( positionAttribute, b );
  14303. vC.fromBufferAttribute( positionAttribute, c );
  14304. uvA.fromBufferAttribute( uvAttribute, a );
  14305. uvB.fromBufferAttribute( uvAttribute, b );
  14306. uvC.fromBufferAttribute( uvAttribute, c );
  14307. vB.sub( vA );
  14308. vC.sub( vA );
  14309. uvB.sub( uvA );
  14310. uvC.sub( uvA );
  14311. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14312. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14313. if ( ! isFinite( r ) ) return;
  14314. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14315. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14316. tan1[ a ].add( sdir );
  14317. tan1[ b ].add( sdir );
  14318. tan1[ c ].add( sdir );
  14319. tan2[ a ].add( tdir );
  14320. tan2[ b ].add( tdir );
  14321. tan2[ c ].add( tdir );
  14322. }
  14323. let groups = this.groups;
  14324. if ( groups.length === 0 ) {
  14325. groups = [ {
  14326. start: 0,
  14327. count: index.count
  14328. } ];
  14329. }
  14330. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14331. const group = groups[ i ];
  14332. const start = group.start;
  14333. const count = group.count;
  14334. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14335. handleTriangle(
  14336. index.getX( j + 0 ),
  14337. index.getX( j + 1 ),
  14338. index.getX( j + 2 )
  14339. );
  14340. }
  14341. }
  14342. const tmp = new Vector3(), tmp2 = new Vector3();
  14343. const n = new Vector3(), n2 = new Vector3();
  14344. function handleVertex( v ) {
  14345. n.fromBufferAttribute( normalAttribute, v );
  14346. n2.copy( n );
  14347. const t = tan1[ v ];
  14348. // Gram-Schmidt orthogonalize
  14349. tmp.copy( t );
  14350. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14351. // Calculate handedness
  14352. tmp2.crossVectors( n2, t );
  14353. const test = tmp2.dot( tan2[ v ] );
  14354. const w = ( test < 0.0 ) ? -1 : 1.0;
  14355. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14356. }
  14357. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14358. const group = groups[ i ];
  14359. const start = group.start;
  14360. const count = group.count;
  14361. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14362. handleVertex( index.getX( j + 0 ) );
  14363. handleVertex( index.getX( j + 1 ) );
  14364. handleVertex( index.getX( j + 2 ) );
  14365. }
  14366. }
  14367. this._transformed = true;
  14368. }
  14369. /**
  14370. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14371. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14372. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14373. * to be the same as the face normal.
  14374. */
  14375. computeVertexNormals() {
  14376. const index = this.index;
  14377. const positionAttribute = this.getAttribute( 'position' );
  14378. if ( positionAttribute !== undefined ) {
  14379. let normalAttribute = this.getAttribute( 'normal' );
  14380. if ( normalAttribute === undefined || normalAttribute.count !== positionAttribute.count ) {
  14381. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14382. this.setAttribute( 'normal', normalAttribute );
  14383. } else {
  14384. // reset existing normals to zero
  14385. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14386. normalAttribute.setXYZ( i, 0, 0, 0 );
  14387. }
  14388. }
  14389. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14390. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14391. const cb = new Vector3(), ab = new Vector3();
  14392. // indexed elements
  14393. if ( index ) {
  14394. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14395. const vA = index.getX( i + 0 );
  14396. const vB = index.getX( i + 1 );
  14397. const vC = index.getX( i + 2 );
  14398. pA.fromBufferAttribute( positionAttribute, vA );
  14399. pB.fromBufferAttribute( positionAttribute, vB );
  14400. pC.fromBufferAttribute( positionAttribute, vC );
  14401. cb.subVectors( pC, pB );
  14402. ab.subVectors( pA, pB );
  14403. cb.cross( ab );
  14404. nA.fromBufferAttribute( normalAttribute, vA );
  14405. nB.fromBufferAttribute( normalAttribute, vB );
  14406. nC.fromBufferAttribute( normalAttribute, vC );
  14407. nA.add( cb );
  14408. nB.add( cb );
  14409. nC.add( cb );
  14410. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14411. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14412. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14413. }
  14414. } else {
  14415. // non-indexed elements (unconnected triangle soup)
  14416. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14417. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14418. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14419. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14420. cb.subVectors( pC, pB );
  14421. ab.subVectors( pA, pB );
  14422. cb.cross( ab );
  14423. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14424. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14425. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14426. }
  14427. }
  14428. this.normalizeNormals();
  14429. normalAttribute.needsUpdate = true;
  14430. }
  14431. }
  14432. /**
  14433. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14434. * correct lighting on the geometry surfaces.
  14435. */
  14436. normalizeNormals() {
  14437. const normals = this.attributes.normal;
  14438. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14439. _vector$9.fromBufferAttribute( normals, i );
  14440. _vector$9.normalize();
  14441. normals.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  14442. }
  14443. }
  14444. /**
  14445. * Return a new non-index version of this indexed geometry. If the geometry
  14446. * is already non-indexed, the method is a NOOP.
  14447. *
  14448. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14449. */
  14450. toNonIndexed() {
  14451. function convertBufferAttribute( attribute, indices ) {
  14452. const array = attribute.array;
  14453. const itemSize = attribute.itemSize;
  14454. const normalized = attribute.normalized;
  14455. const array2 = new array.constructor( indices.length * itemSize );
  14456. let index = 0, index2 = 0;
  14457. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14458. if ( attribute.isInterleavedBufferAttribute ) {
  14459. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14460. } else {
  14461. index = indices[ i ] * itemSize;
  14462. }
  14463. for ( let j = 0; j < itemSize; j ++ ) {
  14464. array2[ index2 ++ ] = array[ index ++ ];
  14465. }
  14466. }
  14467. return new BufferAttribute( array2, itemSize, normalized );
  14468. }
  14469. //
  14470. if ( this.index === null ) {
  14471. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14472. return this;
  14473. }
  14474. const geometry2 = new BufferGeometry();
  14475. const indices = this.index.array;
  14476. const attributes = this.attributes;
  14477. // attributes
  14478. for ( const name in attributes ) {
  14479. const attribute = attributes[ name ];
  14480. const newAttribute = convertBufferAttribute( attribute, indices );
  14481. geometry2.setAttribute( name, newAttribute );
  14482. }
  14483. // morph attributes
  14484. const morphAttributes = this.morphAttributes;
  14485. for ( const name in morphAttributes ) {
  14486. const morphArray = [];
  14487. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14488. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14489. const attribute = morphAttribute[ i ];
  14490. const newAttribute = convertBufferAttribute( attribute, indices );
  14491. morphArray.push( newAttribute );
  14492. }
  14493. geometry2.morphAttributes[ name ] = morphArray;
  14494. }
  14495. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14496. // groups
  14497. const groups = this.groups;
  14498. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14499. const group = groups[ i ];
  14500. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14501. }
  14502. return geometry2;
  14503. }
  14504. /**
  14505. * Serializes the geometry into JSON.
  14506. *
  14507. * @return {Object} A JSON object representing the serialized geometry.
  14508. */
  14509. toJSON() {
  14510. const data = {
  14511. metadata: {
  14512. version: 4.7,
  14513. type: 'BufferGeometry',
  14514. generator: 'BufferGeometry.toJSON'
  14515. }
  14516. };
  14517. // standard BufferGeometry serialization
  14518. data.uuid = this.uuid;
  14519. data.type = ( this.parameters !== undefined && this._transformed === true ) ? 'BufferGeometry' : this.type;
  14520. if ( this.name !== '' ) data.name = this.name;
  14521. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14522. if ( this.parameters !== undefined && this._transformed !== true ) {
  14523. const parameters = this.parameters;
  14524. for ( const key in parameters ) {
  14525. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14526. }
  14527. return data;
  14528. }
  14529. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14530. data.data = { attributes: {} };
  14531. const index = this.index;
  14532. if ( index !== null ) {
  14533. data.data.index = {
  14534. type: index.array.constructor.name,
  14535. array: Array.prototype.slice.call( index.array )
  14536. };
  14537. }
  14538. const attributes = this.attributes;
  14539. for ( const key in attributes ) {
  14540. const attribute = attributes[ key ];
  14541. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14542. }
  14543. const morphAttributes = {};
  14544. let hasMorphAttributes = false;
  14545. for ( const key in this.morphAttributes ) {
  14546. const attributeArray = this.morphAttributes[ key ];
  14547. const array = [];
  14548. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14549. const attribute = attributeArray[ i ];
  14550. array.push( attribute.toJSON( data.data ) );
  14551. }
  14552. if ( array.length > 0 ) {
  14553. morphAttributes[ key ] = array;
  14554. hasMorphAttributes = true;
  14555. }
  14556. }
  14557. if ( hasMorphAttributes ) {
  14558. data.data.morphAttributes = morphAttributes;
  14559. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14560. }
  14561. const groups = this.groups;
  14562. if ( groups.length > 0 ) {
  14563. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14564. }
  14565. const boundingSphere = this.boundingSphere;
  14566. if ( boundingSphere !== null ) {
  14567. data.data.boundingSphere = boundingSphere.toJSON();
  14568. }
  14569. return data;
  14570. }
  14571. /**
  14572. * Returns a new geometry with copied values from this instance.
  14573. *
  14574. * @return {BufferGeometry} A clone of this instance.
  14575. */
  14576. clone() {
  14577. return new this.constructor().copy( this );
  14578. }
  14579. /**
  14580. * Copies the values of the given geometry to this instance.
  14581. *
  14582. * @param {BufferGeometry} source - The geometry to copy.
  14583. * @return {BufferGeometry} A reference to this instance.
  14584. */
  14585. copy( source ) {
  14586. // reset
  14587. this.index = null;
  14588. this.attributes = {};
  14589. this.morphAttributes = {};
  14590. this.groups = [];
  14591. this.boundingBox = null;
  14592. this.boundingSphere = null;
  14593. // used for storing cloned, shared data
  14594. const data = {};
  14595. // name
  14596. this.name = source.name;
  14597. // index
  14598. const index = source.index;
  14599. if ( index !== null ) {
  14600. this.setIndex( index.clone() );
  14601. }
  14602. // attributes
  14603. const attributes = source.attributes;
  14604. for ( const name in attributes ) {
  14605. const attribute = attributes[ name ];
  14606. this.setAttribute( name, attribute.clone( data ) );
  14607. }
  14608. // morph attributes
  14609. const morphAttributes = source.morphAttributes;
  14610. for ( const name in morphAttributes ) {
  14611. const array = [];
  14612. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14613. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  14614. array.push( morphAttribute[ i ].clone( data ) );
  14615. }
  14616. this.morphAttributes[ name ] = array;
  14617. }
  14618. this.morphTargetsRelative = source.morphTargetsRelative;
  14619. // groups
  14620. const groups = source.groups;
  14621. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14622. const group = groups[ i ];
  14623. this.addGroup( group.start, group.count, group.materialIndex );
  14624. }
  14625. // bounding box
  14626. const boundingBox = source.boundingBox;
  14627. if ( boundingBox !== null ) {
  14628. this.boundingBox = boundingBox.clone();
  14629. }
  14630. // bounding sphere
  14631. const boundingSphere = source.boundingSphere;
  14632. if ( boundingSphere !== null ) {
  14633. this.boundingSphere = boundingSphere.clone();
  14634. }
  14635. // draw range
  14636. this.drawRange.start = source.drawRange.start;
  14637. this.drawRange.count = source.drawRange.count;
  14638. // user data
  14639. this.userData = source.userData;
  14640. // transformed flag
  14641. this._transformed = source._transformed;
  14642. return this;
  14643. }
  14644. /**
  14645. * Frees the GPU-related resources allocated by this instance. Call this
  14646. * method whenever this instance is no longer used in your app.
  14647. *
  14648. * @fires BufferGeometry#dispose
  14649. */
  14650. dispose() {
  14651. this.dispatchEvent( { type: 'dispose' } );
  14652. }
  14653. }
  14654. /**
  14655. * "Interleaved" means that multiple attributes, possibly of different types,
  14656. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  14657. *
  14658. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  14659. */
  14660. class InterleavedBuffer {
  14661. /**
  14662. * Constructs a new interleaved buffer.
  14663. *
  14664. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  14665. * @param {number} stride - The number of typed-array elements per vertex.
  14666. */
  14667. constructor( array, stride ) {
  14668. /**
  14669. * This flag can be used for type testing.
  14670. *
  14671. * @type {boolean}
  14672. * @readonly
  14673. * @default true
  14674. */
  14675. this.isInterleavedBuffer = true;
  14676. /**
  14677. * A typed array with a shared buffer storing attribute data.
  14678. *
  14679. * @type {TypedArray}
  14680. */
  14681. this.array = array;
  14682. /**
  14683. * The number of typed-array elements per vertex.
  14684. *
  14685. * @type {number}
  14686. */
  14687. this.stride = stride;
  14688. /**
  14689. * The total number of elements in the array
  14690. *
  14691. * @type {number}
  14692. * @readonly
  14693. */
  14694. this.count = array !== undefined ? array.length / stride : 0;
  14695. /**
  14696. * Defines the intended usage pattern of the data store for optimization purposes.
  14697. *
  14698. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  14699. * instantiate a new one and set the desired usage before the next render.
  14700. *
  14701. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  14702. * @default StaticDrawUsage
  14703. */
  14704. this.usage = StaticDrawUsage;
  14705. /**
  14706. * This can be used to only update some components of stored vectors (for example, just the
  14707. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  14708. *
  14709. * @type {Array<Object>}
  14710. */
  14711. this.updateRanges = [];
  14712. /**
  14713. * A version number, incremented every time the `needsUpdate` is set to `true`.
  14714. *
  14715. * @type {number}
  14716. */
  14717. this.version = 0;
  14718. /**
  14719. * The UUID of the interleaved buffer.
  14720. *
  14721. * @type {string}
  14722. * @readonly
  14723. */
  14724. this.uuid = generateUUID();
  14725. }
  14726. /**
  14727. * A callback function that is executed after the renderer has transferred the attribute array
  14728. * data to the GPU.
  14729. */
  14730. onUploadCallback() {}
  14731. /**
  14732. * Flag to indicate that this attribute has changed and should be re-sent to
  14733. * the GPU. Set this to `true` when you modify the value of the array.
  14734. *
  14735. * @type {number}
  14736. * @default false
  14737. * @param {boolean} value
  14738. */
  14739. set needsUpdate( value ) {
  14740. if ( value === true ) this.version ++;
  14741. }
  14742. /**
  14743. * Sets the usage of this interleaved buffer.
  14744. *
  14745. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  14746. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  14747. */
  14748. setUsage( value ) {
  14749. this.usage = value;
  14750. return this;
  14751. }
  14752. /**
  14753. * Adds a range of data in the data array to be updated on the GPU.
  14754. *
  14755. * @param {number} start - Position at which to start update.
  14756. * @param {number} count - The number of components to update.
  14757. */
  14758. addUpdateRange( start, count ) {
  14759. this.updateRanges.push( { start, count } );
  14760. }
  14761. /**
  14762. * Clears the update ranges.
  14763. */
  14764. clearUpdateRanges() {
  14765. this.updateRanges.length = 0;
  14766. }
  14767. /**
  14768. * Copies the values of the given interleaved buffer to this instance.
  14769. *
  14770. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  14771. * @return {InterleavedBuffer} A reference to this instance.
  14772. */
  14773. copy( source ) {
  14774. this.array = new source.array.constructor( source.array );
  14775. this.count = source.count;
  14776. this.stride = source.stride;
  14777. this.usage = source.usage;
  14778. return this;
  14779. }
  14780. /**
  14781. * Copies a vector from the given interleaved buffer to this one. The start
  14782. * and destination position in the attribute buffers are represented by the
  14783. * given indices.
  14784. *
  14785. * @param {number} index1 - The destination index into this interleaved buffer.
  14786. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  14787. * @param {number} index2 - The source index into the given interleaved buffer.
  14788. * @return {InterleavedBuffer} A reference to this instance.
  14789. */
  14790. copyAt( index1, interleavedBuffer, index2 ) {
  14791. index1 *= this.stride;
  14792. index2 *= interleavedBuffer.stride;
  14793. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  14794. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  14795. }
  14796. return this;
  14797. }
  14798. /**
  14799. * Sets the given array data in the interleaved buffer.
  14800. *
  14801. * @param {(TypedArray|Array)} value - The array data to set.
  14802. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  14803. * @return {InterleavedBuffer} A reference to this instance.
  14804. */
  14805. set( value, offset = 0 ) {
  14806. this.array.set( value, offset );
  14807. return this;
  14808. }
  14809. /**
  14810. * Returns a new interleaved buffer with copied values from this instance.
  14811. *
  14812. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  14813. * @return {InterleavedBuffer} A clone of this instance.
  14814. */
  14815. clone( data ) {
  14816. if ( data.arrayBuffers === undefined ) {
  14817. data.arrayBuffers = {};
  14818. }
  14819. if ( this.array.buffer._uuid === undefined ) {
  14820. this.array.buffer._uuid = generateUUID();
  14821. }
  14822. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14823. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  14824. }
  14825. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  14826. const ib = new this.constructor( array, this.stride );
  14827. ib.setUsage( this.usage );
  14828. return ib;
  14829. }
  14830. /**
  14831. * Sets the given callback function that is executed after the Renderer has transferred
  14832. * the array data to the GPU. Can be used to perform clean-up operations after
  14833. * the upload when data are not needed anymore on the CPU side.
  14834. *
  14835. * @param {Function} callback - The `onUpload()` callback.
  14836. * @return {InterleavedBuffer} A reference to this instance.
  14837. */
  14838. onUpload( callback ) {
  14839. this.onUploadCallback = callback;
  14840. return this;
  14841. }
  14842. /**
  14843. * Serializes the interleaved buffer into JSON.
  14844. *
  14845. * @param {Object} [data] - An optional value holding meta information about the serialization.
  14846. * @return {Object} A JSON object representing the serialized interleaved buffer.
  14847. */
  14848. toJSON( data ) {
  14849. if ( data.arrayBuffers === undefined ) {
  14850. data.arrayBuffers = {};
  14851. }
  14852. // generate UUID for array buffer if necessary
  14853. if ( this.array.buffer._uuid === undefined ) {
  14854. this.array.buffer._uuid = generateUUID();
  14855. }
  14856. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14857. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  14858. }
  14859. //
  14860. return {
  14861. uuid: this.uuid,
  14862. buffer: this.array.buffer._uuid,
  14863. type: this.array.constructor.name,
  14864. stride: this.stride
  14865. };
  14866. }
  14867. }
  14868. const _vector$8 = /*@__PURE__*/ new Vector3();
  14869. /**
  14870. * An alternative version of a buffer attribute with interleaved data. Interleaved
  14871. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  14872. * different offsets into the buffer.
  14873. */
  14874. class InterleavedBufferAttribute {
  14875. /**
  14876. * Constructs a new interleaved buffer attribute.
  14877. *
  14878. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  14879. * @param {number} itemSize - The item size.
  14880. * @param {number} offset - The attribute offset into the buffer.
  14881. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14882. */
  14883. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  14884. /**
  14885. * This flag can be used for type testing.
  14886. *
  14887. * @type {boolean}
  14888. * @readonly
  14889. * @default true
  14890. */
  14891. this.isInterleavedBufferAttribute = true;
  14892. /**
  14893. * The name of the buffer attribute.
  14894. *
  14895. * @type {string}
  14896. */
  14897. this.name = '';
  14898. /**
  14899. * The buffer holding the interleaved data.
  14900. *
  14901. * @type {InterleavedBuffer}
  14902. */
  14903. this.data = interleavedBuffer;
  14904. /**
  14905. * The item size, see {@link BufferAttribute#itemSize}.
  14906. *
  14907. * @type {number}
  14908. */
  14909. this.itemSize = itemSize;
  14910. /**
  14911. * The attribute offset into the buffer.
  14912. *
  14913. * @type {number}
  14914. */
  14915. this.offset = offset;
  14916. /**
  14917. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  14918. *
  14919. * @type {InterleavedBuffer}
  14920. */
  14921. this.normalized = normalized;
  14922. }
  14923. /**
  14924. * The item count of this buffer attribute.
  14925. *
  14926. * @type {number}
  14927. * @readonly
  14928. */
  14929. get count() {
  14930. return this.data.count;
  14931. }
  14932. /**
  14933. * The array holding the interleaved buffer attribute data.
  14934. *
  14935. * @type {TypedArray}
  14936. */
  14937. get array() {
  14938. return this.data.array;
  14939. }
  14940. /**
  14941. * Flag to indicate that this attribute has changed and should be re-sent to
  14942. * the GPU. Set this to `true` when you modify the value of the array.
  14943. *
  14944. * @type {number}
  14945. * @default false
  14946. * @param {boolean} value
  14947. */
  14948. set needsUpdate( value ) {
  14949. this.data.needsUpdate = value;
  14950. }
  14951. /**
  14952. * Applies the given 4x4 matrix to the given attribute. Only works with
  14953. * item size `3`.
  14954. *
  14955. * @param {Matrix4} m - The matrix to apply.
  14956. * @return {InterleavedBufferAttribute} A reference to this instance.
  14957. */
  14958. applyMatrix4( m ) {
  14959. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  14960. _vector$8.fromBufferAttribute( this, i );
  14961. _vector$8.applyMatrix4( m );
  14962. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14963. }
  14964. return this;
  14965. }
  14966. /**
  14967. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  14968. * item size `3`.
  14969. *
  14970. * @param {Matrix3} m - The normal matrix to apply.
  14971. * @return {InterleavedBufferAttribute} A reference to this instance.
  14972. */
  14973. applyNormalMatrix( m ) {
  14974. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14975. _vector$8.fromBufferAttribute( this, i );
  14976. _vector$8.applyNormalMatrix( m );
  14977. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14978. }
  14979. return this;
  14980. }
  14981. /**
  14982. * Applies the given 4x4 matrix to the given attribute. Only works with
  14983. * item size `3` and with direction vectors.
  14984. *
  14985. * @param {Matrix4} m - The matrix to apply.
  14986. * @return {InterleavedBufferAttribute} A reference to this instance.
  14987. */
  14988. transformDirection( m ) {
  14989. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14990. _vector$8.fromBufferAttribute( this, i );
  14991. _vector$8.transformDirection( m );
  14992. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14993. }
  14994. return this;
  14995. }
  14996. /**
  14997. * Returns the given component of the vector at the given index.
  14998. *
  14999. * @param {number} index - The index into the buffer attribute.
  15000. * @param {number} component - The component index.
  15001. * @return {number} The returned value.
  15002. */
  15003. getComponent( index, component ) {
  15004. let value = this.array[ index * this.data.stride + this.offset + component ];
  15005. if ( this.normalized ) value = denormalize( value, this.array );
  15006. return value;
  15007. }
  15008. /**
  15009. * Sets the given value to the given component of the vector at the given index.
  15010. *
  15011. * @param {number} index - The index into the buffer attribute.
  15012. * @param {number} component - The component index.
  15013. * @param {number} value - The value to set.
  15014. * @return {InterleavedBufferAttribute} A reference to this instance.
  15015. */
  15016. setComponent( index, component, value ) {
  15017. if ( this.normalized ) value = normalize( value, this.array );
  15018. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  15019. return this;
  15020. }
  15021. /**
  15022. * Sets the x component of the vector at the given index.
  15023. *
  15024. * @param {number} index - The index into the buffer attribute.
  15025. * @param {number} x - The value to set.
  15026. * @return {InterleavedBufferAttribute} A reference to this instance.
  15027. */
  15028. setX( index, x ) {
  15029. if ( this.normalized ) x = normalize( x, this.array );
  15030. this.data.array[ index * this.data.stride + this.offset ] = x;
  15031. return this;
  15032. }
  15033. /**
  15034. * Sets the y component of the vector at the given index.
  15035. *
  15036. * @param {number} index - The index into the buffer attribute.
  15037. * @param {number} y - The value to set.
  15038. * @return {InterleavedBufferAttribute} A reference to this instance.
  15039. */
  15040. setY( index, y ) {
  15041. if ( this.normalized ) y = normalize( y, this.array );
  15042. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15043. return this;
  15044. }
  15045. /**
  15046. * Sets the z component of the vector at the given index.
  15047. *
  15048. * @param {number} index - The index into the buffer attribute.
  15049. * @param {number} z - The value to set.
  15050. * @return {InterleavedBufferAttribute} A reference to this instance.
  15051. */
  15052. setZ( index, z ) {
  15053. if ( this.normalized ) z = normalize( z, this.array );
  15054. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15055. return this;
  15056. }
  15057. /**
  15058. * Sets the w component of the vector at the given index.
  15059. *
  15060. * @param {number} index - The index into the buffer attribute.
  15061. * @param {number} w - The value to set.
  15062. * @return {InterleavedBufferAttribute} A reference to this instance.
  15063. */
  15064. setW( index, w ) {
  15065. if ( this.normalized ) w = normalize( w, this.array );
  15066. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15067. return this;
  15068. }
  15069. /**
  15070. * Returns the x component of the vector at the given index.
  15071. *
  15072. * @param {number} index - The index into the buffer attribute.
  15073. * @return {number} The x component.
  15074. */
  15075. getX( index ) {
  15076. let x = this.data.array[ index * this.data.stride + this.offset ];
  15077. if ( this.normalized ) x = denormalize( x, this.array );
  15078. return x;
  15079. }
  15080. /**
  15081. * Returns the y component of the vector at the given index.
  15082. *
  15083. * @param {number} index - The index into the buffer attribute.
  15084. * @return {number} The y component.
  15085. */
  15086. getY( index ) {
  15087. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  15088. if ( this.normalized ) y = denormalize( y, this.array );
  15089. return y;
  15090. }
  15091. /**
  15092. * Returns the z component of the vector at the given index.
  15093. *
  15094. * @param {number} index - The index into the buffer attribute.
  15095. * @return {number} The z component.
  15096. */
  15097. getZ( index ) {
  15098. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  15099. if ( this.normalized ) z = denormalize( z, this.array );
  15100. return z;
  15101. }
  15102. /**
  15103. * Returns the w component of the vector at the given index.
  15104. *
  15105. * @param {number} index - The index into the buffer attribute.
  15106. * @return {number} The w component.
  15107. */
  15108. getW( index ) {
  15109. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  15110. if ( this.normalized ) w = denormalize( w, this.array );
  15111. return w;
  15112. }
  15113. /**
  15114. * Sets the x and y component of the vector at the given index.
  15115. *
  15116. * @param {number} index - The index into the buffer attribute.
  15117. * @param {number} x - The value for the x component to set.
  15118. * @param {number} y - The value for the y component to set.
  15119. * @return {InterleavedBufferAttribute} A reference to this instance.
  15120. */
  15121. setXY( index, x, y ) {
  15122. index = index * this.data.stride + this.offset;
  15123. if ( this.normalized ) {
  15124. x = normalize( x, this.array );
  15125. y = normalize( y, this.array );
  15126. }
  15127. this.data.array[ index + 0 ] = x;
  15128. this.data.array[ index + 1 ] = y;
  15129. return this;
  15130. }
  15131. /**
  15132. * Sets the x, y and z component of the vector at the given index.
  15133. *
  15134. * @param {number} index - The index into the buffer attribute.
  15135. * @param {number} x - The value for the x component to set.
  15136. * @param {number} y - The value for the y component to set.
  15137. * @param {number} z - The value for the z component to set.
  15138. * @return {InterleavedBufferAttribute} A reference to this instance.
  15139. */
  15140. setXYZ( index, x, y, z ) {
  15141. index = index * this.data.stride + this.offset;
  15142. if ( this.normalized ) {
  15143. x = normalize( x, this.array );
  15144. y = normalize( y, this.array );
  15145. z = normalize( z, this.array );
  15146. }
  15147. this.data.array[ index + 0 ] = x;
  15148. this.data.array[ index + 1 ] = y;
  15149. this.data.array[ index + 2 ] = z;
  15150. return this;
  15151. }
  15152. /**
  15153. * Sets the x, y, z and w component of the vector at the given index.
  15154. *
  15155. * @param {number} index - The index into the buffer attribute.
  15156. * @param {number} x - The value for the x component to set.
  15157. * @param {number} y - The value for the y component to set.
  15158. * @param {number} z - The value for the z component to set.
  15159. * @param {number} w - The value for the w component to set.
  15160. * @return {InterleavedBufferAttribute} A reference to this instance.
  15161. */
  15162. setXYZW( index, x, y, z, w ) {
  15163. index = index * this.data.stride + this.offset;
  15164. if ( this.normalized ) {
  15165. x = normalize( x, this.array );
  15166. y = normalize( y, this.array );
  15167. z = normalize( z, this.array );
  15168. w = normalize( w, this.array );
  15169. }
  15170. this.data.array[ index + 0 ] = x;
  15171. this.data.array[ index + 1 ] = y;
  15172. this.data.array[ index + 2 ] = z;
  15173. this.data.array[ index + 3 ] = w;
  15174. return this;
  15175. }
  15176. /**
  15177. * Returns a new buffer attribute with copied values from this instance.
  15178. *
  15179. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15180. *
  15181. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  15182. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  15183. */
  15184. clone( data ) {
  15185. if ( data === undefined ) {
  15186. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  15187. const array = [];
  15188. for ( let i = 0; i < this.count; i ++ ) {
  15189. const index = i * this.data.stride + this.offset;
  15190. for ( let j = 0; j < this.itemSize; j ++ ) {
  15191. array.push( this.data.array[ index + j ] );
  15192. }
  15193. }
  15194. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15195. } else {
  15196. if ( data.interleavedBuffers === undefined ) {
  15197. data.interleavedBuffers = {};
  15198. }
  15199. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15200. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15201. }
  15202. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15203. }
  15204. }
  15205. /**
  15206. * Serializes the buffer attribute into JSON.
  15207. *
  15208. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15209. *
  15210. * @param {Object} [data] - An optional value holding meta information about the serialization.
  15211. * @return {Object} A JSON object representing the serialized buffer attribute.
  15212. */
  15213. toJSON( data ) {
  15214. if ( data === undefined ) {
  15215. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  15216. const array = [];
  15217. for ( let i = 0; i < this.count; i ++ ) {
  15218. const index = i * this.data.stride + this.offset;
  15219. for ( let j = 0; j < this.itemSize; j ++ ) {
  15220. array.push( this.data.array[ index + j ] );
  15221. }
  15222. }
  15223. // de-interleave data and save it as an ordinary buffer attribute for now
  15224. return {
  15225. itemSize: this.itemSize,
  15226. type: this.array.constructor.name,
  15227. array: array,
  15228. normalized: this.normalized
  15229. };
  15230. } else {
  15231. // save as true interleaved attribute
  15232. if ( data.interleavedBuffers === undefined ) {
  15233. data.interleavedBuffers = {};
  15234. }
  15235. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15236. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15237. }
  15238. return {
  15239. isInterleavedBufferAttribute: true,
  15240. itemSize: this.itemSize,
  15241. data: this.data.uuid,
  15242. offset: this.offset,
  15243. normalized: this.normalized
  15244. };
  15245. }
  15246. }
  15247. }
  15248. let _materialId = 0;
  15249. /**
  15250. * Abstract base class for materials.
  15251. *
  15252. * Materials define the appearance of renderable 3D objects.
  15253. *
  15254. * @abstract
  15255. * @augments EventDispatcher
  15256. */
  15257. class Material extends EventDispatcher {
  15258. /**
  15259. * Constructs a new material.
  15260. */
  15261. constructor() {
  15262. super();
  15263. /**
  15264. * This flag can be used for type testing.
  15265. *
  15266. * @type {boolean}
  15267. * @readonly
  15268. * @default true
  15269. */
  15270. this.isMaterial = true;
  15271. /**
  15272. * The ID of the material.
  15273. *
  15274. * @name Material#id
  15275. * @type {number}
  15276. * @readonly
  15277. */
  15278. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  15279. /**
  15280. * The UUID of the material.
  15281. *
  15282. * @type {string}
  15283. * @readonly
  15284. */
  15285. this.uuid = generateUUID();
  15286. /**
  15287. * The name of the material.
  15288. *
  15289. * @type {string}
  15290. */
  15291. this.name = '';
  15292. /**
  15293. * The type property is used for detecting the object type
  15294. * in context of serialization/deserialization.
  15295. *
  15296. * @type {string}
  15297. * @readonly
  15298. */
  15299. this.type = 'Material';
  15300. /**
  15301. * Defines the blending type of the material.
  15302. *
  15303. * It must be set to `CustomBlending` if custom blending properties like
  15304. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  15305. * should have any effect.
  15306. *
  15307. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  15308. * @default NormalBlending
  15309. */
  15310. this.blending = NormalBlending;
  15311. /**
  15312. * Defines which side of faces will be rendered - front, back or both.
  15313. *
  15314. * @type {(FrontSide|BackSide|DoubleSide)}
  15315. * @default FrontSide
  15316. */
  15317. this.side = FrontSide;
  15318. /**
  15319. * If set to `true`, vertex colors should be used.
  15320. *
  15321. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  15322. * four (RGBA) component color buffer attribute is used.
  15323. *
  15324. * @type {boolean}
  15325. * @default false
  15326. */
  15327. this.vertexColors = false;
  15328. /**
  15329. * Defines how transparent the material is.
  15330. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  15331. *
  15332. * If the {@link Material#transparent} is not set to `true`,
  15333. * the material will remain fully opaque and this value will only affect its color.
  15334. *
  15335. * @type {number}
  15336. * @default 1
  15337. */
  15338. this.opacity = 1;
  15339. /**
  15340. * Defines whether this material is transparent. This has an effect on
  15341. * rendering as transparent objects need special treatment and are rendered
  15342. * after non-transparent objects.
  15343. *
  15344. * When set to true, the extent to which the material is transparent is
  15345. * controlled by {@link Material#opacity}.
  15346. *
  15347. * @type {boolean}
  15348. * @default false
  15349. */
  15350. this.transparent = false;
  15351. /**
  15352. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  15353. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  15354. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  15355. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  15356. *
  15357. * @type {boolean}
  15358. * @default false
  15359. */
  15360. this.alphaHash = false;
  15361. /**
  15362. * Defines the blending source factor.
  15363. *
  15364. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15365. * @default SrcAlphaFactor
  15366. */
  15367. this.blendSrc = SrcAlphaFactor;
  15368. /**
  15369. * Defines the blending destination factor.
  15370. *
  15371. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15372. * @default OneMinusSrcAlphaFactor
  15373. */
  15374. this.blendDst = OneMinusSrcAlphaFactor;
  15375. /**
  15376. * Defines the blending equation.
  15377. *
  15378. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15379. * @default AddEquation
  15380. */
  15381. this.blendEquation = AddEquation;
  15382. /**
  15383. * Defines the blending source alpha factor.
  15384. *
  15385. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15386. * @default null
  15387. */
  15388. this.blendSrcAlpha = null;
  15389. /**
  15390. * Defines the blending destination alpha factor.
  15391. *
  15392. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15393. * @default null
  15394. */
  15395. this.blendDstAlpha = null;
  15396. /**
  15397. * Defines the blending equation of the alpha channel.
  15398. *
  15399. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15400. * @default null
  15401. */
  15402. this.blendEquationAlpha = null;
  15403. /**
  15404. * Represents the RGB values of the constant blend color.
  15405. *
  15406. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  15407. *
  15408. * @type {Color}
  15409. * @default (0,0,0)
  15410. */
  15411. this.blendColor = new Color( 0, 0, 0 );
  15412. /**
  15413. * Represents the alpha value of the constant blend color.
  15414. *
  15415. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  15416. *
  15417. * @type {number}
  15418. * @default 0
  15419. */
  15420. this.blendAlpha = 0;
  15421. /**
  15422. * Defines the depth function.
  15423. *
  15424. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  15425. * @default LessEqualDepth
  15426. */
  15427. this.depthFunc = LessEqualDepth;
  15428. /**
  15429. * Whether to have depth test enabled when rendering this material.
  15430. * When the depth test is disabled, the depth write will also be implicitly disabled.
  15431. *
  15432. * @type {boolean}
  15433. * @default true
  15434. */
  15435. this.depthTest = true;
  15436. /**
  15437. * Whether rendering this material has any effect on the depth buffer.
  15438. *
  15439. * When drawing 2D overlays it can be useful to disable the depth writing in
  15440. * order to layer several things together without creating z-index artifacts.
  15441. *
  15442. * @type {boolean}
  15443. * @default true
  15444. */
  15445. this.depthWrite = true;
  15446. /**
  15447. * The bit mask to use when writing to the stencil buffer.
  15448. *
  15449. * @type {number}
  15450. * @default 0xff
  15451. */
  15452. this.stencilWriteMask = 0xff;
  15453. /**
  15454. * The stencil comparison function to use.
  15455. *
  15456. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  15457. * @default AlwaysStencilFunc
  15458. */
  15459. this.stencilFunc = AlwaysStencilFunc;
  15460. /**
  15461. * The value to use when performing stencil comparisons or stencil operations.
  15462. *
  15463. * @type {number}
  15464. * @default 0
  15465. */
  15466. this.stencilRef = 0;
  15467. /**
  15468. * The bit mask to use when comparing against the stencil buffer.
  15469. *
  15470. * @type {number}
  15471. * @default 0xff
  15472. */
  15473. this.stencilFuncMask = 0xff;
  15474. /**
  15475. * Which stencil operation to perform when the comparison function returns `false`.
  15476. *
  15477. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15478. * @default KeepStencilOp
  15479. */
  15480. this.stencilFail = KeepStencilOp;
  15481. /**
  15482. * Which stencil operation to perform when the comparison function returns
  15483. * `true` but the depth test fails.
  15484. *
  15485. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15486. * @default KeepStencilOp
  15487. */
  15488. this.stencilZFail = KeepStencilOp;
  15489. /**
  15490. * Which stencil operation to perform when the comparison function returns
  15491. * `true` and the depth test passes.
  15492. *
  15493. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15494. * @default KeepStencilOp
  15495. */
  15496. this.stencilZPass = KeepStencilOp;
  15497. /**
  15498. * Whether stencil operations are performed against the stencil buffer. In
  15499. * order to perform writes or comparisons against the stencil buffer this
  15500. * value must be `true`.
  15501. *
  15502. * @type {boolean}
  15503. * @default false
  15504. */
  15505. this.stencilWrite = false;
  15506. /**
  15507. * User-defined clipping planes specified as THREE.Plane objects in world
  15508. * space. These planes apply to the objects this material is attached to.
  15509. * Points in space whose signed distance to the plane is negative are clipped
  15510. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  15511. * be `true`.
  15512. *
  15513. * @type {?Array<Plane>}
  15514. * @default null
  15515. */
  15516. this.clippingPlanes = null;
  15517. /**
  15518. * Changes the behavior of clipping planes so that only their intersection is
  15519. * clipped, rather than their union.
  15520. *
  15521. * @type {boolean}
  15522. * @default false
  15523. */
  15524. this.clipIntersection = false;
  15525. /**
  15526. * Defines whether to clip shadows according to the clipping planes specified
  15527. * on this material.
  15528. *
  15529. * @type {boolean}
  15530. * @default false
  15531. */
  15532. this.clipShadows = false;
  15533. /**
  15534. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  15535. * is determined as follows:
  15536. *
  15537. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  15538. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  15539. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  15540. *
  15541. * @type {?(FrontSide|BackSide|DoubleSide)}
  15542. * @default null
  15543. */
  15544. this.shadowSide = null;
  15545. /**
  15546. * Whether to render the material's color.
  15547. *
  15548. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  15549. * objects that occlude other objects.
  15550. *
  15551. * @type {boolean}
  15552. * @default true
  15553. */
  15554. this.colorWrite = true;
  15555. /**
  15556. * Override the renderer's default precision for this material.
  15557. *
  15558. * @type {?('highp'|'mediump'|'lowp')}
  15559. * @default null
  15560. */
  15561. this.precision = null;
  15562. /**
  15563. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  15564. * be offset after it is interpolated from the depth values of the appropriate vertices.
  15565. * The offset is added before the depth test is performed and before the value is written
  15566. * into the depth buffer.
  15567. *
  15568. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  15569. * rendering solids with highlighted edges.
  15570. *
  15571. * @type {boolean}
  15572. * @default false
  15573. */
  15574. this.polygonOffset = false;
  15575. /**
  15576. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  15577. *
  15578. * @type {number}
  15579. * @default 0
  15580. */
  15581. this.polygonOffsetFactor = 0;
  15582. /**
  15583. * Is multiplied by an implementation-specific value to create a constant depth offset.
  15584. *
  15585. * @type {number}
  15586. * @default 0
  15587. */
  15588. this.polygonOffsetUnits = 0;
  15589. /**
  15590. * Whether to apply dithering to the color to remove the appearance of banding.
  15591. *
  15592. * @type {boolean}
  15593. * @default false
  15594. */
  15595. this.dithering = false;
  15596. /**
  15597. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  15598. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  15599. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  15600. *
  15601. * @type {boolean}
  15602. * @default false
  15603. */
  15604. this.alphaToCoverage = false;
  15605. /**
  15606. * Whether to premultiply the alpha (transparency) value.
  15607. *
  15608. * @type {boolean}
  15609. * @default false
  15610. */
  15611. this.premultipliedAlpha = false;
  15612. /**
  15613. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  15614. *
  15615. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  15616. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  15617. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  15618. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  15619. * disable the two pass rendering to avoid performance issues.
  15620. *
  15621. * @type {boolean}
  15622. * @default false
  15623. */
  15624. this.forceSinglePass = false;
  15625. /**
  15626. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  15627. *
  15628. * @type {boolean}
  15629. * @default true
  15630. */
  15631. this.allowOverride = true;
  15632. /**
  15633. * Defines whether 3D objects using this material are visible.
  15634. *
  15635. * @type {boolean}
  15636. * @default true
  15637. */
  15638. this.visible = true;
  15639. /**
  15640. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  15641. *
  15642. * It is ignored when rendering to a render target or using post processing or when using
  15643. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  15644. *
  15645. * @type {boolean}
  15646. * @default true
  15647. */
  15648. this.toneMapped = true;
  15649. /**
  15650. * An object that can be used to store custom data about the Material. It
  15651. * should not hold references to functions as these will not be cloned.
  15652. *
  15653. * @type {Object}
  15654. */
  15655. this.userData = {};
  15656. /**
  15657. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  15658. *
  15659. * @type {number}
  15660. * @readonly
  15661. * @default 0
  15662. */
  15663. this.version = 0;
  15664. this._alphaTest = 0;
  15665. }
  15666. /**
  15667. * Sets the alpha value to be used when running an alpha test. The material
  15668. * will not be rendered if the opacity is lower than this value.
  15669. *
  15670. * @type {number}
  15671. * @readonly
  15672. * @default 0
  15673. */
  15674. get alphaTest() {
  15675. return this._alphaTest;
  15676. }
  15677. set alphaTest( value ) {
  15678. if ( this._alphaTest > 0 !== value > 0 ) {
  15679. this.version ++;
  15680. }
  15681. this._alphaTest = value;
  15682. }
  15683. /**
  15684. * An optional callback that is executed immediately before the material is used to render a 3D object.
  15685. *
  15686. * This method can only be used when rendering with {@link WebGLRenderer}.
  15687. *
  15688. * @param {WebGLRenderer} renderer - The renderer.
  15689. * @param {Scene} scene - The scene.
  15690. * @param {Camera} camera - The camera that is used to render the scene.
  15691. * @param {BufferGeometry} geometry - The 3D object's geometry.
  15692. * @param {Object3D} object - The 3D object.
  15693. * @param {Object} group - The geometry group data.
  15694. */
  15695. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  15696. /**
  15697. * An optional callback that is executed immediately before the shader
  15698. * program is compiled. This function is called with the shader source code
  15699. * as a parameter. Useful for the modification of built-in materials.
  15700. *
  15701. * This method can only be used when rendering with {@link WebGLRenderer}. The
  15702. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  15703. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  15704. *
  15705. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  15706. * @param {WebGLRenderer} renderer - A reference to the renderer.
  15707. */
  15708. onBeforeCompile( /* shaderobject, renderer */ ) {}
  15709. /**
  15710. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  15711. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  15712. * shader or recompile the shader for this material as needed.
  15713. *
  15714. * This method can only be used when rendering with {@link WebGLRenderer}.
  15715. *
  15716. * @return {string} The custom program cache key.
  15717. */
  15718. customProgramCacheKey() {
  15719. return this.onBeforeCompile.toString();
  15720. }
  15721. /**
  15722. * This method can be used to set default values from parameter objects.
  15723. * It is a generic implementation so it can be used with different types
  15724. * of materials.
  15725. *
  15726. * @param {Object} [values] - The material values to set.
  15727. */
  15728. setValues( values ) {
  15729. if ( values === undefined ) return;
  15730. for ( const key in values ) {
  15731. const newValue = values[ key ];
  15732. if ( newValue === undefined ) {
  15733. warn( `Material: parameter '${ key }' has value of undefined.` );
  15734. continue;
  15735. }
  15736. const currentValue = this[ key ];
  15737. if ( currentValue === undefined ) {
  15738. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  15739. continue;
  15740. }
  15741. if ( currentValue && currentValue.isColor ) {
  15742. currentValue.set( newValue );
  15743. } else if (
  15744. ( ( currentValue && currentValue.isVector2 ) && ( newValue && newValue.isVector2 ) ) ||
  15745. ( ( currentValue && currentValue.isEuler ) && ( newValue && newValue.isEuler ) ) ||
  15746. ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) )
  15747. ) {
  15748. currentValue.copy( newValue );
  15749. } else {
  15750. this[ key ] = newValue;
  15751. }
  15752. }
  15753. }
  15754. /**
  15755. * Serializes the material into JSON.
  15756. *
  15757. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  15758. * @return {Object} A JSON object representing the serialized material.
  15759. * @see {@link ObjectLoader#parse}
  15760. */
  15761. toJSON( meta ) {
  15762. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  15763. if ( isRootObject ) {
  15764. meta = {
  15765. textures: {},
  15766. images: {}
  15767. };
  15768. }
  15769. const data = {
  15770. metadata: {
  15771. version: 4.7,
  15772. type: 'Material',
  15773. generator: 'Material.toJSON'
  15774. }
  15775. };
  15776. // standard Material serialization
  15777. data.uuid = this.uuid;
  15778. data.type = this.type;
  15779. if ( this.name !== '' ) data.name = this.name;
  15780. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  15781. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  15782. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  15783. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  15784. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  15785. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  15786. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  15787. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  15788. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  15789. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  15790. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  15791. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  15792. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  15793. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  15794. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  15795. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  15796. }
  15797. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  15798. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  15799. }
  15800. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  15801. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  15802. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  15803. }
  15804. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  15805. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  15806. }
  15807. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  15808. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  15809. }
  15810. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  15811. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  15812. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  15813. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  15814. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  15815. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  15816. }
  15817. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  15818. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  15819. }
  15820. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  15821. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  15822. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  15823. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  15824. }
  15825. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  15826. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  15827. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  15828. if ( this.lightMap && this.lightMap.isTexture ) {
  15829. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  15830. data.lightMapIntensity = this.lightMapIntensity;
  15831. }
  15832. if ( this.aoMap && this.aoMap.isTexture ) {
  15833. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  15834. data.aoMapIntensity = this.aoMapIntensity;
  15835. }
  15836. if ( this.bumpMap && this.bumpMap.isTexture ) {
  15837. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  15838. data.bumpScale = this.bumpScale;
  15839. }
  15840. if ( this.normalMap && this.normalMap.isTexture ) {
  15841. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  15842. data.normalMapType = this.normalMapType;
  15843. data.normalScale = this.normalScale.toArray();
  15844. }
  15845. if ( this.displacementMap && this.displacementMap.isTexture ) {
  15846. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  15847. data.displacementScale = this.displacementScale;
  15848. data.displacementBias = this.displacementBias;
  15849. }
  15850. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  15851. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  15852. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  15853. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  15854. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  15855. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  15856. if ( this.envMap && this.envMap.isTexture ) {
  15857. data.envMap = this.envMap.toJSON( meta ).uuid;
  15858. if ( this.combine !== undefined ) data.combine = this.combine;
  15859. }
  15860. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  15861. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  15862. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  15863. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  15864. if ( this.gradientMap && this.gradientMap.isTexture ) {
  15865. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  15866. }
  15867. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  15868. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  15869. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  15870. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  15871. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  15872. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  15873. if ( this.size !== undefined ) data.size = this.size;
  15874. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  15875. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  15876. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  15877. if ( this.side !== FrontSide ) data.side = this.side;
  15878. if ( this.vertexColors === true ) data.vertexColors = true;
  15879. if ( this.opacity < 1 ) data.opacity = this.opacity;
  15880. if ( this.transparent === true ) data.transparent = true;
  15881. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  15882. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  15883. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  15884. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  15885. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  15886. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  15887. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  15888. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  15889. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  15890. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  15891. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  15892. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  15893. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  15894. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  15895. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  15896. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  15897. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  15898. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  15899. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  15900. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  15901. // rotation (SpriteMaterial)
  15902. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  15903. if ( this.polygonOffset === true ) data.polygonOffset = true;
  15904. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  15905. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  15906. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  15907. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  15908. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  15909. if ( this.scale !== undefined ) data.scale = this.scale;
  15910. if ( this.dithering === true ) data.dithering = true;
  15911. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  15912. if ( this.alphaHash === true ) data.alphaHash = true;
  15913. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  15914. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  15915. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  15916. if ( this.allowOverride === false ) data.allowOverride = false;
  15917. if ( this.wireframe === true ) data.wireframe = true;
  15918. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  15919. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  15920. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  15921. if ( this.flatShading === true ) data.flatShading = true;
  15922. if ( this.visible === false ) data.visible = false;
  15923. if ( this.toneMapped === false ) data.toneMapped = false;
  15924. if ( this.fog === false ) data.fog = false;
  15925. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15926. // TODO: Copied from Object3D.toJSON
  15927. function extractFromCache( cache ) {
  15928. const values = [];
  15929. for ( const key in cache ) {
  15930. const data = cache[ key ];
  15931. delete data.metadata;
  15932. values.push( data );
  15933. }
  15934. return values;
  15935. }
  15936. if ( isRootObject ) {
  15937. const textures = extractFromCache( meta.textures );
  15938. const images = extractFromCache( meta.images );
  15939. if ( textures.length > 0 ) data.textures = textures;
  15940. if ( images.length > 0 ) data.images = images;
  15941. }
  15942. return data;
  15943. }
  15944. /**
  15945. * Deserializes the material from the given JSON.
  15946. *
  15947. * @param {Object} json - The JSON holding the serialized material.
  15948. * @param {Object<string,Texture>} textures - A dictionary holding textures referenced by the material.
  15949. * @return {Material} A reference to this material.
  15950. */
  15951. fromJSON( json, textures ) {
  15952. if ( json.uuid !== undefined ) this.uuid = json.uuid;
  15953. if ( json.name !== undefined ) this.name = json.name;
  15954. if ( json.color !== undefined && this.color !== undefined ) this.color.setHex( json.color );
  15955. if ( json.roughness !== undefined ) this.roughness = json.roughness;
  15956. if ( json.metalness !== undefined ) this.metalness = json.metalness;
  15957. if ( json.sheen !== undefined ) this.sheen = json.sheen;
  15958. if ( json.sheenColor !== undefined ) this.sheenColor = new Color().setHex( json.sheenColor );
  15959. if ( json.sheenRoughness !== undefined ) this.sheenRoughness = json.sheenRoughness;
  15960. if ( json.emissive !== undefined && this.emissive !== undefined ) this.emissive.setHex( json.emissive );
  15961. if ( json.specular !== undefined && this.specular !== undefined ) this.specular.setHex( json.specular );
  15962. if ( json.specularIntensity !== undefined ) this.specularIntensity = json.specularIntensity;
  15963. if ( json.specularColor !== undefined && this.specularColor !== undefined ) this.specularColor.setHex( json.specularColor );
  15964. if ( json.shininess !== undefined ) this.shininess = json.shininess;
  15965. if ( json.clearcoat !== undefined ) this.clearcoat = json.clearcoat;
  15966. if ( json.clearcoatRoughness !== undefined ) this.clearcoatRoughness = json.clearcoatRoughness;
  15967. if ( json.dispersion !== undefined ) this.dispersion = json.dispersion;
  15968. if ( json.iridescence !== undefined ) this.iridescence = json.iridescence;
  15969. if ( json.iridescenceIOR !== undefined ) this.iridescenceIOR = json.iridescenceIOR;
  15970. if ( json.iridescenceThicknessRange !== undefined ) this.iridescenceThicknessRange = json.iridescenceThicknessRange;
  15971. if ( json.transmission !== undefined ) this.transmission = json.transmission;
  15972. if ( json.thickness !== undefined ) this.thickness = json.thickness;
  15973. if ( json.attenuationDistance !== undefined ) this.attenuationDistance = json.attenuationDistance;
  15974. if ( json.attenuationColor !== undefined && this.attenuationColor !== undefined ) this.attenuationColor.setHex( json.attenuationColor );
  15975. if ( json.anisotropy !== undefined ) this.anisotropy = json.anisotropy;
  15976. if ( json.anisotropyRotation !== undefined ) this.anisotropyRotation = json.anisotropyRotation;
  15977. if ( json.fog !== undefined ) this.fog = json.fog;
  15978. if ( json.flatShading !== undefined ) this.flatShading = json.flatShading;
  15979. if ( json.blending !== undefined ) this.blending = json.blending;
  15980. if ( json.combine !== undefined ) this.combine = json.combine;
  15981. if ( json.side !== undefined ) this.side = json.side;
  15982. if ( json.shadowSide !== undefined ) this.shadowSide = json.shadowSide;
  15983. if ( json.opacity !== undefined ) this.opacity = json.opacity;
  15984. if ( json.transparent !== undefined ) this.transparent = json.transparent;
  15985. if ( json.alphaTest !== undefined ) this.alphaTest = json.alphaTest;
  15986. if ( json.alphaHash !== undefined ) this.alphaHash = json.alphaHash;
  15987. if ( json.depthFunc !== undefined ) this.depthFunc = json.depthFunc;
  15988. if ( json.depthTest !== undefined ) this.depthTest = json.depthTest;
  15989. if ( json.depthWrite !== undefined ) this.depthWrite = json.depthWrite;
  15990. if ( json.colorWrite !== undefined ) this.colorWrite = json.colorWrite;
  15991. if ( json.blendSrc !== undefined ) this.blendSrc = json.blendSrc;
  15992. if ( json.blendDst !== undefined ) this.blendDst = json.blendDst;
  15993. if ( json.blendEquation !== undefined ) this.blendEquation = json.blendEquation;
  15994. if ( json.blendSrcAlpha !== undefined ) this.blendSrcAlpha = json.blendSrcAlpha;
  15995. if ( json.blendDstAlpha !== undefined ) this.blendDstAlpha = json.blendDstAlpha;
  15996. if ( json.blendEquationAlpha !== undefined ) this.blendEquationAlpha = json.blendEquationAlpha;
  15997. if ( json.blendColor !== undefined && this.blendColor !== undefined ) this.blendColor.setHex( json.blendColor );
  15998. if ( json.blendAlpha !== undefined ) this.blendAlpha = json.blendAlpha;
  15999. if ( json.stencilWriteMask !== undefined ) this.stencilWriteMask = json.stencilWriteMask;
  16000. if ( json.stencilFunc !== undefined ) this.stencilFunc = json.stencilFunc;
  16001. if ( json.stencilRef !== undefined ) this.stencilRef = json.stencilRef;
  16002. if ( json.stencilFuncMask !== undefined ) this.stencilFuncMask = json.stencilFuncMask;
  16003. if ( json.stencilFail !== undefined ) this.stencilFail = json.stencilFail;
  16004. if ( json.stencilZFail !== undefined ) this.stencilZFail = json.stencilZFail;
  16005. if ( json.stencilZPass !== undefined ) this.stencilZPass = json.stencilZPass;
  16006. if ( json.stencilWrite !== undefined ) this.stencilWrite = json.stencilWrite;
  16007. if ( json.wireframe !== undefined ) this.wireframe = json.wireframe;
  16008. if ( json.wireframeLinewidth !== undefined ) this.wireframeLinewidth = json.wireframeLinewidth;
  16009. if ( json.wireframeLinecap !== undefined ) this.wireframeLinecap = json.wireframeLinecap;
  16010. if ( json.wireframeLinejoin !== undefined ) this.wireframeLinejoin = json.wireframeLinejoin;
  16011. if ( json.rotation !== undefined ) this.rotation = json.rotation;
  16012. if ( json.linewidth !== undefined ) this.linewidth = json.linewidth;
  16013. if ( json.dashSize !== undefined ) this.dashSize = json.dashSize;
  16014. if ( json.gapSize !== undefined ) this.gapSize = json.gapSize;
  16015. if ( json.scale !== undefined ) this.scale = json.scale;
  16016. if ( json.polygonOffset !== undefined ) this.polygonOffset = json.polygonOffset;
  16017. if ( json.polygonOffsetFactor !== undefined ) this.polygonOffsetFactor = json.polygonOffsetFactor;
  16018. if ( json.polygonOffsetUnits !== undefined ) this.polygonOffsetUnits = json.polygonOffsetUnits;
  16019. if ( json.dithering !== undefined ) this.dithering = json.dithering;
  16020. if ( json.alphaToCoverage !== undefined ) this.alphaToCoverage = json.alphaToCoverage;
  16021. if ( json.premultipliedAlpha !== undefined ) this.premultipliedAlpha = json.premultipliedAlpha;
  16022. if ( json.forceSinglePass !== undefined ) this.forceSinglePass = json.forceSinglePass;
  16023. if ( json.allowOverride !== undefined ) this.allowOverride = json.allowOverride;
  16024. if ( json.visible !== undefined ) this.visible = json.visible;
  16025. if ( json.toneMapped !== undefined ) this.toneMapped = json.toneMapped;
  16026. if ( json.userData !== undefined ) this.userData = json.userData;
  16027. if ( json.vertexColors !== undefined ) {
  16028. if ( typeof json.vertexColors === 'number' ) {
  16029. this.vertexColors = json.vertexColors > 0;
  16030. } else {
  16031. this.vertexColors = json.vertexColors;
  16032. }
  16033. }
  16034. // for PointsMaterial
  16035. if ( json.size !== undefined ) this.size = json.size;
  16036. if ( json.sizeAttenuation !== undefined ) this.sizeAttenuation = json.sizeAttenuation;
  16037. // maps
  16038. if ( json.map !== undefined ) this.map = textures[ json.map ] || null;
  16039. if ( json.matcap !== undefined ) this.matcap = textures[ json.matcap ] || null;
  16040. if ( json.alphaMap !== undefined ) this.alphaMap = textures[ json.alphaMap ] || null;
  16041. if ( json.bumpMap !== undefined ) this.bumpMap = textures[ json.bumpMap ] || null;
  16042. if ( json.bumpScale !== undefined ) this.bumpScale = json.bumpScale;
  16043. if ( json.normalMap !== undefined ) this.normalMap = textures[ json.normalMap ] || null;
  16044. if ( json.normalMapType !== undefined ) this.normalMapType = json.normalMapType;
  16045. if ( json.normalScale !== undefined ) {
  16046. let normalScale = json.normalScale;
  16047. if ( Array.isArray( normalScale ) === false ) {
  16048. // Blender exporter used to export a scalar. See #7459
  16049. normalScale = [ normalScale, normalScale ];
  16050. }
  16051. this.normalScale = new Vector2().fromArray( normalScale );
  16052. }
  16053. if ( json.displacementMap !== undefined ) this.displacementMap = textures[ json.displacementMap ] || null;
  16054. if ( json.displacementScale !== undefined ) this.displacementScale = json.displacementScale;
  16055. if ( json.displacementBias !== undefined ) this.displacementBias = json.displacementBias;
  16056. if ( json.roughnessMap !== undefined ) this.roughnessMap = textures[ json.roughnessMap ] || null;
  16057. if ( json.metalnessMap !== undefined ) this.metalnessMap = textures[ json.metalnessMap ] || null;
  16058. if ( json.emissiveMap !== undefined ) this.emissiveMap = textures[ json.emissiveMap ] || null;
  16059. if ( json.emissiveIntensity !== undefined ) this.emissiveIntensity = json.emissiveIntensity;
  16060. if ( json.specularMap !== undefined ) this.specularMap = textures[ json.specularMap ] || null;
  16061. if ( json.specularIntensityMap !== undefined ) this.specularIntensityMap = textures[ json.specularIntensityMap ] || null;
  16062. if ( json.specularColorMap !== undefined ) this.specularColorMap = textures[ json.specularColorMap ] || null;
  16063. if ( json.envMap !== undefined ) this.envMap = textures[ json.envMap ] || null;
  16064. if ( json.envMapRotation !== undefined ) this.envMapRotation.fromArray( json.envMapRotation );
  16065. if ( json.envMapIntensity !== undefined ) this.envMapIntensity = json.envMapIntensity;
  16066. if ( json.reflectivity !== undefined ) this.reflectivity = json.reflectivity;
  16067. if ( json.refractionRatio !== undefined ) this.refractionRatio = json.refractionRatio;
  16068. if ( json.lightMap !== undefined ) this.lightMap = textures[ json.lightMap ] || null;
  16069. if ( json.lightMapIntensity !== undefined ) this.lightMapIntensity = json.lightMapIntensity;
  16070. if ( json.aoMap !== undefined ) this.aoMap = textures[ json.aoMap ] || null;
  16071. if ( json.aoMapIntensity !== undefined ) this.aoMapIntensity = json.aoMapIntensity;
  16072. if ( json.gradientMap !== undefined ) this.gradientMap = textures[ json.gradientMap ] || null;
  16073. if ( json.clearcoatMap !== undefined ) this.clearcoatMap = textures[ json.clearcoatMap ] || null;
  16074. if ( json.clearcoatRoughnessMap !== undefined ) this.clearcoatRoughnessMap = textures[ json.clearcoatRoughnessMap ] || null;
  16075. if ( json.clearcoatNormalMap !== undefined ) this.clearcoatNormalMap = textures[ json.clearcoatNormalMap ] || null;
  16076. if ( json.clearcoatNormalScale !== undefined ) this.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16077. if ( json.iridescenceMap !== undefined ) this.iridescenceMap = textures[ json.iridescenceMap ] || null;
  16078. if ( json.iridescenceThicknessMap !== undefined ) this.iridescenceThicknessMap = textures[ json.iridescenceThicknessMap ] || null;
  16079. if ( json.transmissionMap !== undefined ) this.transmissionMap = textures[ json.transmissionMap ] || null;
  16080. if ( json.thicknessMap !== undefined ) this.thicknessMap = textures[ json.thicknessMap ] || null;
  16081. if ( json.anisotropyMap !== undefined ) this.anisotropyMap = textures[ json.anisotropyMap ] || null;
  16082. if ( json.sheenColorMap !== undefined ) this.sheenColorMap = textures[ json.sheenColorMap ] || null;
  16083. if ( json.sheenRoughnessMap !== undefined ) this.sheenRoughnessMap = textures[ json.sheenRoughnessMap ] || null;
  16084. return this;
  16085. }
  16086. /**
  16087. * Returns a new material with copied values from this instance.
  16088. *
  16089. * @return {Material} A clone of this instance.
  16090. */
  16091. clone() {
  16092. return new this.constructor().copy( this );
  16093. }
  16094. /**
  16095. * Copies the values of the given material to this instance.
  16096. *
  16097. * @param {Material} source - The material to copy.
  16098. * @return {Material} A reference to this instance.
  16099. */
  16100. copy( source ) {
  16101. this.name = source.name;
  16102. this.blending = source.blending;
  16103. this.side = source.side;
  16104. this.vertexColors = source.vertexColors;
  16105. this.opacity = source.opacity;
  16106. this.transparent = source.transparent;
  16107. this.blendSrc = source.blendSrc;
  16108. this.blendDst = source.blendDst;
  16109. this.blendEquation = source.blendEquation;
  16110. this.blendSrcAlpha = source.blendSrcAlpha;
  16111. this.blendDstAlpha = source.blendDstAlpha;
  16112. this.blendEquationAlpha = source.blendEquationAlpha;
  16113. this.blendColor.copy( source.blendColor );
  16114. this.blendAlpha = source.blendAlpha;
  16115. this.depthFunc = source.depthFunc;
  16116. this.depthTest = source.depthTest;
  16117. this.depthWrite = source.depthWrite;
  16118. this.stencilWriteMask = source.stencilWriteMask;
  16119. this.stencilFunc = source.stencilFunc;
  16120. this.stencilRef = source.stencilRef;
  16121. this.stencilFuncMask = source.stencilFuncMask;
  16122. this.stencilFail = source.stencilFail;
  16123. this.stencilZFail = source.stencilZFail;
  16124. this.stencilZPass = source.stencilZPass;
  16125. this.stencilWrite = source.stencilWrite;
  16126. const srcPlanes = source.clippingPlanes;
  16127. let dstPlanes = null;
  16128. if ( srcPlanes !== null ) {
  16129. const n = srcPlanes.length;
  16130. dstPlanes = new Array( n );
  16131. for ( let i = 0; i !== n; ++ i ) {
  16132. dstPlanes[ i ] = srcPlanes[ i ].clone();
  16133. }
  16134. }
  16135. this.clippingPlanes = dstPlanes;
  16136. this.clipIntersection = source.clipIntersection;
  16137. this.clipShadows = source.clipShadows;
  16138. this.shadowSide = source.shadowSide;
  16139. this.colorWrite = source.colorWrite;
  16140. this.precision = source.precision;
  16141. this.polygonOffset = source.polygonOffset;
  16142. this.polygonOffsetFactor = source.polygonOffsetFactor;
  16143. this.polygonOffsetUnits = source.polygonOffsetUnits;
  16144. this.dithering = source.dithering;
  16145. this.alphaTest = source.alphaTest;
  16146. this.alphaHash = source.alphaHash;
  16147. this.alphaToCoverage = source.alphaToCoverage;
  16148. this.premultipliedAlpha = source.premultipliedAlpha;
  16149. this.forceSinglePass = source.forceSinglePass;
  16150. this.allowOverride = source.allowOverride;
  16151. this.visible = source.visible;
  16152. this.toneMapped = source.toneMapped;
  16153. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  16154. return this;
  16155. }
  16156. /**
  16157. * Frees the GPU-related resources allocated by this instance. Call this
  16158. * method whenever this instance is no longer used in your app.
  16159. *
  16160. * @fires Material#dispose
  16161. */
  16162. dispose() {
  16163. /**
  16164. * Fires when the material has been disposed of.
  16165. *
  16166. * @event Material#dispose
  16167. * @type {Object}
  16168. */
  16169. this.dispatchEvent( { type: 'dispose' } );
  16170. }
  16171. /**
  16172. * Setting this property to `true` indicates the engine the material
  16173. * needs to be recompiled.
  16174. *
  16175. * @type {boolean}
  16176. * @default false
  16177. * @param {boolean} value
  16178. */
  16179. set needsUpdate( value ) {
  16180. if ( value === true ) this.version ++;
  16181. }
  16182. }
  16183. /**
  16184. * A material for rendering instances of {@link Sprite}.
  16185. *
  16186. * ```js
  16187. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  16188. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  16189. *
  16190. * const sprite = new THREE.Sprite( material );
  16191. * sprite.scale.set(200, 200, 1)
  16192. * scene.add( sprite );
  16193. * ```
  16194. *
  16195. * @augments Material
  16196. */
  16197. class SpriteMaterial extends Material {
  16198. /**
  16199. * Constructs a new sprite material.
  16200. *
  16201. * @param {Object} [parameters] - An object with one or more properties
  16202. * defining the material's appearance. Any property of the material
  16203. * (including any property from inherited materials) can be passed
  16204. * in here. Color values can be passed any type of value accepted
  16205. * by {@link Color#set}.
  16206. */
  16207. constructor( parameters ) {
  16208. super();
  16209. /**
  16210. * This flag can be used for type testing.
  16211. *
  16212. * @type {boolean}
  16213. * @readonly
  16214. * @default true
  16215. */
  16216. this.isSpriteMaterial = true;
  16217. this.type = 'SpriteMaterial';
  16218. /**
  16219. * Color of the material.
  16220. *
  16221. * @type {Color}
  16222. * @default (1,1,1)
  16223. */
  16224. this.color = new Color( 0xffffff );
  16225. /**
  16226. * The color map. May optionally include an alpha channel, typically combined
  16227. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  16228. * color is modulated by the diffuse `color`.
  16229. *
  16230. * `map` represents color data, and the texture must be assigned a
  16231. * {@link Texture#colorSpace}. Most `map` textures set
  16232. * `texture.colorSpace = SRGBColorSpace`.
  16233. *
  16234. * @type {?Texture}
  16235. * @default null
  16236. */
  16237. this.map = null;
  16238. /**
  16239. * The alpha map is a grayscale texture that controls the opacity across the
  16240. * surface (black: fully transparent; white: fully opaque).
  16241. *
  16242. * Only the color of the texture is used, ignoring the alpha channel if one
  16243. * exists. For RGB and RGBA textures, the renderer will use the green channel
  16244. * when sampling this texture due to the extra bit of precision provided for
  16245. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  16246. * luminance/alpha textures will also still work as expected.
  16247. *
  16248. * `alphaMap` represents non-color data. Any texture assigned must have
  16249. * `texture.colorSpace = NoColorSpace` (default).
  16250. *
  16251. * @type {?Texture}
  16252. * @default null
  16253. */
  16254. this.alphaMap = null;
  16255. /**
  16256. * The rotation of the sprite in radians.
  16257. *
  16258. * @type {number}
  16259. * @default 0
  16260. */
  16261. this.rotation = 0;
  16262. /**
  16263. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  16264. *
  16265. * @type {boolean}
  16266. * @default true
  16267. */
  16268. this.sizeAttenuation = true;
  16269. /**
  16270. * Overwritten since sprite materials are transparent
  16271. * by default.
  16272. *
  16273. * @type {boolean}
  16274. * @default true
  16275. */
  16276. this.transparent = true;
  16277. /**
  16278. * Whether the material is affected by fog or not.
  16279. *
  16280. * @type {boolean}
  16281. * @default true
  16282. */
  16283. this.fog = true;
  16284. this.setValues( parameters );
  16285. }
  16286. copy( source ) {
  16287. super.copy( source );
  16288. this.color.copy( source.color );
  16289. this.map = source.map;
  16290. this.alphaMap = source.alphaMap;
  16291. this.rotation = source.rotation;
  16292. this.sizeAttenuation = source.sizeAttenuation;
  16293. this.fog = source.fog;
  16294. return this;
  16295. }
  16296. }
  16297. let _geometry;
  16298. const _intersectPoint = /*@__PURE__*/ new Vector3();
  16299. const _worldScale = /*@__PURE__*/ new Vector3();
  16300. const _mvPosition = /*@__PURE__*/ new Vector3();
  16301. const _alignedPosition = /*@__PURE__*/ new Vector2();
  16302. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  16303. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  16304. const _vA$1 = /*@__PURE__*/ new Vector3();
  16305. const _vB$1 = /*@__PURE__*/ new Vector3();
  16306. const _vC$1 = /*@__PURE__*/ new Vector3();
  16307. const _uvA = /*@__PURE__*/ new Vector2();
  16308. const _uvB = /*@__PURE__*/ new Vector2();
  16309. const _uvC = /*@__PURE__*/ new Vector2();
  16310. /**
  16311. * A sprite is a plane that always faces towards the camera, generally with a
  16312. * partially transparent texture applied.
  16313. *
  16314. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  16315. * have no effect.
  16316. *
  16317. * ```js
  16318. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  16319. * const material = new THREE.SpriteMaterial( { map: map } );
  16320. *
  16321. * const sprite = new THREE.Sprite( material );
  16322. * scene.add( sprite );
  16323. * ```
  16324. *
  16325. * @augments Object3D
  16326. */
  16327. class Sprite extends Object3D {
  16328. /**
  16329. * Constructs a new sprite.
  16330. *
  16331. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  16332. */
  16333. constructor( material = new SpriteMaterial() ) {
  16334. super();
  16335. /**
  16336. * This flag can be used for type testing.
  16337. *
  16338. * @type {boolean}
  16339. * @readonly
  16340. * @default true
  16341. */
  16342. this.isSprite = true;
  16343. this.type = 'Sprite';
  16344. if ( _geometry === undefined ) {
  16345. _geometry = new BufferGeometry();
  16346. const float32Array = new Float32Array( [
  16347. -0.5, -0.5, 0, 0, 0,
  16348. 0.5, -0.5, 0, 1, 0,
  16349. 0.5, 0.5, 0, 1, 1,
  16350. -0.5, 0.5, 0, 0, 1
  16351. ] );
  16352. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16353. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16354. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16355. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16356. }
  16357. /**
  16358. * The sprite geometry.
  16359. *
  16360. * @type {BufferGeometry}
  16361. */
  16362. this.geometry = _geometry;
  16363. /**
  16364. * The sprite material.
  16365. *
  16366. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  16367. */
  16368. this.material = material;
  16369. /**
  16370. * The sprite's anchor point, and the point around which the sprite rotates.
  16371. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  16372. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  16373. *
  16374. * @type {Vector2}
  16375. * @default (0.5,0.5)
  16376. */
  16377. this.center = new Vector2( 0.5, 0.5 );
  16378. /**
  16379. * The number of instances of this sprite.
  16380. * Can only be used with {@link WebGPURenderer}.
  16381. *
  16382. * @type {number}
  16383. * @default 1
  16384. */
  16385. this.count = 1;
  16386. }
  16387. /**
  16388. * Computes intersection points between a casted ray and this sprite.
  16389. *
  16390. * @param {Raycaster} raycaster - The raycaster.
  16391. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16392. */
  16393. raycast( raycaster, intersects ) {
  16394. if ( raycaster.camera === null ) {
  16395. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16396. }
  16397. _worldScale.setFromMatrixScale( this.matrixWorld );
  16398. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16399. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16400. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16401. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16402. _worldScale.multiplyScalar( - _mvPosition.z );
  16403. }
  16404. const rotation = this.material.rotation;
  16405. let sin, cos;
  16406. if ( rotation !== 0 ) {
  16407. cos = Math.cos( rotation );
  16408. sin = Math.sin( rotation );
  16409. }
  16410. const center = this.center;
  16411. transformVertex( _vA$1.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16412. transformVertex( _vB$1.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16413. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16414. _uvA.set( 0, 0 );
  16415. _uvB.set( 1, 0 );
  16416. _uvC.set( 1, 1 );
  16417. // check first triangle
  16418. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16419. if ( intersect === null ) {
  16420. // check second triangle
  16421. transformVertex( _vB$1.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16422. _uvB.set( 0, 1 );
  16423. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16424. if ( intersect === null ) {
  16425. return;
  16426. }
  16427. }
  16428. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16429. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16430. intersects.push( {
  16431. distance: distance,
  16432. point: _intersectPoint.clone(),
  16433. uv: Triangle.getInterpolation( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA, _uvB, _uvC, new Vector2() ),
  16434. face: null,
  16435. object: this
  16436. } );
  16437. }
  16438. copy( source, recursive ) {
  16439. super.copy( source, recursive );
  16440. if ( source.center !== undefined ) this.center.copy( source.center );
  16441. this.material = source.material;
  16442. return this;
  16443. }
  16444. }
  16445. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16446. // compute position in camera space
  16447. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16448. // to check if rotation is not zero
  16449. if ( sin !== undefined ) {
  16450. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16451. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16452. } else {
  16453. _rotatedPosition.copy( _alignedPosition );
  16454. }
  16455. vertexPosition.copy( mvPosition );
  16456. vertexPosition.x += _rotatedPosition.x;
  16457. vertexPosition.y += _rotatedPosition.y;
  16458. // transform to world space
  16459. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16460. }
  16461. const _v1$2 = /*@__PURE__*/ new Vector3();
  16462. const _v2$1 = /*@__PURE__*/ new Vector3();
  16463. /**
  16464. * A component for providing a basic Level of Detail (LOD) mechanism.
  16465. *
  16466. * Every LOD level is associated with an object, and rendering can be switched
  16467. * between them at the distances specified. Typically you would create, say,
  16468. * three meshes, one for far away (low detail), one for mid range (medium
  16469. * detail) and one for close up (high detail).
  16470. *
  16471. * ```js
  16472. * const lod = new THREE.LOD();
  16473. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  16474. *
  16475. * //Create spheres with 3 levels of detail and create new LOD levels for them
  16476. * for( let i = 0; i < 3; i++ ) {
  16477. *
  16478. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  16479. * const mesh = new THREE.Mesh( geometry, material );
  16480. * lod.addLevel( mesh, i * 75 );
  16481. *
  16482. * }
  16483. *
  16484. * scene.add( lod );
  16485. * ```
  16486. *
  16487. * @augments Object3D
  16488. */
  16489. class LOD extends Object3D {
  16490. /**
  16491. * Constructs a new LOD.
  16492. */
  16493. constructor() {
  16494. super();
  16495. /**
  16496. * This flag can be used for type testing.
  16497. *
  16498. * @type {boolean}
  16499. * @readonly
  16500. * @default true
  16501. */
  16502. this.isLOD = true;
  16503. /**
  16504. * The current LOD index.
  16505. *
  16506. * @private
  16507. * @type {number}
  16508. * @default 0
  16509. */
  16510. this._currentLevel = 0;
  16511. this.type = 'LOD';
  16512. Object.defineProperties( this, {
  16513. /**
  16514. * This array holds the LOD levels.
  16515. *
  16516. * @name LOD#levels
  16517. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  16518. */
  16519. levels: {
  16520. enumerable: true,
  16521. value: []
  16522. }
  16523. } );
  16524. /**
  16525. * Whether the LOD object is updated automatically by the renderer per frame
  16526. * or not. If set to `false`, you have to call {@link LOD#update} in the
  16527. * render loop by yourself.
  16528. *
  16529. * @type {boolean}
  16530. * @default true
  16531. */
  16532. this.autoUpdate = true;
  16533. }
  16534. copy( source ) {
  16535. super.copy( source, false );
  16536. const levels = source.levels;
  16537. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16538. const level = levels[ i ];
  16539. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  16540. }
  16541. this.autoUpdate = source.autoUpdate;
  16542. return this;
  16543. }
  16544. /**
  16545. * Adds a mesh that will display at a certain distance and greater. Typically
  16546. * the further away the distance, the lower the detail on the mesh.
  16547. *
  16548. * @param {Object3D} object - The 3D object to display at this level.
  16549. * @param {number} [distance=0] - The distance at which to display this level of detail.
  16550. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  16551. * @return {LOD} A reference to this instance.
  16552. */
  16553. addLevel( object, distance = 0, hysteresis = 0 ) {
  16554. distance = Math.abs( distance );
  16555. const levels = this.levels;
  16556. let l;
  16557. for ( l = 0; l < levels.length; l ++ ) {
  16558. if ( distance < levels[ l ].distance ) {
  16559. break;
  16560. }
  16561. }
  16562. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  16563. this.add( object );
  16564. return this;
  16565. }
  16566. /**
  16567. * Removes an existing level, based on the distance from the camera.
  16568. * Returns `true` when the level has been removed. Otherwise `false`.
  16569. *
  16570. * @param {number} distance - Distance of the level to remove.
  16571. * @return {boolean} Whether the level has been removed or not.
  16572. */
  16573. removeLevel( distance ) {
  16574. const levels = this.levels;
  16575. for ( let i = 0; i < levels.length; i ++ ) {
  16576. if ( levels[ i ].distance === distance ) {
  16577. const removedElements = levels.splice( i, 1 );
  16578. this.remove( removedElements[ 0 ].object );
  16579. return true;
  16580. }
  16581. }
  16582. return false;
  16583. }
  16584. /**
  16585. * Returns the currently active LOD level index.
  16586. *
  16587. * @return {number} The current active LOD level index.
  16588. */
  16589. getCurrentLevel() {
  16590. return this._currentLevel;
  16591. }
  16592. /**
  16593. * Returns a reference to the first 3D object that is greater than
  16594. * the given distance.
  16595. *
  16596. * @param {number} distance - The LOD distance.
  16597. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  16598. */
  16599. getObjectForDistance( distance ) {
  16600. const levels = this.levels;
  16601. if ( levels.length > 0 ) {
  16602. let i, l;
  16603. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16604. let levelDistance = levels[ i ].distance;
  16605. if ( levels[ i ].object.visible ) {
  16606. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16607. }
  16608. if ( distance < levelDistance ) {
  16609. break;
  16610. }
  16611. }
  16612. return levels[ i - 1 ].object;
  16613. }
  16614. return null;
  16615. }
  16616. /**
  16617. * Computes intersection points between a casted ray and this LOD.
  16618. *
  16619. * @param {Raycaster} raycaster - The raycaster.
  16620. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16621. */
  16622. raycast( raycaster, intersects ) {
  16623. const levels = this.levels;
  16624. if ( levels.length > 0 ) {
  16625. _v1$2.setFromMatrixPosition( this.matrixWorld );
  16626. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  16627. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16628. }
  16629. }
  16630. /**
  16631. * Updates the LOD by computing which LOD level should be visible according
  16632. * to the current distance of the given camera.
  16633. *
  16634. * @param {Camera} camera - The camera the scene is rendered with.
  16635. */
  16636. update( camera ) {
  16637. const levels = this.levels;
  16638. if ( levels.length > 1 ) {
  16639. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  16640. _v2$1.setFromMatrixPosition( this.matrixWorld );
  16641. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  16642. levels[ 0 ].object.visible = true;
  16643. let i, l;
  16644. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16645. let levelDistance = levels[ i ].distance;
  16646. if ( levels[ i ].object.visible ) {
  16647. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16648. }
  16649. if ( distance >= levelDistance ) {
  16650. levels[ i - 1 ].object.visible = false;
  16651. levels[ i ].object.visible = true;
  16652. } else {
  16653. break;
  16654. }
  16655. }
  16656. this._currentLevel = i - 1;
  16657. for ( ; i < l; i ++ ) {
  16658. levels[ i ].object.visible = false;
  16659. }
  16660. }
  16661. }
  16662. toJSON( meta ) {
  16663. const data = super.toJSON( meta );
  16664. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16665. data.object.levels = [];
  16666. const levels = this.levels;
  16667. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16668. const level = levels[ i ];
  16669. data.object.levels.push( {
  16670. object: level.object.uuid,
  16671. distance: level.distance,
  16672. hysteresis: level.hysteresis
  16673. } );
  16674. }
  16675. return data;
  16676. }
  16677. }
  16678. const _vector$7 = /*@__PURE__*/ new Vector3();
  16679. const _segCenter = /*@__PURE__*/ new Vector3();
  16680. const _segDir = /*@__PURE__*/ new Vector3();
  16681. const _diff = /*@__PURE__*/ new Vector3();
  16682. /**
  16683. * A ray that emits from an origin in a certain direction. The class is used by
  16684. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  16685. * mouse picking (working out what objects in the 3D space the mouse is over)
  16686. * amongst other things.
  16687. */
  16688. class Ray {
  16689. /**
  16690. * Constructs a new ray.
  16691. *
  16692. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  16693. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  16694. */
  16695. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  16696. /**
  16697. * The origin of the ray.
  16698. *
  16699. * @type {Vector3}
  16700. */
  16701. this.origin = origin;
  16702. /**
  16703. * The (normalized) direction of the ray.
  16704. *
  16705. * @type {Vector3}
  16706. */
  16707. this.direction = direction;
  16708. }
  16709. /**
  16710. * Sets the ray's components by copying the given values.
  16711. *
  16712. * @param {Vector3} origin - The origin.
  16713. * @param {Vector3} direction - The direction.
  16714. * @return {Ray} A reference to this ray.
  16715. */
  16716. set( origin, direction ) {
  16717. this.origin.copy( origin );
  16718. this.direction.copy( direction );
  16719. return this;
  16720. }
  16721. /**
  16722. * Copies the values of the given ray to this instance.
  16723. *
  16724. * @param {Ray} ray - The ray to copy.
  16725. * @return {Ray} A reference to this ray.
  16726. */
  16727. copy( ray ) {
  16728. this.origin.copy( ray.origin );
  16729. this.direction.copy( ray.direction );
  16730. return this;
  16731. }
  16732. /**
  16733. * Returns a vector that is located at a given distance along this ray.
  16734. *
  16735. * @param {number} t - The distance along the ray to retrieve a position for.
  16736. * @param {Vector3} target - The target vector that is used to store the method's result.
  16737. * @return {Vector3} A position on the ray.
  16738. */
  16739. at( t, target ) {
  16740. return target.copy( this.origin ).addScaledVector( this.direction, t );
  16741. }
  16742. /**
  16743. * Adjusts the direction of the ray to point at the given vector in world space.
  16744. *
  16745. * @param {Vector3} v - The target position.
  16746. * @return {Ray} A reference to this ray.
  16747. */
  16748. lookAt( v ) {
  16749. this.direction.copy( v ).sub( this.origin ).normalize();
  16750. return this;
  16751. }
  16752. /**
  16753. * Shift the origin of this ray along its direction by the given distance.
  16754. *
  16755. * @param {number} t - The distance along the ray to interpolate.
  16756. * @return {Ray} A reference to this ray.
  16757. */
  16758. recast( t ) {
  16759. this.origin.copy( this.at( t, _vector$7 ) );
  16760. return this;
  16761. }
  16762. /**
  16763. * Returns the point along this ray that is closest to the given point.
  16764. *
  16765. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  16766. * @param {Vector3} target - The target vector that is used to store the method's result.
  16767. * @return {Vector3} The closest point on this ray.
  16768. */
  16769. closestPointToPoint( point, target ) {
  16770. target.subVectors( point, this.origin );
  16771. const directionDistance = target.dot( this.direction );
  16772. if ( directionDistance < 0 ) {
  16773. return target.copy( this.origin );
  16774. }
  16775. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16776. }
  16777. /**
  16778. * Returns the distance of the closest approach between this ray and the given point.
  16779. *
  16780. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16781. * @return {number} The distance.
  16782. */
  16783. distanceToPoint( point ) {
  16784. return Math.sqrt( this.distanceSqToPoint( point ) );
  16785. }
  16786. /**
  16787. * Returns the squared distance of the closest approach between this ray and the given point.
  16788. *
  16789. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16790. * @return {number} The squared distance.
  16791. */
  16792. distanceSqToPoint( point ) {
  16793. const directionDistance = _vector$7.subVectors( point, this.origin ).dot( this.direction );
  16794. // point behind the ray
  16795. if ( directionDistance < 0 ) {
  16796. return this.origin.distanceToSquared( point );
  16797. }
  16798. _vector$7.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16799. return _vector$7.distanceToSquared( point );
  16800. }
  16801. /**
  16802. * Returns the squared distance between this ray and the given line segment.
  16803. *
  16804. * @param {Vector3} v0 - The start point of the line segment.
  16805. * @param {Vector3} v1 - The end point of the line segment.
  16806. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  16807. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  16808. * @return {number} The squared distance.
  16809. */
  16810. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  16811. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  16812. // It returns the min distance between the ray and the segment
  16813. // defined by v0 and v1
  16814. // It can also set two optional targets :
  16815. // - The closest point on the ray
  16816. // - The closest point on the segment
  16817. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  16818. _segDir.copy( v1 ).sub( v0 ).normalize();
  16819. _diff.copy( this.origin ).sub( _segCenter );
  16820. const segExtent = v0.distanceTo( v1 ) * 0.5;
  16821. const a01 = - this.direction.dot( _segDir );
  16822. const b0 = _diff.dot( this.direction );
  16823. const b1 = - _diff.dot( _segDir );
  16824. const c = _diff.lengthSq();
  16825. const det = Math.abs( 1 - a01 * a01 );
  16826. let s0, s1, sqrDist, extDet;
  16827. if ( det > 0 ) {
  16828. // The ray and segment are not parallel.
  16829. s0 = a01 * b1 - b0;
  16830. s1 = a01 * b0 - b1;
  16831. extDet = segExtent * det;
  16832. if ( s0 >= 0 ) {
  16833. if ( s1 >= - extDet ) {
  16834. if ( s1 <= extDet ) {
  16835. // region 0
  16836. // Minimum at interior points of ray and segment.
  16837. const invDet = 1 / det;
  16838. s0 *= invDet;
  16839. s1 *= invDet;
  16840. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  16841. } else {
  16842. // region 1
  16843. s1 = segExtent;
  16844. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16845. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16846. }
  16847. } else {
  16848. // region 5
  16849. s1 = - segExtent;
  16850. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16851. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16852. }
  16853. } else {
  16854. if ( s1 <= - extDet ) {
  16855. // region 4
  16856. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  16857. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16858. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16859. } else if ( s1 <= extDet ) {
  16860. // region 3
  16861. s0 = 0;
  16862. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16863. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  16864. } else {
  16865. // region 2
  16866. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  16867. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16868. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16869. }
  16870. }
  16871. } else {
  16872. // Ray and segment are parallel.
  16873. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  16874. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16875. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16876. }
  16877. if ( optionalPointOnRay ) {
  16878. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  16879. }
  16880. if ( optionalPointOnSegment ) {
  16881. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  16882. }
  16883. return sqrDist;
  16884. }
  16885. /**
  16886. * Intersects this ray with the given sphere, returning the intersection
  16887. * point or `null` if there is no intersection.
  16888. *
  16889. * @param {Sphere} sphere - The sphere to intersect.
  16890. * @param {Vector3} target - The target vector that is used to store the method's result.
  16891. * @return {?Vector3} The intersection point.
  16892. */
  16893. intersectSphere( sphere, target ) {
  16894. _vector$7.subVectors( sphere.center, this.origin );
  16895. const tca = _vector$7.dot( this.direction );
  16896. const d2 = _vector$7.dot( _vector$7 ) - tca * tca;
  16897. const radius2 = sphere.radius * sphere.radius;
  16898. if ( d2 > radius2 ) return null;
  16899. const thc = Math.sqrt( radius2 - d2 );
  16900. // t0 = first intersect point - entrance on front of sphere
  16901. const t0 = tca - thc;
  16902. // t1 = second intersect point - exit point on back of sphere
  16903. const t1 = tca + thc;
  16904. // test to see if t1 is behind the ray - if so, return null
  16905. if ( t1 < 0 ) return null;
  16906. // test to see if t0 is behind the ray:
  16907. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  16908. // in order to always return an intersect point that is in front of the ray.
  16909. if ( t0 < 0 ) return this.at( t1, target );
  16910. // else t0 is in front of the ray, so return the first collision point scaled by t0
  16911. return this.at( t0, target );
  16912. }
  16913. /**
  16914. * Returns `true` if this ray intersects with the given sphere.
  16915. *
  16916. * @param {Sphere} sphere - The sphere to intersect.
  16917. * @return {boolean} Whether this ray intersects with the given sphere or not.
  16918. */
  16919. intersectsSphere( sphere ) {
  16920. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  16921. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  16922. }
  16923. /**
  16924. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  16925. * does not intersect with the plane.
  16926. *
  16927. * @param {Plane} plane - The plane to compute the distance to.
  16928. * @return {?number} Whether this ray intersects with the given sphere or not.
  16929. */
  16930. distanceToPlane( plane ) {
  16931. const denominator = plane.normal.dot( this.direction );
  16932. if ( denominator === 0 ) {
  16933. // line is coplanar, return origin
  16934. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  16935. return 0;
  16936. }
  16937. // Null is preferable to undefined since undefined means.... it is undefined
  16938. return null;
  16939. }
  16940. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  16941. // Return if the ray never intersects the plane
  16942. return t >= 0 ? t : null;
  16943. }
  16944. /**
  16945. * Intersects this ray with the given plane, returning the intersection
  16946. * point or `null` if there is no intersection.
  16947. *
  16948. * @param {Plane} plane - The plane to intersect.
  16949. * @param {Vector3} target - The target vector that is used to store the method's result.
  16950. * @return {?Vector3} The intersection point.
  16951. */
  16952. intersectPlane( plane, target ) {
  16953. const t = this.distanceToPlane( plane );
  16954. if ( t === null ) {
  16955. return null;
  16956. }
  16957. return this.at( t, target );
  16958. }
  16959. /**
  16960. * Returns `true` if this ray intersects with the given plane.
  16961. *
  16962. * @param {Plane} plane - The plane to intersect.
  16963. * @return {boolean} Whether this ray intersects with the given plane or not.
  16964. */
  16965. intersectsPlane( plane ) {
  16966. // check if the ray lies on the plane first
  16967. const distToPoint = plane.distanceToPoint( this.origin );
  16968. if ( distToPoint === 0 ) {
  16969. return true;
  16970. }
  16971. const denominator = plane.normal.dot( this.direction );
  16972. if ( denominator * distToPoint < 0 ) {
  16973. return true;
  16974. }
  16975. // ray origin is behind the plane (and is pointing behind it)
  16976. return false;
  16977. }
  16978. /**
  16979. * Intersects this ray with the given bounding box, returning the intersection
  16980. * point or `null` if there is no intersection.
  16981. *
  16982. * @param {Box3} box - The box to intersect.
  16983. * @param {Vector3} target - The target vector that is used to store the method's result.
  16984. * @return {?Vector3} The intersection point.
  16985. */
  16986. intersectBox( box, target ) {
  16987. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  16988. const invdirx = 1 / this.direction.x,
  16989. invdiry = 1 / this.direction.y,
  16990. invdirz = 1 / this.direction.z;
  16991. const origin = this.origin;
  16992. if ( invdirx >= 0 ) {
  16993. tmin = ( box.min.x - origin.x ) * invdirx;
  16994. tmax = ( box.max.x - origin.x ) * invdirx;
  16995. } else {
  16996. tmin = ( box.max.x - origin.x ) * invdirx;
  16997. tmax = ( box.min.x - origin.x ) * invdirx;
  16998. }
  16999. if ( invdiry >= 0 ) {
  17000. tymin = ( box.min.y - origin.y ) * invdiry;
  17001. tymax = ( box.max.y - origin.y ) * invdiry;
  17002. } else {
  17003. tymin = ( box.max.y - origin.y ) * invdiry;
  17004. tymax = ( box.min.y - origin.y ) * invdiry;
  17005. }
  17006. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  17007. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  17008. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  17009. if ( invdirz >= 0 ) {
  17010. tzmin = ( box.min.z - origin.z ) * invdirz;
  17011. tzmax = ( box.max.z - origin.z ) * invdirz;
  17012. } else {
  17013. tzmin = ( box.max.z - origin.z ) * invdirz;
  17014. tzmax = ( box.min.z - origin.z ) * invdirz;
  17015. }
  17016. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  17017. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  17018. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  17019. //return point closest to the ray (positive side)
  17020. if ( tmax < 0 ) return null;
  17021. return this.at( tmin >= 0 ? tmin : tmax, target );
  17022. }
  17023. /**
  17024. * Returns `true` if this ray intersects with the given box.
  17025. *
  17026. * @param {Box3} box - The box to intersect.
  17027. * @return {boolean} Whether this ray intersects with the given box or not.
  17028. */
  17029. intersectsBox( box ) {
  17030. return this.intersectBox( box, _vector$7 ) !== null;
  17031. }
  17032. /**
  17033. * Intersects this ray with the given triangle, returning the intersection
  17034. * point or `null` if there is no intersection.
  17035. *
  17036. * @param {Vector3} a - The first vertex of the triangle.
  17037. * @param {Vector3} b - The second vertex of the triangle.
  17038. * @param {Vector3} c - The third vertex of the triangle.
  17039. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  17040. * @param {Vector3} target - The target vector that is used to store the method's result.
  17041. * @return {?Vector3} The intersection point.
  17042. */
  17043. intersectTriangle( a, b, c, backfaceCulling, target ) {
  17044. // Watertight ray/triangle intersection. Reference: Woop, Benthin, Wald,
  17045. // "Watertight Ray/Triangle Intersection", JCGT vol. 2 no. 1 (2013), Appendix A.
  17046. // https://jcgt.org/published/0002/01/05/
  17047. const origin = this.origin;
  17048. const direction = this.direction;
  17049. const dx = direction.x;
  17050. const dy = direction.y;
  17051. const dz = direction.z;
  17052. // triangle vertices relative to the ray origin
  17053. const aox = a.x - origin.x, aoy = a.y - origin.y, aoz = a.z - origin.z;
  17054. const box = b.x - origin.x, boy = b.y - origin.y, boz = b.z - origin.z;
  17055. const cox = c.x - origin.x, coy = c.y - origin.y, coz = c.z - origin.z;
  17056. // Use the dimension where the ray direction is maximal as the projection
  17057. // axis (kz) and read every component already permuted into (kx, ky, kz).
  17058. // kx and ky are swapped when the direction's kz component is negative, to
  17059. // preserve the winding order of triangles.
  17060. const adx = Math.abs( dx ), ady = Math.abs( dy ), adz = Math.abs( dz );
  17061. let dkx, dky, dkz;
  17062. let akx, aky, akz, bkx, bky, bkz, ckx, cky, ckz;
  17063. if ( adx >= ady && adx >= adz ) {
  17064. dkz = dx; akz = aox; bkz = box; ckz = cox;
  17065. if ( dx >= 0 ) {
  17066. dkx = dy; dky = dz;
  17067. akx = aoy; aky = aoz; bkx = boy; bky = boz; ckx = coy; cky = coz;
  17068. } else {
  17069. dkx = dz; dky = dy;
  17070. akx = aoz; aky = aoy; bkx = boz; bky = boy; ckx = coz; cky = coy;
  17071. }
  17072. } else if ( ady >= adz ) {
  17073. dkz = dy; akz = aoy; bkz = boy; ckz = coy;
  17074. if ( dy >= 0 ) {
  17075. dkx = dz; dky = dx;
  17076. akx = aoz; aky = aox; bkx = boz; bky = box; ckx = coz; cky = cox;
  17077. } else {
  17078. dkx = dx; dky = dz;
  17079. akx = aox; aky = aoz; bkx = box; bky = boz; ckx = cox; cky = coz;
  17080. }
  17081. } else {
  17082. dkz = dz; akz = aoz; bkz = boz; ckz = coz;
  17083. if ( dz >= 0 ) {
  17084. dkx = dx; dky = dy;
  17085. akx = aox; aky = aoy; bkx = box; bky = boy; ckx = cox; cky = coy;
  17086. } else {
  17087. dkx = dy; dky = dx;
  17088. akx = aoy; aky = aox; bkx = boy; bky = box; ckx = coy; cky = cox;
  17089. }
  17090. }
  17091. // a zero direction has no maximal axis and cannot intersect
  17092. if ( dkz === 0 ) return null;
  17093. // shear constants that align the ray with the +kz axis
  17094. const sx = dkx / dkz, sy = dky / dkz, sz = 1 / dkz;
  17095. // sheared and scaled vertices
  17096. const ax = akx - sx * akz, ay = aky - sy * akz;
  17097. const bx = bkx - sx * bkz, by = bky - sy * bkz;
  17098. const cx = ckx - sx * ckz, cy = cky - sy * ckz;
  17099. // scaled barycentric coordinates (signed edge functions); the shear makes a
  17100. // shared edge evaluate identically for both adjacent triangles, so the ray
  17101. // can never fall between them
  17102. const u = cx * by - cy * bx;
  17103. const v = ax * cy - ay * cx;
  17104. const w = bx * ay - by * ax;
  17105. if ( backfaceCulling ) {
  17106. if ( u < 0 || v < 0 || w < 0 ) return null;
  17107. } else {
  17108. if ( ( u < 0 || v < 0 || w < 0 ) && ( u > 0 || v > 0 || w > 0 ) ) return null;
  17109. }
  17110. const det = u + v + w;
  17111. // ray is co-planar with the triangle
  17112. if ( det === 0 ) return null;
  17113. // scaled hit distance; t = tScaled / det must lie in front of the origin
  17114. const tScaled = sz * ( u * akz + v * bkz + w * ckz );
  17115. if ( det > 0 ? tScaled < 0 : tScaled > 0 ) return null;
  17116. return this.at( tScaled / det, target );
  17117. }
  17118. /**
  17119. * Transforms this ray with the given 4x4 transformation matrix.
  17120. *
  17121. * @param {Matrix4} matrix4 - The transformation matrix.
  17122. * @return {Ray} A reference to this ray.
  17123. */
  17124. applyMatrix4( matrix4 ) {
  17125. this.origin.applyMatrix4( matrix4 );
  17126. this.direction.transformDirection( matrix4 );
  17127. return this;
  17128. }
  17129. /**
  17130. * Returns `true` if this ray is equal with the given one.
  17131. *
  17132. * @param {Ray} ray - The ray to test for equality.
  17133. * @return {boolean} Whether this ray is equal with the given one.
  17134. */
  17135. equals( ray ) {
  17136. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  17137. }
  17138. /**
  17139. * Returns a new ray with copied values from this instance.
  17140. *
  17141. * @return {Ray} A clone of this instance.
  17142. */
  17143. clone() {
  17144. return new this.constructor().copy( this );
  17145. }
  17146. }
  17147. /**
  17148. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  17149. *
  17150. * This material is not affected by lights.
  17151. *
  17152. * @augments Material
  17153. * @demo scenes/material-browser.html#MeshBasicMaterial
  17154. */
  17155. class MeshBasicMaterial extends Material {
  17156. /**
  17157. * Constructs a new mesh basic material.
  17158. *
  17159. * @param {Object} [parameters] - An object with one or more properties
  17160. * defining the material's appearance. Any property of the material
  17161. * (including any property from inherited materials) can be passed
  17162. * in here. Color values can be passed any type of value accepted
  17163. * by {@link Color#set}.
  17164. */
  17165. constructor( parameters ) {
  17166. super();
  17167. /**
  17168. * This flag can be used for type testing.
  17169. *
  17170. * @type {boolean}
  17171. * @readonly
  17172. * @default true
  17173. */
  17174. this.isMeshBasicMaterial = true;
  17175. this.type = 'MeshBasicMaterial';
  17176. /**
  17177. * Color of the material.
  17178. *
  17179. * @type {Color}
  17180. * @default (1,1,1)
  17181. */
  17182. this.color = new Color( 0xffffff ); // diffuse
  17183. /**
  17184. * The color map. May optionally include an alpha channel, typically combined
  17185. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17186. * color is modulated by the diffuse `color`.
  17187. *
  17188. * `map` represents color data, and the texture must be assigned a
  17189. * {@link Texture#colorSpace}. Most `map` textures set
  17190. * `texture.colorSpace = SRGBColorSpace`.
  17191. *
  17192. * @type {?Texture}
  17193. * @default null
  17194. */
  17195. this.map = null;
  17196. /**
  17197. * The light map. Requires a second set of UVs.
  17198. *
  17199. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  17200. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  17201. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  17202. * such as `.exr` or `.hdr`.
  17203. *
  17204. * @type {?Texture}
  17205. * @default null
  17206. */
  17207. this.lightMap = null;
  17208. /**
  17209. * Intensity of the baked light.
  17210. *
  17211. * @type {number}
  17212. * @default 1
  17213. */
  17214. this.lightMapIntensity = 1.0;
  17215. /**
  17216. * The red channel of this texture is used as the ambient occlusion map.
  17217. * Requires a second set of UVs.
  17218. *
  17219. * `aoMap` represents non-color data. Any texture assigned must have
  17220. * `texture.colorSpace = NoColorSpace` (default).
  17221. *
  17222. * @type {?Texture}
  17223. * @default null
  17224. */
  17225. this.aoMap = null;
  17226. /**
  17227. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  17228. * disables ambient occlusion. Where intensity is `1` and the AO map's
  17229. * red channel is also `1`, ambient light is fully occluded on a surface.
  17230. *
  17231. * @type {number}
  17232. * @default 1
  17233. */
  17234. this.aoMapIntensity = 1.0;
  17235. /**
  17236. * Specular map used by the material.
  17237. *
  17238. * `specularMap` represents color data, and the texture must be assigned a
  17239. * {@link Texture#colorSpace}. Most `specularMap` textures set
  17240. * `texture.colorSpace = SRGBColorSpace`.
  17241. *
  17242. * @type {?Texture}
  17243. * @default null
  17244. */
  17245. this.specularMap = null;
  17246. /**
  17247. * The alpha map is a grayscale texture that controls the opacity across the
  17248. * surface (black: fully transparent; white: fully opaque).
  17249. *
  17250. * Only the color of the texture is used, ignoring the alpha channel if one
  17251. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17252. * when sampling this texture due to the extra bit of precision provided for
  17253. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17254. * luminance/alpha textures will also still work as expected.
  17255. *
  17256. * `alphaMap` represents non-color data. Any texture assigned must have
  17257. * `texture.colorSpace = NoColorSpace` (default).
  17258. *
  17259. * @type {?Texture}
  17260. * @default null
  17261. */
  17262. this.alphaMap = null;
  17263. /**
  17264. * The environment map.
  17265. *
  17266. * `envMap` represents luminance data, and the texture must be assigned
  17267. * a {@link Texture#colorSpace}. Most `envMap` textures set
  17268. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  17269. * such as `.exr` or `.hdr`.
  17270. *
  17271. * @type {?Texture}
  17272. * @default null
  17273. */
  17274. this.envMap = null;
  17275. /**
  17276. * The rotation of the environment map in radians.
  17277. *
  17278. * @type {Euler}
  17279. * @default (0,0,0)
  17280. */
  17281. this.envMapRotation = new Euler();
  17282. /**
  17283. * How to combine the result of the surface's color with the environment map, if any.
  17284. *
  17285. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  17286. * blend between the two colors.
  17287. *
  17288. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  17289. * @default MultiplyOperation
  17290. */
  17291. this.combine = MultiplyOperation;
  17292. /**
  17293. * How much the environment map affects the surface.
  17294. * The valid range is between `0` (no reflections) and `1` (full reflections).
  17295. *
  17296. * @type {number}
  17297. * @default 1
  17298. */
  17299. this.reflectivity = 1;
  17300. /**
  17301. * The index of refraction (IOR) of air (approximately 1) divided by the
  17302. * index of refraction of the material. It is used with environment mapping
  17303. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  17304. * The refraction ratio should not exceed `1`.
  17305. *
  17306. * @type {number}
  17307. * @default 0.98
  17308. */
  17309. this.refractionRatio = 0.98;
  17310. /**
  17311. * Renders the geometry as a wireframe.
  17312. *
  17313. * @type {boolean}
  17314. * @default false
  17315. */
  17316. this.wireframe = false;
  17317. /**
  17318. * Controls the thickness of the wireframe.
  17319. *
  17320. * Can only be used with {@link SVGRenderer}.
  17321. *
  17322. * @type {number}
  17323. * @default 1
  17324. */
  17325. this.wireframeLinewidth = 1;
  17326. /**
  17327. * Defines appearance of wireframe ends.
  17328. *
  17329. * Can only be used with {@link SVGRenderer}.
  17330. *
  17331. * @type {('round'|'bevel'|'miter')}
  17332. * @default 'round'
  17333. */
  17334. this.wireframeLinecap = 'round';
  17335. /**
  17336. * Defines appearance of wireframe joints.
  17337. *
  17338. * Can only be used with {@link SVGRenderer}.
  17339. *
  17340. * @type {('round'|'bevel'|'miter')}
  17341. * @default 'round'
  17342. */
  17343. this.wireframeLinejoin = 'round';
  17344. /**
  17345. * Whether the material is affected by fog or not.
  17346. *
  17347. * @type {boolean}
  17348. * @default true
  17349. */
  17350. this.fog = true;
  17351. this.setValues( parameters );
  17352. }
  17353. copy( source ) {
  17354. super.copy( source );
  17355. this.color.copy( source.color );
  17356. this.map = source.map;
  17357. this.lightMap = source.lightMap;
  17358. this.lightMapIntensity = source.lightMapIntensity;
  17359. this.aoMap = source.aoMap;
  17360. this.aoMapIntensity = source.aoMapIntensity;
  17361. this.specularMap = source.specularMap;
  17362. this.alphaMap = source.alphaMap;
  17363. this.envMap = source.envMap;
  17364. this.envMapRotation.copy( source.envMapRotation );
  17365. this.combine = source.combine;
  17366. this.reflectivity = source.reflectivity;
  17367. this.refractionRatio = source.refractionRatio;
  17368. this.wireframe = source.wireframe;
  17369. this.wireframeLinewidth = source.wireframeLinewidth;
  17370. this.wireframeLinecap = source.wireframeLinecap;
  17371. this.wireframeLinejoin = source.wireframeLinejoin;
  17372. this.fog = source.fog;
  17373. return this;
  17374. }
  17375. }
  17376. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  17377. const _ray$3 = /*@__PURE__*/ new Ray();
  17378. const _sphere$6 = /*@__PURE__*/ new Sphere();
  17379. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  17380. const _vA = /*@__PURE__*/ new Vector3();
  17381. const _vB = /*@__PURE__*/ new Vector3();
  17382. const _vC = /*@__PURE__*/ new Vector3();
  17383. const _tempA = /*@__PURE__*/ new Vector3();
  17384. const _morphA = /*@__PURE__*/ new Vector3();
  17385. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  17386. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  17387. /**
  17388. * Class representing triangular polygon mesh based objects.
  17389. *
  17390. * ```js
  17391. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  17392. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17393. * const mesh = new THREE.Mesh( geometry, material );
  17394. * scene.add( mesh );
  17395. * ```
  17396. *
  17397. * @augments Object3D
  17398. */
  17399. class Mesh extends Object3D {
  17400. /**
  17401. * Constructs a new mesh.
  17402. *
  17403. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17404. * @param {Material|Array<Material>} [material] - The mesh material.
  17405. */
  17406. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  17407. super();
  17408. /**
  17409. * This flag can be used for type testing.
  17410. *
  17411. * @type {boolean}
  17412. * @readonly
  17413. * @default true
  17414. */
  17415. this.isMesh = true;
  17416. this.type = 'Mesh';
  17417. /**
  17418. * The mesh geometry.
  17419. *
  17420. * @type {BufferGeometry}
  17421. */
  17422. this.geometry = geometry;
  17423. /**
  17424. * The mesh material.
  17425. *
  17426. * @type {Material|Array<Material>}
  17427. * @default MeshBasicMaterial
  17428. */
  17429. this.material = material;
  17430. /**
  17431. * A dictionary representing the morph targets in the geometry. The key is the
  17432. * morph targets name, the value its attribute index. This member is `undefined`
  17433. * by default and only set when morph targets are detected in the geometry.
  17434. *
  17435. * @type {Object<string,number>|undefined}
  17436. * @default undefined
  17437. */
  17438. this.morphTargetDictionary = undefined;
  17439. /**
  17440. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  17441. * is applied. This member is `undefined` by default and only set when morph targets are
  17442. * detected in the geometry.
  17443. *
  17444. * @type {Array<number>|undefined}
  17445. * @default undefined
  17446. */
  17447. this.morphTargetInfluences = undefined;
  17448. /**
  17449. * The number of instances of this mesh.
  17450. * Can only be used with {@link WebGPURenderer}.
  17451. *
  17452. * @type {number}
  17453. * @default 1
  17454. */
  17455. this.count = 1;
  17456. this.updateMorphTargets();
  17457. }
  17458. copy( source, recursive ) {
  17459. super.copy( source, recursive );
  17460. if ( source.morphTargetInfluences !== undefined ) {
  17461. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  17462. }
  17463. if ( source.morphTargetDictionary !== undefined ) {
  17464. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  17465. }
  17466. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  17467. this.geometry = source.geometry;
  17468. return this;
  17469. }
  17470. /**
  17471. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  17472. * to make sure existing morph targets can influence this 3D object.
  17473. */
  17474. updateMorphTargets() {
  17475. const geometry = this.geometry;
  17476. const morphAttributes = geometry.morphAttributes;
  17477. const keys = Object.keys( morphAttributes );
  17478. if ( keys.length > 0 ) {
  17479. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17480. if ( morphAttribute !== undefined ) {
  17481. this.morphTargetInfluences = [];
  17482. this.morphTargetDictionary = {};
  17483. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17484. const name = morphAttribute[ m ].name || String( m );
  17485. this.morphTargetInfluences.push( 0 );
  17486. this.morphTargetDictionary[ name ] = m;
  17487. }
  17488. }
  17489. }
  17490. }
  17491. /**
  17492. * Returns the local-space position of the vertex at the given index, taking into
  17493. * account the current animation state of both morph targets and skinning.
  17494. *
  17495. * @param {number} index - The vertex index.
  17496. * @param {Vector3} target - The target object that is used to store the method's result.
  17497. * @return {Vector3} The vertex position in local space.
  17498. */
  17499. getVertexPosition( index, target ) {
  17500. const geometry = this.geometry;
  17501. const position = geometry.attributes.position;
  17502. const morphPosition = geometry.morphAttributes.position;
  17503. const morphTargetsRelative = geometry.morphTargetsRelative;
  17504. target.fromBufferAttribute( position, index );
  17505. const morphInfluences = this.morphTargetInfluences;
  17506. if ( morphPosition && morphInfluences ) {
  17507. _morphA.set( 0, 0, 0 );
  17508. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  17509. const influence = morphInfluences[ i ];
  17510. const morphAttribute = morphPosition[ i ];
  17511. if ( influence === 0 ) continue;
  17512. _tempA.fromBufferAttribute( morphAttribute, index );
  17513. if ( morphTargetsRelative ) {
  17514. _morphA.addScaledVector( _tempA, influence );
  17515. } else {
  17516. _morphA.addScaledVector( _tempA.sub( target ), influence );
  17517. }
  17518. }
  17519. target.add( _morphA );
  17520. }
  17521. return target;
  17522. }
  17523. /**
  17524. * Computes intersection points between a casted ray and this line.
  17525. *
  17526. * @param {Raycaster} raycaster - The raycaster.
  17527. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17528. */
  17529. raycast( raycaster, intersects ) {
  17530. const geometry = this.geometry;
  17531. const material = this.material;
  17532. const matrixWorld = this.matrixWorld;
  17533. if ( material === undefined ) return;
  17534. // test with bounding sphere in world space
  17535. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17536. _sphere$6.copy( geometry.boundingSphere );
  17537. _sphere$6.applyMatrix4( matrixWorld );
  17538. // check distance from ray origin to bounding sphere
  17539. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  17540. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  17541. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  17542. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  17543. }
  17544. // convert ray to local space of mesh
  17545. _inverseMatrix$3.copy( matrixWorld ).invert();
  17546. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  17547. // test with bounding box in local space
  17548. if ( geometry.boundingBox !== null ) {
  17549. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  17550. }
  17551. // test for intersections with geometry
  17552. this._computeIntersections( raycaster, intersects, _ray$3 );
  17553. }
  17554. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  17555. let intersection;
  17556. const geometry = this.geometry;
  17557. const material = this.material;
  17558. const index = geometry.index;
  17559. const position = geometry.attributes.position;
  17560. const uv = geometry.attributes.uv;
  17561. const uv1 = geometry.attributes.uv1;
  17562. const normal = geometry.attributes.normal;
  17563. const groups = geometry.groups;
  17564. const drawRange = geometry.drawRange;
  17565. if ( index !== null ) {
  17566. // indexed buffer geometry
  17567. if ( Array.isArray( material ) ) {
  17568. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17569. const group = groups[ i ];
  17570. const groupMaterial = material[ group.materialIndex ];
  17571. const start = Math.max( group.start, drawRange.start );
  17572. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17573. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17574. const a = index.getX( j );
  17575. const b = index.getX( j + 1 );
  17576. const c = index.getX( j + 2 );
  17577. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17578. if ( intersection ) {
  17579. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  17580. intersection.face.materialIndex = group.materialIndex;
  17581. intersects.push( intersection );
  17582. }
  17583. }
  17584. }
  17585. } else {
  17586. const start = Math.max( 0, drawRange.start );
  17587. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17588. for ( let i = start, il = end; i < il; i += 3 ) {
  17589. const a = index.getX( i );
  17590. const b = index.getX( i + 1 );
  17591. const c = index.getX( i + 2 );
  17592. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17593. if ( intersection ) {
  17594. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  17595. intersects.push( intersection );
  17596. }
  17597. }
  17598. }
  17599. } else if ( position !== undefined ) {
  17600. // non-indexed buffer geometry
  17601. if ( Array.isArray( material ) ) {
  17602. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17603. const group = groups[ i ];
  17604. const groupMaterial = material[ group.materialIndex ];
  17605. const start = Math.max( group.start, drawRange.start );
  17606. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17607. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17608. const a = j;
  17609. const b = j + 1;
  17610. const c = j + 2;
  17611. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17612. if ( intersection ) {
  17613. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  17614. intersection.face.materialIndex = group.materialIndex;
  17615. intersects.push( intersection );
  17616. }
  17617. }
  17618. }
  17619. } else {
  17620. const start = Math.max( 0, drawRange.start );
  17621. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  17622. for ( let i = start, il = end; i < il; i += 3 ) {
  17623. const a = i;
  17624. const b = i + 1;
  17625. const c = i + 2;
  17626. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17627. if ( intersection ) {
  17628. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  17629. intersects.push( intersection );
  17630. }
  17631. }
  17632. }
  17633. }
  17634. }
  17635. }
  17636. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  17637. let intersect;
  17638. if ( material.side === BackSide ) {
  17639. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  17640. } else {
  17641. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  17642. }
  17643. if ( intersect === null ) return null;
  17644. _intersectionPointWorld.copy( point );
  17645. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  17646. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  17647. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  17648. return {
  17649. distance: distance,
  17650. point: _intersectionPointWorld.clone(),
  17651. object: object
  17652. };
  17653. }
  17654. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  17655. object.getVertexPosition( a, _vA );
  17656. object.getVertexPosition( b, _vB );
  17657. object.getVertexPosition( c, _vC );
  17658. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  17659. if ( intersection ) {
  17660. const barycoord = new Vector3();
  17661. Triangle.getBarycoord( _intersectionPoint, _vA, _vB, _vC, barycoord );
  17662. if ( uv ) {
  17663. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  17664. }
  17665. if ( uv1 ) {
  17666. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  17667. }
  17668. if ( normal ) {
  17669. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  17670. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  17671. intersection.normal.multiplyScalar( -1 );
  17672. }
  17673. }
  17674. const face = {
  17675. a: a,
  17676. b: b,
  17677. c: c,
  17678. normal: new Vector3(),
  17679. materialIndex: 0
  17680. };
  17681. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  17682. intersection.face = face;
  17683. intersection.barycoord = barycoord;
  17684. }
  17685. return intersection;
  17686. }
  17687. const _baseVector = /*@__PURE__*/ new Vector4();
  17688. const _skinIndex = /*@__PURE__*/ new Vector4();
  17689. const _skinWeight = /*@__PURE__*/ new Vector4();
  17690. const _vector4 = /*@__PURE__*/ new Vector4();
  17691. const _matrix4 = /*@__PURE__*/ new Matrix4();
  17692. const _vertex = /*@__PURE__*/ new Vector3();
  17693. const _sphere$5 = /*@__PURE__*/ new Sphere();
  17694. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  17695. const _ray$2 = /*@__PURE__*/ new Ray();
  17696. /**
  17697. * A mesh that has a {@link Skeleton} that can then be used to animate the
  17698. * vertices of the geometry with skinning/skeleton animation.
  17699. *
  17700. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  17701. * as buffer attributes in its geometry. These attribute define which bones affect a single
  17702. * vertex to a certain extend.
  17703. *
  17704. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  17705. * or {@link FBXLoader } import respective models.
  17706. *
  17707. * @augments Mesh
  17708. * @demo scenes/bones-browser.html
  17709. */
  17710. class SkinnedMesh extends Mesh {
  17711. /**
  17712. * Constructs a new skinned mesh.
  17713. *
  17714. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17715. * @param {Material|Array<Material>} [material] - The mesh material.
  17716. */
  17717. constructor( geometry, material ) {
  17718. super( geometry, material );
  17719. /**
  17720. * This flag can be used for type testing.
  17721. *
  17722. * @type {boolean}
  17723. * @readonly
  17724. * @default true
  17725. */
  17726. this.isSkinnedMesh = true;
  17727. this.type = 'SkinnedMesh';
  17728. /**
  17729. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  17730. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  17731. * across multiple skinned meshes.
  17732. *
  17733. * @type {(AttachedBindMode|DetachedBindMode)}
  17734. * @default AttachedBindMode
  17735. */
  17736. this.bindMode = AttachedBindMode;
  17737. /**
  17738. * The base matrix that is used for the bound bone transforms.
  17739. *
  17740. * @type {Matrix4}
  17741. */
  17742. this.bindMatrix = new Matrix4();
  17743. /**
  17744. * The base matrix that is used for resetting the bound bone transforms.
  17745. *
  17746. * @type {Matrix4}
  17747. */
  17748. this.bindMatrixInverse = new Matrix4();
  17749. /**
  17750. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  17751. *
  17752. * @type {?Box3}
  17753. * @default null
  17754. */
  17755. this.boundingBox = null;
  17756. /**
  17757. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  17758. *
  17759. * @type {?Sphere}
  17760. * @default null
  17761. */
  17762. this.boundingSphere = null;
  17763. }
  17764. /**
  17765. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  17766. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  17767. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  17768. * the current animation state.
  17769. */
  17770. computeBoundingBox() {
  17771. const geometry = this.geometry;
  17772. if ( this.boundingBox === null ) {
  17773. this.boundingBox = new Box3();
  17774. }
  17775. this.boundingBox.makeEmpty();
  17776. const positionAttribute = geometry.getAttribute( 'position' );
  17777. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17778. this.getVertexPosition( i, _vertex );
  17779. this.boundingBox.expandByPoint( _vertex );
  17780. }
  17781. }
  17782. /**
  17783. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  17784. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  17785. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  17786. * per frame in order to reflect the current animation state.
  17787. */
  17788. computeBoundingSphere() {
  17789. const geometry = this.geometry;
  17790. if ( this.boundingSphere === null ) {
  17791. this.boundingSphere = new Sphere();
  17792. }
  17793. this.boundingSphere.makeEmpty();
  17794. const positionAttribute = geometry.getAttribute( 'position' );
  17795. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17796. this.getVertexPosition( i, _vertex );
  17797. this.boundingSphere.expandByPoint( _vertex );
  17798. }
  17799. }
  17800. copy( source, recursive ) {
  17801. super.copy( source, recursive );
  17802. this.bindMode = source.bindMode;
  17803. this.bindMatrix.copy( source.bindMatrix );
  17804. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17805. this.skeleton = source.skeleton;
  17806. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  17807. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  17808. return this;
  17809. }
  17810. raycast( raycaster, intersects ) {
  17811. const material = this.material;
  17812. const matrixWorld = this.matrixWorld;
  17813. if ( material === undefined ) return;
  17814. // test with bounding sphere in world space
  17815. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  17816. _sphere$5.copy( this.boundingSphere );
  17817. _sphere$5.applyMatrix4( matrixWorld );
  17818. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  17819. // convert ray to local space of skinned mesh
  17820. _inverseMatrix$2.copy( matrixWorld ).invert();
  17821. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  17822. // test with bounding box in local space
  17823. if ( this.boundingBox !== null ) {
  17824. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  17825. }
  17826. // test for intersections with geometry
  17827. this._computeIntersections( raycaster, intersects, _ray$2 );
  17828. }
  17829. getVertexPosition( index, target ) {
  17830. super.getVertexPosition( index, target );
  17831. this.applyBoneTransform( index, target );
  17832. return target;
  17833. }
  17834. /**
  17835. * Binds the given skeleton to the skinned mesh.
  17836. *
  17837. * @param {Skeleton} skeleton - The skeleton to bind.
  17838. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  17839. * the skinned mesh's world matrix will be used instead.
  17840. */
  17841. bind( skeleton, bindMatrix ) {
  17842. this.skeleton = skeleton;
  17843. if ( bindMatrix === undefined ) {
  17844. this.updateMatrixWorld( true );
  17845. this.skeleton.calculateInverses();
  17846. bindMatrix = this.matrixWorld;
  17847. }
  17848. this.bindMatrix.copy( bindMatrix );
  17849. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17850. }
  17851. /**
  17852. * This method sets the skinned mesh in the rest pose).
  17853. */
  17854. pose() {
  17855. this.skeleton.pose();
  17856. }
  17857. /**
  17858. * Normalizes the skin weights which are defined as a buffer attribute
  17859. * in the skinned mesh's geometry.
  17860. */
  17861. normalizeSkinWeights() {
  17862. const vector = new Vector4();
  17863. const skinWeight = this.geometry.attributes.skinWeight;
  17864. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17865. vector.fromBufferAttribute( skinWeight, i );
  17866. const scale = 1.0 / vector.manhattanLength();
  17867. if ( scale !== Infinity ) {
  17868. vector.multiplyScalar( scale );
  17869. } else {
  17870. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17871. }
  17872. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17873. }
  17874. }
  17875. updateMatrixWorld( force ) {
  17876. super.updateMatrixWorld( force );
  17877. if ( this.bindMode === AttachedBindMode ) {
  17878. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17879. } else if ( this.bindMode === DetachedBindMode ) {
  17880. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17881. } else {
  17882. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17883. }
  17884. }
  17885. /**
  17886. * Applies the bone transform associated with the given index to the given
  17887. * vector. Can be used to transform positions or direction vectors by providing
  17888. * a Vector4 with 1 or 0 in the w component respectively. Returns the updated vector.
  17889. *
  17890. * @param {number} index - The vertex index.
  17891. * @param {Vector3|Vector4} target - The target object that is used to store the method's result.
  17892. * @return {Vector3|Vector4} The updated vertex attribute data.
  17893. */
  17894. applyBoneTransform( index, target ) {
  17895. const skeleton = this.skeleton;
  17896. const geometry = this.geometry;
  17897. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17898. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17899. if ( target.isVector4 ) {
  17900. _baseVector.copy( target );
  17901. target.set( 0, 0, 0, 0 );
  17902. } else {
  17903. _baseVector.set( ...target, 1 );
  17904. target.set( 0, 0, 0 );
  17905. }
  17906. _baseVector.applyMatrix4( this.bindMatrix );
  17907. for ( let i = 0; i < 4; i ++ ) {
  17908. const weight = _skinWeight.getComponent( i );
  17909. if ( weight !== 0 ) {
  17910. const boneIndex = _skinIndex.getComponent( i );
  17911. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17912. target.addScaledVector( _vector4.copy( _baseVector ).applyMatrix4( _matrix4 ), weight );
  17913. }
  17914. }
  17915. if ( target.isVector4 ) {
  17916. // ensure the homogenous coordinate remains unchanged after vector operations
  17917. target.w = _baseVector.w;
  17918. }
  17919. return target.applyMatrix4( this.bindMatrixInverse );
  17920. }
  17921. }
  17922. /**
  17923. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  17924. * the {@link SkinnedMesh}.
  17925. *
  17926. * ```js
  17927. * const root = new THREE.Bone();
  17928. * const child = new THREE.Bone();
  17929. *
  17930. * root.add( child );
  17931. * child.position.y = 5;
  17932. * ```
  17933. *
  17934. * @augments Object3D
  17935. */
  17936. class Bone extends Object3D {
  17937. /**
  17938. * Constructs a new bone.
  17939. */
  17940. constructor() {
  17941. super();
  17942. /**
  17943. * This flag can be used for type testing.
  17944. *
  17945. * @type {boolean}
  17946. * @readonly
  17947. * @default true
  17948. */
  17949. this.isBone = true;
  17950. this.type = 'Bone';
  17951. }
  17952. }
  17953. /**
  17954. * Creates a texture directly from raw buffer data.
  17955. *
  17956. * The interpretation of the data depends on type and format: If the type is
  17957. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  17958. * texel data. If the format is `RGBAFormat`, data needs four values for
  17959. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  17960. *
  17961. * @augments Texture
  17962. */
  17963. class DataTexture extends Texture {
  17964. /**
  17965. * Constructs a new data texture.
  17966. *
  17967. * @param {?TypedArray} [data=null] - The buffer data.
  17968. * @param {number} [width=1] - The width of the texture.
  17969. * @param {number} [height=1] - The height of the texture.
  17970. * @param {number} [format=RGBAFormat] - The texture format.
  17971. * @param {number} [type=UnsignedByteType] - The texture type.
  17972. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  17973. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  17974. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  17975. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  17976. * @param {number} [minFilter=NearestFilter] - The min filter value.
  17977. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  17978. * @param {string} [colorSpace=NoColorSpace] - The color space.
  17979. */
  17980. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  17981. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  17982. /**
  17983. * This flag can be used for type testing.
  17984. *
  17985. * @type {boolean}
  17986. * @readonly
  17987. * @default true
  17988. */
  17989. this.isDataTexture = true;
  17990. /**
  17991. * The image definition of a data texture.
  17992. *
  17993. * @type {{data:TypedArray,width:number,height:number}}
  17994. */
  17995. this.image = { data: data, width: width, height: height };
  17996. /**
  17997. * Whether to generate mipmaps (if possible) for a texture.
  17998. *
  17999. * Overwritten and set to `false` by default.
  18000. *
  18001. * @type {boolean}
  18002. * @default false
  18003. */
  18004. this.generateMipmaps = false;
  18005. /**
  18006. * If set to `true`, the texture is flipped along the vertical axis when
  18007. * uploaded to the GPU.
  18008. *
  18009. * Overwritten and set to `false` by default.
  18010. *
  18011. * @type {boolean}
  18012. * @default false
  18013. */
  18014. this.flipY = false;
  18015. /**
  18016. * Specifies the alignment requirements for the start of each pixel row in memory.
  18017. *
  18018. * Overwritten and set to `1` by default.
  18019. *
  18020. * @type {boolean}
  18021. * @default 1
  18022. */
  18023. this.unpackAlignment = 1;
  18024. }
  18025. }
  18026. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18027. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18028. /**
  18029. * Class for representing the armatures in `three.js`. The skeleton
  18030. * is defined by a hierarchy of bones.
  18031. *
  18032. * ```js
  18033. * const bones = [];
  18034. *
  18035. * const shoulder = new THREE.Bone();
  18036. * const elbow = new THREE.Bone();
  18037. * const hand = new THREE.Bone();
  18038. *
  18039. * shoulder.add( elbow );
  18040. * elbow.add( hand );
  18041. *
  18042. * bones.push( shoulder , elbow, hand);
  18043. *
  18044. * shoulder.position.y = -5;
  18045. * elbow.position.y = 0;
  18046. * hand.position.y = 5;
  18047. *
  18048. * const armSkeleton = new THREE.Skeleton( bones );
  18049. * ```
  18050. */
  18051. class Skeleton {
  18052. /**
  18053. * Constructs a new skeleton.
  18054. *
  18055. * @param {Array<Bone>} [bones] - An array of bones.
  18056. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18057. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18058. */
  18059. constructor( bones = [], boneInverses = [] ) {
  18060. this.uuid = generateUUID();
  18061. /**
  18062. * An array of bones defining the skeleton.
  18063. *
  18064. * @type {Array<Bone>}
  18065. */
  18066. this.bones = bones.slice( 0 );
  18067. /**
  18068. * An array of bone inverse matrices.
  18069. *
  18070. * @type {Array<Matrix4>}
  18071. */
  18072. this.boneInverses = boneInverses;
  18073. /**
  18074. * An array buffer holding the bone data.
  18075. * Input data for {@link Skeleton#boneTexture}.
  18076. *
  18077. * @type {?Float32Array}
  18078. * @default null
  18079. */
  18080. this.boneMatrices = null;
  18081. /**
  18082. * A texture holding the bone data for use
  18083. * in the vertex shader.
  18084. *
  18085. * @type {?DataTexture}
  18086. * @default null
  18087. */
  18088. this.boneTexture = null;
  18089. this.init();
  18090. }
  18091. /**
  18092. * Initializes the skeleton. This method gets automatically called by the constructor
  18093. * but depending on how the skeleton is created it might be necessary to call this method
  18094. * manually.
  18095. */
  18096. init() {
  18097. const bones = this.bones;
  18098. const boneInverses = this.boneInverses;
  18099. this.boneMatrices = new Float32Array( bones.length * 16 );
  18100. // calculate inverse bone matrices if necessary
  18101. if ( boneInverses.length === 0 ) {
  18102. this.calculateInverses();
  18103. } else {
  18104. // handle special case
  18105. if ( bones.length !== boneInverses.length ) {
  18106. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18107. this.boneInverses = [];
  18108. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18109. this.boneInverses.push( new Matrix4() );
  18110. }
  18111. }
  18112. }
  18113. }
  18114. /**
  18115. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18116. * and fills it with new matrices.
  18117. */
  18118. calculateInverses() {
  18119. this.boneInverses.length = 0;
  18120. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18121. const inverse = new Matrix4();
  18122. if ( this.bones[ i ] ) {
  18123. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18124. }
  18125. this.boneInverses.push( inverse );
  18126. }
  18127. }
  18128. /**
  18129. * Resets the skeleton to the base pose.
  18130. */
  18131. pose() {
  18132. // recover the bind-time world matrices
  18133. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18134. const bone = this.bones[ i ];
  18135. if ( bone ) {
  18136. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18137. }
  18138. }
  18139. // compute the local matrices, positions, rotations and scales
  18140. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18141. const bone = this.bones[ i ];
  18142. if ( bone ) {
  18143. if ( bone.parent && bone.parent.isBone ) {
  18144. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18145. bone.matrix.multiply( bone.matrixWorld );
  18146. } else {
  18147. bone.matrix.copy( bone.matrixWorld );
  18148. }
  18149. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18150. }
  18151. }
  18152. }
  18153. /**
  18154. * Resets the skeleton to the base pose.
  18155. */
  18156. update() {
  18157. const bones = this.bones;
  18158. const boneInverses = this.boneInverses;
  18159. const boneMatrices = this.boneMatrices;
  18160. const boneTexture = this.boneTexture;
  18161. // flatten bone matrices to array
  18162. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18163. // compute the offset between the current and the original transform
  18164. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18165. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18166. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18167. }
  18168. if ( boneTexture !== null ) {
  18169. boneTexture.needsUpdate = true;
  18170. }
  18171. }
  18172. /**
  18173. * Returns a new skeleton with copied values from this instance.
  18174. *
  18175. * @return {Skeleton} A clone of this instance.
  18176. */
  18177. clone() {
  18178. return new Skeleton( this.bones, this.boneInverses );
  18179. }
  18180. /**
  18181. * Computes a data texture for passing bone data to the vertex shader.
  18182. *
  18183. * @return {Skeleton} A reference of this instance.
  18184. */
  18185. computeBoneTexture() {
  18186. // layout (1 matrix = 4 pixels)
  18187. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18188. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18189. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18190. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18191. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18192. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18193. size = Math.ceil( size / 4 ) * 4;
  18194. size = Math.max( size, 4 );
  18195. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18196. boneMatrices.set( this.boneMatrices ); // copy current values
  18197. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18198. boneTexture.needsUpdate = true;
  18199. this.boneMatrices = boneMatrices;
  18200. this.boneTexture = boneTexture;
  18201. return this;
  18202. }
  18203. /**
  18204. * Searches through the skeleton's bone array and returns the first with a
  18205. * matching name.
  18206. *
  18207. * @param {string} name - The name of the bone.
  18208. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18209. */
  18210. getBoneByName( name ) {
  18211. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18212. const bone = this.bones[ i ];
  18213. if ( bone.name === name ) {
  18214. return bone;
  18215. }
  18216. }
  18217. return undefined;
  18218. }
  18219. /**
  18220. * Frees the GPU-related resources allocated by this instance. Call this
  18221. * method whenever this instance is no longer used in your app.
  18222. */
  18223. dispose( ) {
  18224. if ( this.boneTexture !== null ) {
  18225. this.boneTexture.dispose();
  18226. this.boneTexture = null;
  18227. }
  18228. }
  18229. /**
  18230. * Setups the skeleton by the given JSON and bones.
  18231. *
  18232. * @param {Object} json - The skeleton as serialized JSON.
  18233. * @param {Object<string, Bone>} bones - An array of bones.
  18234. * @return {Skeleton} A reference of this instance.
  18235. */
  18236. fromJSON( json, bones ) {
  18237. this.uuid = json.uuid;
  18238. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18239. const uuid = json.bones[ i ];
  18240. let bone = bones[ uuid ];
  18241. if ( bone === undefined ) {
  18242. warn( 'Skeleton: No bone found with UUID:', uuid );
  18243. bone = new Bone();
  18244. }
  18245. this.bones.push( bone );
  18246. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18247. }
  18248. this.init();
  18249. return this;
  18250. }
  18251. /**
  18252. * Serializes the skeleton into JSON.
  18253. *
  18254. * @return {Object} A JSON object representing the serialized skeleton.
  18255. * @see {@link ObjectLoader#parse}
  18256. */
  18257. toJSON() {
  18258. const data = {
  18259. metadata: {
  18260. version: 4.7,
  18261. type: 'Skeleton',
  18262. generator: 'Skeleton.toJSON'
  18263. },
  18264. bones: [],
  18265. boneInverses: []
  18266. };
  18267. data.uuid = this.uuid;
  18268. const bones = this.bones;
  18269. const boneInverses = this.boneInverses;
  18270. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18271. const bone = bones[ i ];
  18272. data.bones.push( bone.uuid );
  18273. const boneInverse = boneInverses[ i ];
  18274. data.boneInverses.push( boneInverse.toArray() );
  18275. }
  18276. return data;
  18277. }
  18278. }
  18279. /**
  18280. * An instanced version of a buffer attribute.
  18281. *
  18282. * @augments BufferAttribute
  18283. */
  18284. class InstancedBufferAttribute extends BufferAttribute {
  18285. /**
  18286. * Constructs a new instanced buffer attribute.
  18287. *
  18288. * @param {TypedArray} array - The array holding the attribute data.
  18289. * @param {number} itemSize - The item size.
  18290. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18291. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18292. */
  18293. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18294. super( array, itemSize, normalized );
  18295. /**
  18296. * This flag can be used for type testing.
  18297. *
  18298. * @type {boolean}
  18299. * @readonly
  18300. * @default true
  18301. */
  18302. this.isInstancedBufferAttribute = true;
  18303. /**
  18304. * Defines how often a value of this buffer attribute should be repeated. A
  18305. * value of one means that each value of the instanced attribute is used for
  18306. * a single instance. A value of two means that each value is used for two
  18307. * consecutive instances (and so on).
  18308. *
  18309. * @type {number}
  18310. * @default 1
  18311. */
  18312. this.meshPerAttribute = meshPerAttribute;
  18313. }
  18314. copy( source ) {
  18315. super.copy( source );
  18316. this.meshPerAttribute = source.meshPerAttribute;
  18317. return this;
  18318. }
  18319. toJSON() {
  18320. const data = super.toJSON();
  18321. data.meshPerAttribute = this.meshPerAttribute;
  18322. data.isInstancedBufferAttribute = true;
  18323. return data;
  18324. }
  18325. }
  18326. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18327. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18328. const _instanceIntersects = [];
  18329. const _box3 = /*@__PURE__*/ new Box3();
  18330. const _identity = /*@__PURE__*/ new Matrix4();
  18331. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18332. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18333. /**
  18334. * A special version of a mesh with instanced rendering support. Use
  18335. * this class if you have to render a large number of objects with the same
  18336. * geometry and material(s) but with different world transformations. The usage
  18337. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18338. * improve the overall rendering performance in your application.
  18339. *
  18340. * @augments Mesh
  18341. */
  18342. class InstancedMesh extends Mesh {
  18343. /**
  18344. * Constructs a new instanced mesh.
  18345. *
  18346. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18347. * @param {Material|Array<Material>} [material] - The mesh material.
  18348. * @param {number} count - The number of instances.
  18349. */
  18350. constructor( geometry, material, count ) {
  18351. super( geometry, material );
  18352. /**
  18353. * This flag can be used for type testing.
  18354. *
  18355. * @type {boolean}
  18356. * @readonly
  18357. * @default true
  18358. */
  18359. this.isInstancedMesh = true;
  18360. /**
  18361. * Represents the local transformation of all instances. You have to set its
  18362. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18363. * via {@link InstancedMesh#setMatrixAt}.
  18364. *
  18365. * @type {InstancedBufferAttribute}
  18366. */
  18367. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18368. /**
  18369. * Represents the color of all instances. You have to set its
  18370. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18371. * via {@link InstancedMesh#setColorAt}.
  18372. *
  18373. * @type {?InstancedBufferAttribute}
  18374. * @default null
  18375. */
  18376. this.instanceColor = null;
  18377. /**
  18378. * Represents the morph target weights of all instances. You have to set its
  18379. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18380. * via {@link InstancedMesh#setMorphAt}.
  18381. *
  18382. * @type {?DataTexture}
  18383. * @default null
  18384. */
  18385. this.morphTexture = null;
  18386. /**
  18387. * The number of instances.
  18388. *
  18389. * @type {number}
  18390. */
  18391. this.count = count;
  18392. /**
  18393. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18394. *
  18395. * @type {?Box3}
  18396. * @default null
  18397. */
  18398. this.boundingBox = null;
  18399. /**
  18400. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18401. *
  18402. * @type {?Sphere}
  18403. * @default null
  18404. */
  18405. this.boundingSphere = null;
  18406. for ( let i = 0; i < count; i ++ ) {
  18407. this.setMatrixAt( i, _identity );
  18408. }
  18409. }
  18410. /**
  18411. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18412. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18413. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18414. */
  18415. computeBoundingBox() {
  18416. const geometry = this.geometry;
  18417. const count = this.count;
  18418. if ( this.boundingBox === null ) {
  18419. this.boundingBox = new Box3();
  18420. }
  18421. if ( geometry.boundingBox === null ) {
  18422. geometry.computeBoundingBox();
  18423. }
  18424. this.boundingBox.makeEmpty();
  18425. for ( let i = 0; i < count; i ++ ) {
  18426. this.getMatrixAt( i, _instanceLocalMatrix );
  18427. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18428. this.boundingBox.union( _box3 );
  18429. }
  18430. }
  18431. /**
  18432. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18433. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18434. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18435. */
  18436. computeBoundingSphere() {
  18437. const geometry = this.geometry;
  18438. const count = this.count;
  18439. if ( this.boundingSphere === null ) {
  18440. this.boundingSphere = new Sphere();
  18441. }
  18442. if ( geometry.boundingSphere === null ) {
  18443. geometry.computeBoundingSphere();
  18444. }
  18445. this.boundingSphere.makeEmpty();
  18446. for ( let i = 0; i < count; i ++ ) {
  18447. this.getMatrixAt( i, _instanceLocalMatrix );
  18448. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18449. this.boundingSphere.union( _sphere$4 );
  18450. }
  18451. }
  18452. copy( source, recursive ) {
  18453. super.copy( source, recursive );
  18454. this.instanceMatrix.copy( source.instanceMatrix );
  18455. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18456. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18457. this.count = source.count;
  18458. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18459. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18460. return this;
  18461. }
  18462. /**
  18463. * Gets the color of the defined instance.
  18464. *
  18465. * @param {number} index - The instance index.
  18466. * @param {Color} color - The target object that is used to store the method's result.
  18467. * @return {Color} A reference to the target color.
  18468. */
  18469. getColorAt( index, color ) {
  18470. if ( this.instanceColor === null ) {
  18471. return color.setRGB( 1, 1, 1 );
  18472. } else {
  18473. return color.fromArray( this.instanceColor.array, index * 3 );
  18474. }
  18475. }
  18476. /**
  18477. * Gets the local transformation matrix of the defined instance.
  18478. *
  18479. * @param {number} index - The instance index.
  18480. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18481. * @return {Matrix4} A reference to the target matrix.
  18482. */
  18483. getMatrixAt( index, matrix ) {
  18484. return matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18485. }
  18486. /**
  18487. * Gets the morph target weights of the defined instance.
  18488. *
  18489. * @param {number} index - The instance index.
  18490. * @param {Mesh} object - The target object that is used to store the method's result.
  18491. */
  18492. getMorphAt( index, object ) {
  18493. const objectInfluences = object.morphTargetInfluences;
  18494. const array = this.morphTexture.source.data.data;
  18495. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18496. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18497. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18498. objectInfluences[ i ] = array[ dataIndex + i ];
  18499. }
  18500. }
  18501. raycast( raycaster, intersects ) {
  18502. const matrixWorld = this.matrixWorld;
  18503. const raycastTimes = this.count;
  18504. _mesh$1.geometry = this.geometry;
  18505. _mesh$1.material = this.material;
  18506. if ( _mesh$1.material === undefined ) return;
  18507. // test with bounding sphere first
  18508. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18509. _sphere$4.copy( this.boundingSphere );
  18510. _sphere$4.applyMatrix4( matrixWorld );
  18511. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18512. // now test each instance
  18513. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18514. // calculate the world matrix for each instance
  18515. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18516. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18517. // the mesh represents this single instance
  18518. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18519. _mesh$1.raycast( raycaster, _instanceIntersects );
  18520. // process the result of raycast
  18521. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18522. const intersect = _instanceIntersects[ i ];
  18523. intersect.instanceId = instanceId;
  18524. intersect.object = this;
  18525. intersects.push( intersect );
  18526. }
  18527. _instanceIntersects.length = 0;
  18528. }
  18529. }
  18530. /**
  18531. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18532. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18533. *
  18534. * @param {number} index - The instance index.
  18535. * @param {Color} color - The instance color.
  18536. * @return {InstancedMesh} A reference to this instanced mesh.
  18537. */
  18538. setColorAt( index, color ) {
  18539. if ( this.instanceColor === null ) {
  18540. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18541. }
  18542. color.toArray( this.instanceColor.array, index * 3 );
  18543. return this;
  18544. }
  18545. /**
  18546. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18547. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the matrices.
  18548. *
  18549. * @param {number} index - The instance index.
  18550. * @param {Matrix4} matrix - The local transformation.
  18551. * @return {InstancedMesh} A reference to this instanced mesh.
  18552. */
  18553. setMatrixAt( index, matrix ) {
  18554. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18555. return this;
  18556. }
  18557. /**
  18558. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18559. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18560. *
  18561. * @param {number} index - The instance index.
  18562. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18563. * of a single instance.
  18564. * @return {InstancedMesh} A reference to this instanced mesh.
  18565. */
  18566. setMorphAt( index, object ) {
  18567. const objectInfluences = object.morphTargetInfluences;
  18568. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18569. if ( this.morphTexture === null ) {
  18570. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18571. }
  18572. const array = this.morphTexture.source.data.data;
  18573. let morphInfluencesSum = 0;
  18574. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18575. morphInfluencesSum += objectInfluences[ i ];
  18576. }
  18577. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18578. const dataIndex = len * index;
  18579. array[ dataIndex ] = morphBaseInfluence;
  18580. array.set( objectInfluences, dataIndex + 1 );
  18581. return this;
  18582. }
  18583. updateMorphTargets() {
  18584. }
  18585. /**
  18586. * Frees the GPU-related resources allocated by this instance. Call this
  18587. * method whenever this instance is no longer used in your app.
  18588. */
  18589. dispose() {
  18590. this.dispatchEvent( { type: 'dispose' } );
  18591. if ( this.morphTexture !== null ) {
  18592. this.morphTexture.dispose();
  18593. this.morphTexture = null;
  18594. }
  18595. }
  18596. }
  18597. const _vector1 = /*@__PURE__*/ new Vector3();
  18598. const _vector2 = /*@__PURE__*/ new Vector3();
  18599. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  18600. /**
  18601. * A two dimensional surface that extends infinitely in 3D space, represented
  18602. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  18603. * by a unit length normal vector and a constant.
  18604. */
  18605. class Plane {
  18606. /**
  18607. * Constructs a new plane.
  18608. *
  18609. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  18610. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  18611. */
  18612. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  18613. /**
  18614. * This flag can be used for type testing.
  18615. *
  18616. * @type {boolean}
  18617. * @readonly
  18618. * @default true
  18619. */
  18620. this.isPlane = true;
  18621. /**
  18622. * A unit length vector defining the normal of the plane.
  18623. *
  18624. * @type {Vector3}
  18625. */
  18626. this.normal = normal;
  18627. /**
  18628. * The signed distance from the origin to the plane.
  18629. *
  18630. * @type {number}
  18631. * @default 0
  18632. */
  18633. this.constant = constant;
  18634. }
  18635. /**
  18636. * Sets the plane components by copying the given values.
  18637. *
  18638. * @param {Vector3} normal - The normal.
  18639. * @param {number} constant - The constant.
  18640. * @return {Plane} A reference to this plane.
  18641. */
  18642. set( normal, constant ) {
  18643. this.normal.copy( normal );
  18644. this.constant = constant;
  18645. return this;
  18646. }
  18647. /**
  18648. * Sets the plane components by defining `x`, `y`, `z` as the
  18649. * plane normal and `w` as the constant.
  18650. *
  18651. * @param {number} x - The value for the normal's x component.
  18652. * @param {number} y - The value for the normal's y component.
  18653. * @param {number} z - The value for the normal's z component.
  18654. * @param {number} w - The constant value.
  18655. * @return {Plane} A reference to this plane.
  18656. */
  18657. setComponents( x, y, z, w ) {
  18658. this.normal.set( x, y, z );
  18659. this.constant = w;
  18660. return this;
  18661. }
  18662. /**
  18663. * Sets the plane from the given normal and coplanar point (that is a point
  18664. * that lies onto the plane).
  18665. *
  18666. * @param {Vector3} normal - The normal.
  18667. * @param {Vector3} point - A coplanar point.
  18668. * @return {Plane} A reference to this plane.
  18669. */
  18670. setFromNormalAndCoplanarPoint( normal, point ) {
  18671. this.normal.copy( normal );
  18672. this.constant = - point.dot( this.normal );
  18673. return this;
  18674. }
  18675. /**
  18676. * Sets the plane from three coplanar points. The winding order is
  18677. * assumed to be counter-clockwise, and determines the direction of
  18678. * the plane normal.
  18679. *
  18680. * @param {Vector3} a - The first coplanar point.
  18681. * @param {Vector3} b - The second coplanar point.
  18682. * @param {Vector3} c - The third coplanar point.
  18683. * @return {Plane} A reference to this plane.
  18684. */
  18685. setFromCoplanarPoints( a, b, c ) {
  18686. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  18687. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  18688. this.setFromNormalAndCoplanarPoint( normal, a );
  18689. return this;
  18690. }
  18691. /**
  18692. * Copies the values of the given plane to this instance.
  18693. *
  18694. * @param {Plane} plane - The plane to copy.
  18695. * @return {Plane} A reference to this plane.
  18696. */
  18697. copy( plane ) {
  18698. this.normal.copy( plane.normal );
  18699. this.constant = plane.constant;
  18700. return this;
  18701. }
  18702. /**
  18703. * Normalizes the plane normal and adjusts the constant accordingly.
  18704. *
  18705. * @return {Plane} A reference to this plane.
  18706. */
  18707. normalize() {
  18708. // Note: will lead to a divide by zero if the plane is invalid.
  18709. const inverseNormalLength = 1.0 / this.normal.length();
  18710. this.normal.multiplyScalar( inverseNormalLength );
  18711. this.constant *= inverseNormalLength;
  18712. return this;
  18713. }
  18714. /**
  18715. * Negates both the plane normal and the constant.
  18716. *
  18717. * @return {Plane} A reference to this plane.
  18718. */
  18719. negate() {
  18720. this.constant *= -1;
  18721. this.normal.negate();
  18722. return this;
  18723. }
  18724. /**
  18725. * Returns the signed distance from the given point to this plane.
  18726. *
  18727. * @param {Vector3} point - The point to compute the distance for.
  18728. * @return {number} The signed distance.
  18729. */
  18730. distanceToPoint( point ) {
  18731. return this.normal.dot( point ) + this.constant;
  18732. }
  18733. /**
  18734. * Returns the signed distance from the given sphere to this plane.
  18735. *
  18736. * @param {Sphere} sphere - The sphere to compute the distance for.
  18737. * @return {number} The signed distance.
  18738. */
  18739. distanceToSphere( sphere ) {
  18740. return this.distanceToPoint( sphere.center ) - sphere.radius;
  18741. }
  18742. /**
  18743. * Projects a the given point onto the plane.
  18744. *
  18745. * @param {Vector3} point - The point to project.
  18746. * @param {Vector3} target - The target vector that is used to store the method's result.
  18747. * @return {Vector3} The projected point on the plane.
  18748. */
  18749. projectPoint( point, target ) {
  18750. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  18751. }
  18752. /**
  18753. * Returns the intersection point of the passed line and the plane. Returns
  18754. * `null` if the line does not intersect. Returns the line's starting point if
  18755. * the line is coplanar with the plane.
  18756. *
  18757. * @param {Line3} line - The line to compute the intersection for.
  18758. * @param {Vector3} target - The target vector that is used to store the method's result.
  18759. * @param {boolean} [clampToLine=true] - Whether to clamp the intersection to the line segment.
  18760. * @return {?Vector3} The intersection point. Returns `null` if no intersection is detected.
  18761. */
  18762. intersectLine( line, target, clampToLine = true ) {
  18763. const direction = line.delta( _vector1 );
  18764. const denominator = this.normal.dot( direction );
  18765. if ( denominator === 0 ) {
  18766. // line is coplanar, return origin
  18767. if ( this.distanceToPoint( line.start ) === 0 ) {
  18768. return target.copy( line.start );
  18769. }
  18770. // Unsure if this is the correct method to handle this case.
  18771. return null;
  18772. }
  18773. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  18774. if ( ( clampToLine === true ) && ( t < 0 || t > 1 ) ) {
  18775. return null;
  18776. }
  18777. return target.copy( line.start ).addScaledVector( direction, t );
  18778. }
  18779. /**
  18780. * Returns `true` if the given line segment intersects with (passes through) the plane.
  18781. *
  18782. * @param {Line3} line - The line to test.
  18783. * @return {boolean} Whether the given line segment intersects with the plane or not.
  18784. */
  18785. intersectsLine( line ) {
  18786. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  18787. const startSign = this.distanceToPoint( line.start );
  18788. const endSign = this.distanceToPoint( line.end );
  18789. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  18790. }
  18791. /**
  18792. * Returns `true` if the given bounding box intersects with the plane.
  18793. *
  18794. * @param {Box3} box - The bounding box to test.
  18795. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  18796. */
  18797. intersectsBox( box ) {
  18798. return box.intersectsPlane( this );
  18799. }
  18800. /**
  18801. * Returns `true` if the given bounding sphere intersects with the plane.
  18802. *
  18803. * @param {Sphere} sphere - The bounding sphere to test.
  18804. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  18805. */
  18806. intersectsSphere( sphere ) {
  18807. return sphere.intersectsPlane( this );
  18808. }
  18809. /**
  18810. * Returns a coplanar vector to the plane, by calculating the
  18811. * projection of the normal at the origin onto the plane.
  18812. *
  18813. * @param {Vector3} target - The target vector that is used to store the method's result.
  18814. * @return {Vector3} The coplanar point.
  18815. */
  18816. coplanarPoint( target ) {
  18817. return target.copy( this.normal ).multiplyScalar( - this.constant );
  18818. }
  18819. /**
  18820. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  18821. *
  18822. * The optional normal matrix can be pre-computed like so:
  18823. * ```js
  18824. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  18825. * ```
  18826. *
  18827. * @param {Matrix4} matrix - The transformation matrix.
  18828. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  18829. * @return {Plane} A reference to this plane.
  18830. */
  18831. applyMatrix4( matrix, optionalNormalMatrix ) {
  18832. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  18833. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  18834. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  18835. this.constant = - referencePoint.dot( normal );
  18836. return this;
  18837. }
  18838. /**
  18839. * Translates the plane by the distance defined by the given offset vector.
  18840. * Note that this only affects the plane constant and will not affect the normal vector.
  18841. *
  18842. * @param {Vector3} offset - The offset vector.
  18843. * @return {Plane} A reference to this plane.
  18844. */
  18845. translate( offset ) {
  18846. this.constant -= offset.dot( this.normal );
  18847. return this;
  18848. }
  18849. /**
  18850. * Returns `true` if this plane is equal with the given one.
  18851. *
  18852. * @param {Plane} plane - The plane to test for equality.
  18853. * @return {boolean} Whether this plane is equal with the given one.
  18854. */
  18855. equals( plane ) {
  18856. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  18857. }
  18858. /**
  18859. * Returns a new plane with copied values from this instance.
  18860. *
  18861. * @return {Plane} A clone of this instance.
  18862. */
  18863. clone() {
  18864. return new this.constructor().copy( this );
  18865. }
  18866. }
  18867. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18868. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  18869. const _vector$6 = /*@__PURE__*/ new Vector3();
  18870. /**
  18871. * Frustums are used to determine what is inside the camera's field of view.
  18872. * They help speed up the rendering process - objects which lie outside a camera's
  18873. * frustum can safely be excluded from rendering.
  18874. *
  18875. * This class is mainly intended for use internally by a renderer.
  18876. */
  18877. class Frustum {
  18878. /**
  18879. * Constructs a new frustum.
  18880. *
  18881. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18882. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18883. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18884. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18885. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18886. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18887. */
  18888. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  18889. /**
  18890. * This array holds the planes that enclose the frustum.
  18891. *
  18892. * @type {Array<Plane>}
  18893. */
  18894. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  18895. }
  18896. /**
  18897. * Sets the frustum planes by copying the given planes.
  18898. *
  18899. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18900. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18901. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18902. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18903. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18904. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18905. * @return {Frustum} A reference to this frustum.
  18906. */
  18907. set( p0, p1, p2, p3, p4, p5 ) {
  18908. const planes = this.planes;
  18909. planes[ 0 ].copy( p0 );
  18910. planes[ 1 ].copy( p1 );
  18911. planes[ 2 ].copy( p2 );
  18912. planes[ 3 ].copy( p3 );
  18913. planes[ 4 ].copy( p4 );
  18914. planes[ 5 ].copy( p5 );
  18915. return this;
  18916. }
  18917. /**
  18918. * Copies the values of the given frustum to this instance.
  18919. *
  18920. * @param {Frustum} frustum - The frustum to copy.
  18921. * @return {Frustum} A reference to this frustum.
  18922. */
  18923. copy( frustum ) {
  18924. const planes = this.planes;
  18925. for ( let i = 0; i < 6; i ++ ) {
  18926. planes[ i ].copy( frustum.planes[ i ] );
  18927. }
  18928. return this;
  18929. }
  18930. /**
  18931. * Sets the frustum planes from the given projection matrix.
  18932. *
  18933. * @param {Matrix4} m - The projection matrix.
  18934. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  18935. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  18936. * @return {Frustum} A reference to this frustum.
  18937. */
  18938. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  18939. const planes = this.planes;
  18940. const me = m.elements;
  18941. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  18942. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  18943. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  18944. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  18945. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  18946. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  18947. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  18948. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  18949. if ( reversedDepth ) {
  18950. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  18951. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  18952. } else {
  18953. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  18954. if ( coordinateSystem === WebGLCoordinateSystem ) {
  18955. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  18956. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  18957. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  18958. } else {
  18959. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  18960. }
  18961. }
  18962. return this;
  18963. }
  18964. /**
  18965. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  18966. *
  18967. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  18968. *
  18969. * @param {Object3D} object - The 3D object to test.
  18970. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  18971. */
  18972. intersectsObject( object ) {
  18973. if ( object.boundingSphere !== undefined ) {
  18974. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  18975. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  18976. } else {
  18977. const geometry = object.geometry;
  18978. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18979. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  18980. }
  18981. return this.intersectsSphere( _sphere$3 );
  18982. }
  18983. /**
  18984. * Returns `true` if the given sprite is intersecting this frustum.
  18985. *
  18986. * @param {Sprite} sprite - The sprite to test.
  18987. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  18988. */
  18989. intersectsSprite( sprite ) {
  18990. _sphere$3.center.set( 0, 0, 0 );
  18991. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  18992. _sphere$3.radius = 0.7071067811865476 + offset;
  18993. _sphere$3.applyMatrix4( sprite.matrixWorld );
  18994. return this.intersectsSphere( _sphere$3 );
  18995. }
  18996. /**
  18997. * Returns `true` if the given bounding sphere is intersecting this frustum.
  18998. *
  18999. * @param {Sphere} sphere - The bounding sphere to test.
  19000. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19001. */
  19002. intersectsSphere( sphere ) {
  19003. const planes = this.planes;
  19004. const center = sphere.center;
  19005. const negRadius = - sphere.radius;
  19006. for ( let i = 0; i < 6; i ++ ) {
  19007. const distance = planes[ i ].distanceToPoint( center );
  19008. if ( distance < negRadius ) {
  19009. return false;
  19010. }
  19011. }
  19012. return true;
  19013. }
  19014. /**
  19015. * Returns `true` if the given bounding box is intersecting this frustum.
  19016. *
  19017. * @param {Box3} box - The bounding box to test.
  19018. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19019. */
  19020. intersectsBox( box ) {
  19021. const planes = this.planes;
  19022. for ( let i = 0; i < 6; i ++ ) {
  19023. const plane = planes[ i ];
  19024. // corner at max distance
  19025. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19026. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19027. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19028. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19029. return false;
  19030. }
  19031. }
  19032. return true;
  19033. }
  19034. /**
  19035. * Returns `true` if the given point lies within the frustum.
  19036. *
  19037. * @param {Vector3} point - The point to test.
  19038. * @return {boolean} Whether the point lies within this frustum or not.
  19039. */
  19040. containsPoint( point ) {
  19041. const planes = this.planes;
  19042. for ( let i = 0; i < 6; i ++ ) {
  19043. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19044. return false;
  19045. }
  19046. }
  19047. return true;
  19048. }
  19049. /**
  19050. * Returns a new frustum with copied values from this instance.
  19051. *
  19052. * @return {Frustum} A clone of this instance.
  19053. */
  19054. clone() {
  19055. return new this.constructor().copy( this );
  19056. }
  19057. }
  19058. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  19059. /**
  19060. * FrustumArray is used to determine if an object is visible in at least one camera
  19061. * from an array of cameras. This is particularly useful for multi-view renderers.
  19062. */
  19063. class FrustumArray {
  19064. /**
  19065. * Constructs a new frustum array.
  19066. *
  19067. */
  19068. constructor() {
  19069. /**
  19070. * The coordinate system to use.
  19071. *
  19072. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19073. * @default WebGLCoordinateSystem
  19074. */
  19075. this.coordinateSystem = WebGLCoordinateSystem;
  19076. /**
  19077. * A pool of frustum instances. It may hold more entries than are
  19078. * currently in use; surplus instances are kept for reuse to avoid
  19079. * reallocating when array cameras of different lengths are rendered.
  19080. *
  19081. * @private
  19082. * @type {Array<Frustum>}
  19083. */
  19084. this._frustums = [];
  19085. /**
  19086. * The number of frustums in {@link FrustumArray#_frustums} that are currently
  19087. * in use.
  19088. *
  19089. * @private
  19090. * @type {number}
  19091. * @default 0
  19092. */
  19093. this._count = 0;
  19094. }
  19095. /**
  19096. * Computes and caches a frustum for each camera of the given array camera.
  19097. *
  19098. * @param {ArrayCamera} cameraArray - The array camera whose sub-cameras define the frustums.
  19099. * @return {FrustumArray} A reference to this frustum array.
  19100. */
  19101. setFromArrayCamera( cameraArray ) {
  19102. const cameras = cameraArray.cameras;
  19103. const frustums = this._frustums;
  19104. for ( let i = 0; i < cameras.length; i ++ ) {
  19105. const camera = cameras[ i ];
  19106. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  19107. if ( frustums[ i ] === undefined ) frustums[ i ] = new Frustum();
  19108. frustums[ i ].setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  19109. }
  19110. this._count = cameras.length;
  19111. return this;
  19112. }
  19113. /**
  19114. * Returns `true` if the 3D object's bounding sphere is intersecting any cached frustum.
  19115. *
  19116. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19117. *
  19118. * @param {Object3D} object - The 3D object to test.
  19119. * @return {boolean} Whether the 3D object is visible in any camera.
  19120. */
  19121. intersectsObject( object ) {
  19122. const frustums = this._frustums;
  19123. for ( let i = 0; i < this._count; i ++ ) {
  19124. if ( frustums[ i ].intersectsObject( object ) ) return true;
  19125. }
  19126. return false;
  19127. }
  19128. /**
  19129. * Returns `true` if the given sprite is intersecting any cached frustum.
  19130. *
  19131. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19132. *
  19133. * @param {Sprite} sprite - The sprite to test.
  19134. * @return {boolean} Whether the sprite is visible in any camera.
  19135. */
  19136. intersectsSprite( sprite ) {
  19137. const frustums = this._frustums;
  19138. for ( let i = 0; i < this._count; i ++ ) {
  19139. if ( frustums[ i ].intersectsSprite( sprite ) ) return true;
  19140. }
  19141. return false;
  19142. }
  19143. /**
  19144. * Returns `true` if the given bounding sphere is intersecting any cached frustum.
  19145. *
  19146. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19147. *
  19148. * @param {Sphere} sphere - The bounding sphere to test.
  19149. * @return {boolean} Whether the sphere is visible in any camera.
  19150. */
  19151. intersectsSphere( sphere ) {
  19152. const frustums = this._frustums;
  19153. for ( let i = 0; i < this._count; i ++ ) {
  19154. if ( frustums[ i ].intersectsSphere( sphere ) ) return true;
  19155. }
  19156. return false;
  19157. }
  19158. /**
  19159. * Returns `true` if the given bounding box is intersecting any cached frustum.
  19160. *
  19161. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19162. *
  19163. * @param {Box3} box - The bounding box to test.
  19164. * @return {boolean} Whether the box is visible in any camera.
  19165. */
  19166. intersectsBox( box ) {
  19167. const frustums = this._frustums;
  19168. for ( let i = 0; i < this._count; i ++ ) {
  19169. if ( frustums[ i ].intersectsBox( box ) ) return true;
  19170. }
  19171. return false;
  19172. }
  19173. /**
  19174. * Returns `true` if the given point lies within any cached frustum.
  19175. *
  19176. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19177. *
  19178. * @param {Vector3} point - The point to test.
  19179. * @return {boolean} Whether the point is visible in any camera.
  19180. */
  19181. containsPoint( point ) {
  19182. const frustums = this._frustums;
  19183. for ( let i = 0; i < this._count; i ++ ) {
  19184. if ( frustums[ i ].containsPoint( point ) ) return true;
  19185. }
  19186. return false;
  19187. }
  19188. /**
  19189. * Copies the values of the given frustum array to this instance.
  19190. *
  19191. * @param {FrustumArray} frustumArray - The frustum array to copy.
  19192. * @return {FrustumArray} A reference to this frustum array.
  19193. */
  19194. copy( source ) {
  19195. this.coordinateSystem = source.coordinateSystem;
  19196. const frustums = this._frustums;
  19197. const sourceFrustums = source._frustums;
  19198. for ( let i = 0; i < source._count; i ++ ) {
  19199. if ( frustums[ i ] === undefined ) frustums[ i ] = new Frustum();
  19200. frustums[ i ].copy( sourceFrustums[ i ] );
  19201. }
  19202. this._count = source._count;
  19203. return this;
  19204. }
  19205. /**
  19206. * Returns a new frustum array with copied values from this instance.
  19207. *
  19208. * @return {FrustumArray} A clone of this instance.
  19209. */
  19210. clone() {
  19211. return new FrustumArray().copy( this );
  19212. }
  19213. }
  19214. function ascIdSort( a, b ) {
  19215. return a - b;
  19216. }
  19217. function sortOpaque( a, b ) {
  19218. return a.z - b.z;
  19219. }
  19220. function sortTransparent( a, b ) {
  19221. return b.z - a.z;
  19222. }
  19223. class MultiDrawRenderList {
  19224. constructor() {
  19225. this.index = 0;
  19226. this.pool = [];
  19227. this.list = [];
  19228. }
  19229. push( start, count, z, index ) {
  19230. const pool = this.pool;
  19231. const list = this.list;
  19232. if ( this.index >= pool.length ) {
  19233. pool.push( {
  19234. start: -1,
  19235. count: -1,
  19236. z: -1,
  19237. index: -1,
  19238. } );
  19239. }
  19240. const item = pool[ this.index ];
  19241. list.push( item );
  19242. this.index ++;
  19243. item.start = start;
  19244. item.count = count;
  19245. item.z = z;
  19246. item.index = index;
  19247. }
  19248. reset() {
  19249. this.list.length = 0;
  19250. this.index = 0;
  19251. }
  19252. }
  19253. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19254. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19255. const _frustum = /*@__PURE__*/ new Frustum();
  19256. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19257. const _box$1 = /*@__PURE__*/ new Box3();
  19258. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19259. const _vector$5 = /*@__PURE__*/ new Vector3();
  19260. const _forward$1 = /*@__PURE__*/ new Vector3();
  19261. const _temp = /*@__PURE__*/ new Vector3();
  19262. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19263. const _mesh = /*@__PURE__*/ new Mesh();
  19264. const _batchIntersects = [];
  19265. // copies data from attribute "src" into "target" starting at "targetOffset"
  19266. function copyAttributeData( src, target, targetOffset = 0 ) {
  19267. const itemSize = target.itemSize;
  19268. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19269. // use the component getters and setters if the array data cannot
  19270. // be copied directly
  19271. const vertexCount = src.count;
  19272. for ( let i = 0; i < vertexCount; i ++ ) {
  19273. for ( let c = 0; c < itemSize; c ++ ) {
  19274. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19275. }
  19276. }
  19277. } else {
  19278. // faster copy approach using typed array set function
  19279. target.array.set( src.array, targetOffset * itemSize );
  19280. }
  19281. target.needsUpdate = true;
  19282. }
  19283. // safely copies array contents to a potentially smaller array
  19284. function copyArrayContents( src, target ) {
  19285. if ( src.constructor !== target.constructor ) {
  19286. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19287. const len = Math.min( src.length, target.length );
  19288. for ( let i = 0; i < len; i ++ ) {
  19289. target[ i ] = src[ i ];
  19290. }
  19291. } else {
  19292. // if the arrays use the same data layout we can use a fast block copy
  19293. const len = Math.min( src.length, target.length );
  19294. target.set( new src.constructor( src.buffer, 0, len ) );
  19295. }
  19296. }
  19297. /**
  19298. * A special version of a mesh with multi draw batch rendering support. Use
  19299. * this class if you have to render a large number of objects with the same
  19300. * material but with different geometries or world transformations. The usage of
  19301. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19302. * rendering performance in your application.
  19303. *
  19304. * ```js
  19305. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19306. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19307. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19308. *
  19309. * // initialize and add geometries into the batched mesh
  19310. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19311. * const boxGeometryId = batchedMesh.addGeometry( box );
  19312. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19313. *
  19314. * // create instances of those geometries
  19315. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19316. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19317. *
  19318. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19319. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19320. *
  19321. * // position the geometries
  19322. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19323. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19324. *
  19325. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19326. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19327. *
  19328. * scene.add( batchedMesh );
  19329. * ```
  19330. *
  19331. * @augments Mesh
  19332. */
  19333. class BatchedMesh extends Mesh {
  19334. /**
  19335. * Constructs a new batched mesh.
  19336. *
  19337. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19338. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19339. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19340. * @param {Material|Array<Material>} [material] - The mesh material.
  19341. */
  19342. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19343. super( new BufferGeometry(), material );
  19344. /**
  19345. * This flag can be used for type testing.
  19346. *
  19347. * @type {boolean}
  19348. * @readonly
  19349. * @default true
  19350. */
  19351. this.isBatchedMesh = true;
  19352. /**
  19353. * When set ot `true`, the individual objects of a batch are frustum culled.
  19354. *
  19355. * @type {boolean}
  19356. * @default true
  19357. */
  19358. this.perObjectFrustumCulled = true;
  19359. /**
  19360. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19361. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19362. * rendered front to back.
  19363. *
  19364. * @type {boolean}
  19365. * @default true
  19366. */
  19367. this.sortObjects = true;
  19368. /**
  19369. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19370. *
  19371. * @type {?Box3}
  19372. * @default null
  19373. */
  19374. this.boundingBox = null;
  19375. /**
  19376. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19377. *
  19378. * @type {?Sphere}
  19379. * @default null
  19380. */
  19381. this.boundingSphere = null;
  19382. /**
  19383. * Takes a sort a function that is run before render. The function takes a list of instances to
  19384. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19385. * sort with.
  19386. *
  19387. * @type {?Function}
  19388. * @default null
  19389. */
  19390. this.customSort = null;
  19391. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19392. this._instanceInfo = [];
  19393. this._geometryInfo = [];
  19394. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19395. this._availableInstanceIds = [];
  19396. this._availableGeometryIds = [];
  19397. // used to track where the next point is that geometry should be inserted
  19398. this._nextIndexStart = 0;
  19399. this._nextVertexStart = 0;
  19400. this._geometryCount = 0;
  19401. // flags
  19402. this._visibilityChanged = true;
  19403. this._geometryInitialized = false;
  19404. // cached user options
  19405. this._maxInstanceCount = maxInstanceCount;
  19406. this._maxVertexCount = maxVertexCount;
  19407. this._maxIndexCount = maxIndexCount;
  19408. // buffers for multi draw
  19409. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19410. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19411. this._multiDrawCount = 0;
  19412. // Local matrix per geometry by using data texture
  19413. this._matricesTexture = null;
  19414. this._indirectTexture = null;
  19415. this._colorsTexture = null;
  19416. this._initMatricesTexture();
  19417. this._initIndirectTexture();
  19418. }
  19419. /**
  19420. * The maximum number of individual instances that can be stored in the batch.
  19421. *
  19422. * @type {number}
  19423. * @readonly
  19424. */
  19425. get maxInstanceCount() {
  19426. return this._maxInstanceCount;
  19427. }
  19428. /**
  19429. * The instance count.
  19430. *
  19431. * @type {number}
  19432. * @readonly
  19433. */
  19434. get instanceCount() {
  19435. return this._instanceInfo.length - this._availableInstanceIds.length;
  19436. }
  19437. /**
  19438. * The number of unused vertices.
  19439. *
  19440. * @type {number}
  19441. * @readonly
  19442. */
  19443. get unusedVertexCount() {
  19444. return this._maxVertexCount - this._nextVertexStart;
  19445. }
  19446. /**
  19447. * The number of unused indices.
  19448. *
  19449. * @type {number}
  19450. * @readonly
  19451. */
  19452. get unusedIndexCount() {
  19453. return this._maxIndexCount - this._nextIndexStart;
  19454. }
  19455. _initMatricesTexture() {
  19456. // layout (1 matrix = 4 pixels)
  19457. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19458. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19459. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19460. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19461. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19462. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19463. size = Math.ceil( size / 4 ) * 4;
  19464. size = Math.max( size, 4 );
  19465. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19466. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19467. this._matricesTexture = matricesTexture;
  19468. }
  19469. _initIndirectTexture() {
  19470. let size = Math.sqrt( this._maxInstanceCount );
  19471. size = Math.ceil( size );
  19472. const indirectArray = new Uint32Array( size * size );
  19473. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19474. this._indirectTexture = indirectTexture;
  19475. }
  19476. _initColorsTexture() {
  19477. let size = Math.sqrt( this._maxInstanceCount );
  19478. size = Math.ceil( size );
  19479. // 4 floats per RGBA pixel initialized to white
  19480. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19481. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19482. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19483. this._colorsTexture = colorsTexture;
  19484. }
  19485. _initializeGeometry( reference ) {
  19486. const geometry = this.geometry;
  19487. const maxVertexCount = this._maxVertexCount;
  19488. const maxIndexCount = this._maxIndexCount;
  19489. if ( this._geometryInitialized === false ) {
  19490. for ( const attributeName in reference.attributes ) {
  19491. const srcAttribute = reference.getAttribute( attributeName );
  19492. const { array, itemSize, normalized } = srcAttribute;
  19493. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19494. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19495. geometry.setAttribute( attributeName, dstAttribute );
  19496. }
  19497. if ( reference.getIndex() !== null ) {
  19498. // Reserve last u16 index for primitive restart.
  19499. const indexArray = maxVertexCount > 65535
  19500. ? new Uint32Array( maxIndexCount )
  19501. : new Uint16Array( maxIndexCount );
  19502. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19503. }
  19504. this._geometryInitialized = true;
  19505. }
  19506. }
  19507. // Make sure the geometry is compatible with the existing combined geometry attributes
  19508. _validateGeometry( geometry ) {
  19509. // check to ensure the geometries are using consistent attributes and indices
  19510. const batchGeometry = this.geometry;
  19511. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19512. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19513. }
  19514. for ( const attributeName in batchGeometry.attributes ) {
  19515. if ( ! geometry.hasAttribute( attributeName ) ) {
  19516. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19517. }
  19518. const srcAttribute = geometry.getAttribute( attributeName );
  19519. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19520. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19521. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19522. }
  19523. }
  19524. }
  19525. /**
  19526. * Validates the instance defined by the given ID.
  19527. *
  19528. * @param {number} instanceId - The instance to validate.
  19529. */
  19530. validateInstanceId( instanceId ) {
  19531. const instanceInfo = this._instanceInfo;
  19532. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19533. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19534. }
  19535. }
  19536. /**
  19537. * Validates the geometry defined by the given ID.
  19538. *
  19539. * @param {number} geometryId - The geometry to validate.
  19540. */
  19541. validateGeometryId( geometryId ) {
  19542. const geometryInfoList = this._geometryInfo;
  19543. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19544. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19545. }
  19546. }
  19547. /**
  19548. * Takes a sort a function that is run before render. The function takes a list of instances to
  19549. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19550. *
  19551. * @param {Function} func - The custom sort function.
  19552. * @return {BatchedMesh} A reference to this batched mesh.
  19553. */
  19554. setCustomSort( func ) {
  19555. this.customSort = func;
  19556. return this;
  19557. }
  19558. /**
  19559. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19560. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19561. * otherwise they are `null`.
  19562. */
  19563. computeBoundingBox() {
  19564. if ( this.boundingBox === null ) {
  19565. this.boundingBox = new Box3();
  19566. }
  19567. const boundingBox = this.boundingBox;
  19568. const instanceInfo = this._instanceInfo;
  19569. boundingBox.makeEmpty();
  19570. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19571. if ( instanceInfo[ i ].active === false ) continue;
  19572. const geometryId = instanceInfo[ i ].geometryIndex;
  19573. this.getMatrixAt( i, _matrix$1 );
  19574. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19575. boundingBox.union( _box$1 );
  19576. }
  19577. }
  19578. /**
  19579. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19580. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19581. * otherwise they are `null`.
  19582. */
  19583. computeBoundingSphere() {
  19584. if ( this.boundingSphere === null ) {
  19585. this.boundingSphere = new Sphere();
  19586. }
  19587. const boundingSphere = this.boundingSphere;
  19588. const instanceInfo = this._instanceInfo;
  19589. boundingSphere.makeEmpty();
  19590. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19591. if ( instanceInfo[ i ].active === false ) continue;
  19592. const geometryId = instanceInfo[ i ].geometryIndex;
  19593. this.getMatrixAt( i, _matrix$1 );
  19594. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19595. boundingSphere.union( _sphere$2 );
  19596. }
  19597. }
  19598. /**
  19599. * Adds a new instance to the batch using the geometry of the given ID and returns
  19600. * a new id referring to the new instance to be used by other functions.
  19601. *
  19602. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  19603. * @return {number} The instance ID.
  19604. */
  19605. addInstance( geometryId ) {
  19606. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  19607. // ensure we're not over geometry
  19608. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  19609. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  19610. }
  19611. const instanceInfo = {
  19612. visible: true,
  19613. active: true,
  19614. geometryIndex: geometryId,
  19615. };
  19616. let drawId = null;
  19617. // Prioritize using previously freed instance ids
  19618. if ( this._availableInstanceIds.length > 0 ) {
  19619. this._availableInstanceIds.sort( ascIdSort );
  19620. drawId = this._availableInstanceIds.shift();
  19621. this._instanceInfo[ drawId ] = instanceInfo;
  19622. } else {
  19623. drawId = this._instanceInfo.length;
  19624. this._instanceInfo.push( instanceInfo );
  19625. }
  19626. const matricesTexture = this._matricesTexture;
  19627. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  19628. matricesTexture.needsUpdate = true;
  19629. const colorsTexture = this._colorsTexture;
  19630. if ( colorsTexture ) {
  19631. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  19632. colorsTexture.needsUpdate = true;
  19633. }
  19634. this._visibilityChanged = true;
  19635. return drawId;
  19636. }
  19637. /**
  19638. * Adds the given geometry to the batch and returns the associated
  19639. * geometry id referring to it to be used in other functions.
  19640. *
  19641. * @param {BufferGeometry} geometry - The geometry to add.
  19642. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  19643. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  19644. * to set a new geometry at this index at a later time that is larger than the original geometry.
  19645. * Defaults to the length of the given geometry vertex buffer.
  19646. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  19647. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  19648. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  19649. * the length of the given geometry index buffer.
  19650. * @return {number} The geometry ID.
  19651. */
  19652. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  19653. this._initializeGeometry( geometry );
  19654. this._validateGeometry( geometry );
  19655. const geometryInfo = {
  19656. // geometry information
  19657. vertexStart: -1,
  19658. vertexCount: -1,
  19659. reservedVertexCount: -1,
  19660. indexStart: -1,
  19661. indexCount: -1,
  19662. reservedIndexCount: -1,
  19663. // draw range information
  19664. start: -1,
  19665. count: -1,
  19666. // state
  19667. boundingBox: null,
  19668. boundingSphere: null,
  19669. active: true,
  19670. };
  19671. const geometryInfoList = this._geometryInfo;
  19672. geometryInfo.vertexStart = this._nextVertexStart;
  19673. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  19674. const index = geometry.getIndex();
  19675. const hasIndex = index !== null;
  19676. if ( hasIndex ) {
  19677. geometryInfo.indexStart = this._nextIndexStart;
  19678. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  19679. }
  19680. if (
  19681. geometryInfo.indexStart !== -1 &&
  19682. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  19683. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  19684. ) {
  19685. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19686. }
  19687. // update id
  19688. let geometryId;
  19689. if ( this._availableGeometryIds.length > 0 ) {
  19690. this._availableGeometryIds.sort( ascIdSort );
  19691. geometryId = this._availableGeometryIds.shift();
  19692. geometryInfoList[ geometryId ] = geometryInfo;
  19693. } else {
  19694. geometryId = this._geometryCount;
  19695. this._geometryCount ++;
  19696. geometryInfoList.push( geometryInfo );
  19697. }
  19698. // update the geometry
  19699. this.setGeometryAt( geometryId, geometry );
  19700. // increment the next geometry position
  19701. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  19702. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  19703. return geometryId;
  19704. }
  19705. /**
  19706. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  19707. * is not enough space reserved for geometry. Calling this will change all instances that are
  19708. * rendering that geometry.
  19709. *
  19710. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  19711. * @param {BufferGeometry} geometry - The new geometry.
  19712. * @return {number} The geometry ID.
  19713. */
  19714. setGeometryAt( geometryId, geometry ) {
  19715. if ( geometryId >= this._geometryCount ) {
  19716. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  19717. }
  19718. this._validateGeometry( geometry );
  19719. const batchGeometry = this.geometry;
  19720. const hasIndex = batchGeometry.getIndex() !== null;
  19721. const dstIndex = batchGeometry.getIndex();
  19722. const srcIndex = geometry.getIndex();
  19723. const geometryInfo = this._geometryInfo[ geometryId ];
  19724. if (
  19725. hasIndex &&
  19726. srcIndex.count > geometryInfo.reservedIndexCount ||
  19727. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  19728. ) {
  19729. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  19730. }
  19731. // copy geometry buffer data over
  19732. const vertexStart = geometryInfo.vertexStart;
  19733. const reservedVertexCount = geometryInfo.reservedVertexCount;
  19734. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  19735. for ( const attributeName in batchGeometry.attributes ) {
  19736. // copy attribute data
  19737. const srcAttribute = geometry.getAttribute( attributeName );
  19738. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19739. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19740. // fill the rest in with zeroes
  19741. const itemSize = srcAttribute.itemSize;
  19742. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  19743. const index = vertexStart + i;
  19744. for ( let c = 0; c < itemSize; c ++ ) {
  19745. dstAttribute.setComponent( index, c, 0 );
  19746. }
  19747. }
  19748. dstAttribute.needsUpdate = true;
  19749. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  19750. }
  19751. // copy index
  19752. if ( hasIndex ) {
  19753. const indexStart = geometryInfo.indexStart;
  19754. const reservedIndexCount = geometryInfo.reservedIndexCount;
  19755. geometryInfo.indexCount = geometry.getIndex().count;
  19756. // copy index data over
  19757. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19758. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19759. }
  19760. // fill the rest in with zeroes
  19761. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  19762. dstIndex.setX( indexStart + i, vertexStart );
  19763. }
  19764. dstIndex.needsUpdate = true;
  19765. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  19766. }
  19767. // update the draw range
  19768. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19769. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  19770. // store the bounding boxes
  19771. geometryInfo.boundingBox = null;
  19772. if ( geometry.boundingBox !== null ) {
  19773. geometryInfo.boundingBox = geometry.boundingBox.clone();
  19774. }
  19775. geometryInfo.boundingSphere = null;
  19776. if ( geometry.boundingSphere !== null ) {
  19777. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  19778. }
  19779. this._visibilityChanged = true;
  19780. return geometryId;
  19781. }
  19782. /**
  19783. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  19784. * this geometry will also be removed as a side effect.
  19785. *
  19786. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  19787. * @return {BatchedMesh} A reference to this batched mesh.
  19788. */
  19789. deleteGeometry( geometryId ) {
  19790. const geometryInfoList = this._geometryInfo;
  19791. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19792. return this;
  19793. }
  19794. // delete any instances associated with this geometry
  19795. const instanceInfo = this._instanceInfo;
  19796. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19797. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  19798. this.deleteInstance( i );
  19799. }
  19800. }
  19801. geometryInfoList[ geometryId ].active = false;
  19802. this._availableGeometryIds.push( geometryId );
  19803. this._visibilityChanged = true;
  19804. return this;
  19805. }
  19806. /**
  19807. * Deletes an existing instance from the batch using the given ID.
  19808. *
  19809. * @param {number} instanceId - The ID of the instance to remove from the batch.
  19810. * @return {BatchedMesh} A reference to this batched mesh.
  19811. */
  19812. deleteInstance( instanceId ) {
  19813. this.validateInstanceId( instanceId );
  19814. this._instanceInfo[ instanceId ].active = false;
  19815. this._availableInstanceIds.push( instanceId );
  19816. this._visibilityChanged = true;
  19817. return this;
  19818. }
  19819. /**
  19820. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  19821. * previously deleted geometry, freeing up space to add new geometry.
  19822. *
  19823. * @return {BatchedMesh} A reference to this batched mesh.
  19824. */
  19825. optimize() {
  19826. // track the next indices to copy data to
  19827. let nextVertexStart = 0;
  19828. let nextIndexStart = 0;
  19829. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  19830. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  19831. const geometryInfoList = this._geometryInfo;
  19832. const indices = geometryInfoList
  19833. .map( ( e, i ) => i )
  19834. .sort( ( a, b ) => {
  19835. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  19836. } );
  19837. const geometry = this.geometry;
  19838. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  19839. // if a geometry range is inactive then don't copy anything
  19840. const index = indices[ i ];
  19841. const geometryInfo = geometryInfoList[ index ];
  19842. if ( geometryInfo.active === false ) {
  19843. continue;
  19844. }
  19845. // if a geometry contains an index buffer then shift it, as well
  19846. if ( geometry.index !== null ) {
  19847. if ( geometryInfo.indexStart !== nextIndexStart ) {
  19848. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  19849. const index = geometry.index;
  19850. const array = index.array;
  19851. // shift the index pointers based on how the vertex data will shift
  19852. // adjusting the index must happen first so the original vertex start value is available
  19853. const elementDelta = nextVertexStart - vertexStart;
  19854. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  19855. array[ j ] = array[ j ] + elementDelta;
  19856. }
  19857. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  19858. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  19859. index.needsUpdate = true;
  19860. geometryInfo.indexStart = nextIndexStart;
  19861. }
  19862. nextIndexStart += geometryInfo.reservedIndexCount;
  19863. }
  19864. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  19865. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  19866. const { vertexStart, reservedVertexCount } = geometryInfo;
  19867. const attributes = geometry.attributes;
  19868. for ( const key in attributes ) {
  19869. const attribute = attributes[ key ];
  19870. const { array, itemSize } = attribute;
  19871. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  19872. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  19873. attribute.needsUpdate = true;
  19874. }
  19875. geometryInfo.vertexStart = nextVertexStart;
  19876. }
  19877. nextVertexStart += geometryInfo.reservedVertexCount;
  19878. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19879. }
  19880. this._nextIndexStart = nextIndexStart;
  19881. this._nextVertexStart = nextVertexStart;
  19882. this._visibilityChanged = true;
  19883. return this;
  19884. }
  19885. /**
  19886. * Returns the bounding box for the given geometry.
  19887. *
  19888. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  19889. * @param {Box3} target - The target object that is used to store the method's result.
  19890. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  19891. */
  19892. getBoundingBoxAt( geometryId, target ) {
  19893. if ( geometryId >= this._geometryCount ) {
  19894. return null;
  19895. }
  19896. // compute bounding box
  19897. const geometry = this.geometry;
  19898. const geometryInfo = this._geometryInfo[ geometryId ];
  19899. if ( geometryInfo.boundingBox === null ) {
  19900. const box = new Box3();
  19901. const index = geometry.index;
  19902. const position = geometry.attributes.position;
  19903. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19904. let iv = i;
  19905. if ( index ) {
  19906. iv = index.getX( iv );
  19907. }
  19908. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19909. }
  19910. geometryInfo.boundingBox = box;
  19911. }
  19912. target.copy( geometryInfo.boundingBox );
  19913. return target;
  19914. }
  19915. /**
  19916. * Returns the bounding sphere for the given geometry.
  19917. *
  19918. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  19919. * @param {Sphere} target - The target object that is used to store the method's result.
  19920. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  19921. */
  19922. getBoundingSphereAt( geometryId, target ) {
  19923. if ( geometryId >= this._geometryCount ) {
  19924. return null;
  19925. }
  19926. // compute bounding sphere
  19927. const geometry = this.geometry;
  19928. const geometryInfo = this._geometryInfo[ geometryId ];
  19929. if ( geometryInfo.boundingSphere === null ) {
  19930. const sphere = new Sphere();
  19931. this.getBoundingBoxAt( geometryId, _box$1 );
  19932. _box$1.getCenter( sphere.center );
  19933. const index = geometry.index;
  19934. const position = geometry.attributes.position;
  19935. let maxRadiusSq = 0;
  19936. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19937. let iv = i;
  19938. if ( index ) {
  19939. iv = index.getX( iv );
  19940. }
  19941. _vector$5.fromBufferAttribute( position, iv );
  19942. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19943. }
  19944. sphere.radius = Math.sqrt( maxRadiusSq );
  19945. geometryInfo.boundingSphere = sphere;
  19946. }
  19947. target.copy( geometryInfo.boundingSphere );
  19948. return target;
  19949. }
  19950. /**
  19951. * Sets the given local transformation matrix to the defined instance.
  19952. * Negatively scaled matrices are not supported.
  19953. *
  19954. * @param {number} instanceId - The ID of an instance to set the matrix of.
  19955. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  19956. * @return {BatchedMesh} A reference to this batched mesh.
  19957. */
  19958. setMatrixAt( instanceId, matrix ) {
  19959. this.validateInstanceId( instanceId );
  19960. const matricesTexture = this._matricesTexture;
  19961. const matricesArray = this._matricesTexture.image.data;
  19962. matrix.toArray( matricesArray, instanceId * 16 );
  19963. matricesTexture.needsUpdate = true;
  19964. return this;
  19965. }
  19966. /**
  19967. * Returns the local transformation matrix of the defined instance.
  19968. *
  19969. * @param {number} instanceId - The ID of an instance to get the matrix of.
  19970. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19971. * @return {Matrix4} The instance's local transformation matrix.
  19972. */
  19973. getMatrixAt( instanceId, matrix ) {
  19974. this.validateInstanceId( instanceId );
  19975. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  19976. }
  19977. /**
  19978. * Sets the given color to the defined instance.
  19979. *
  19980. * @param {number} instanceId - The ID of an instance to set the color of.
  19981. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  19982. * @return {BatchedMesh} A reference to this batched mesh.
  19983. */
  19984. setColorAt( instanceId, color ) {
  19985. this.validateInstanceId( instanceId );
  19986. if ( this._colorsTexture === null ) {
  19987. this._initColorsTexture();
  19988. }
  19989. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  19990. this._colorsTexture.needsUpdate = true;
  19991. return this;
  19992. }
  19993. /**
  19994. * Returns the color of the defined instance.
  19995. *
  19996. * @param {number} instanceId - The ID of an instance to get the color of.
  19997. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  19998. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  19999. */
  20000. getColorAt( instanceId, color ) {
  20001. this.validateInstanceId( instanceId );
  20002. if ( this._colorsTexture === null ) {
  20003. if ( color.isVector4 ) {
  20004. return color.set( 1, 1, 1, 1 );
  20005. } else {
  20006. return color.setRGB( 1, 1, 1 );
  20007. }
  20008. } else {
  20009. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20010. }
  20011. }
  20012. /**
  20013. * Sets the visibility of the instance.
  20014. *
  20015. * @param {number} instanceId - The id of the instance to set the visibility of.
  20016. * @param {boolean} visible - Whether the instance is visible or not.
  20017. * @return {BatchedMesh} A reference to this batched mesh.
  20018. */
  20019. setVisibleAt( instanceId, visible ) {
  20020. this.validateInstanceId( instanceId );
  20021. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20022. return this;
  20023. }
  20024. this._instanceInfo[ instanceId ].visible = visible;
  20025. this._visibilityChanged = true;
  20026. return this;
  20027. }
  20028. /**
  20029. * Returns the visibility state of the defined instance.
  20030. *
  20031. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20032. * @return {boolean} Whether the instance is visible or not.
  20033. */
  20034. getVisibleAt( instanceId ) {
  20035. this.validateInstanceId( instanceId );
  20036. return this._instanceInfo[ instanceId ].visible;
  20037. }
  20038. /**
  20039. * Sets the geometry ID of the instance at the given index.
  20040. *
  20041. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20042. * @param {number} geometryId - The geometry ID to be use by the instance.
  20043. * @return {BatchedMesh} A reference to this batched mesh.
  20044. */
  20045. setGeometryIdAt( instanceId, geometryId ) {
  20046. this.validateInstanceId( instanceId );
  20047. this.validateGeometryId( geometryId );
  20048. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20049. return this;
  20050. }
  20051. /**
  20052. * Returns the geometry ID of the defined instance.
  20053. *
  20054. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20055. * @return {number} The instance's geometry ID.
  20056. */
  20057. getGeometryIdAt( instanceId ) {
  20058. this.validateInstanceId( instanceId );
  20059. return this._instanceInfo[ instanceId ].geometryIndex;
  20060. }
  20061. /**
  20062. * Get the range representing the subset of triangles related to the attached geometry,
  20063. * indicating the starting offset and count, or `null` if invalid.
  20064. *
  20065. * @param {number} geometryId - The id of the geometry to get the range of.
  20066. * @param {Object} [target] - The target object that is used to store the method's result.
  20067. * @return {{
  20068. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20069. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20070. * start:number,count:number
  20071. * }} The result object with range data.
  20072. */
  20073. getGeometryRangeAt( geometryId, target = {} ) {
  20074. this.validateGeometryId( geometryId );
  20075. const geometryInfo = this._geometryInfo[ geometryId ];
  20076. target.vertexStart = geometryInfo.vertexStart;
  20077. target.vertexCount = geometryInfo.vertexCount;
  20078. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20079. target.indexStart = geometryInfo.indexStart;
  20080. target.indexCount = geometryInfo.indexCount;
  20081. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20082. target.start = geometryInfo.start;
  20083. target.count = geometryInfo.count;
  20084. return target;
  20085. }
  20086. /**
  20087. * Resizes the necessary buffers to support the provided number of instances.
  20088. * If the provided arguments shrink the number of instances but there are not enough
  20089. * unused Ids at the end of the list then an error is thrown.
  20090. *
  20091. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20092. */
  20093. setInstanceCount( maxInstanceCount ) {
  20094. // shrink the available instances as much as possible
  20095. const availableInstanceIds = this._availableInstanceIds;
  20096. const instanceInfo = this._instanceInfo;
  20097. availableInstanceIds.sort( ascIdSort );
  20098. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20099. instanceInfo.pop();
  20100. availableInstanceIds.pop();
  20101. }
  20102. // throw an error if it can't be shrunk to the desired size
  20103. if ( maxInstanceCount < instanceInfo.length ) {
  20104. throw new Error( `THREE.BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20105. }
  20106. // copy the multi draw counts
  20107. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20108. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20109. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20110. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20111. this._multiDrawCounts = multiDrawCounts;
  20112. this._multiDrawStarts = multiDrawStarts;
  20113. this._maxInstanceCount = maxInstanceCount;
  20114. // update texture data for instance sampling
  20115. const indirectTexture = this._indirectTexture;
  20116. const matricesTexture = this._matricesTexture;
  20117. const colorsTexture = this._colorsTexture;
  20118. indirectTexture.dispose();
  20119. this._initIndirectTexture();
  20120. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20121. matricesTexture.dispose();
  20122. this._initMatricesTexture();
  20123. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20124. if ( colorsTexture ) {
  20125. colorsTexture.dispose();
  20126. this._initColorsTexture();
  20127. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20128. }
  20129. }
  20130. /**
  20131. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20132. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20133. * end of the geometry attributes then an error is thrown.
  20134. *
  20135. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20136. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20137. */
  20138. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20139. // Check if we can shrink to the requested vertex attribute size
  20140. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20141. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20142. if ( requiredVertexLength > maxVertexCount ) {
  20143. throw new Error( `THREE.BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20144. }
  20145. // Check if we can shrink to the requested index attribute size
  20146. if ( this.geometry.index ) {
  20147. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20148. if ( requiredIndexLength > maxIndexCount ) {
  20149. throw new Error( `THREE.BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20150. }
  20151. }
  20152. //
  20153. // dispose of the previous geometry
  20154. const oldGeometry = this.geometry;
  20155. oldGeometry.dispose();
  20156. // recreate the geometry needed based on the previous variant
  20157. this._maxVertexCount = maxVertexCount;
  20158. this._maxIndexCount = maxIndexCount;
  20159. if ( this._geometryInitialized ) {
  20160. this._geometryInitialized = false;
  20161. this.geometry = new BufferGeometry();
  20162. this._initializeGeometry( oldGeometry );
  20163. }
  20164. // copy data from the previous geometry
  20165. const geometry = this.geometry;
  20166. if ( oldGeometry.index ) {
  20167. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20168. }
  20169. for ( const key in oldGeometry.attributes ) {
  20170. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20171. }
  20172. }
  20173. raycast( raycaster, intersects ) {
  20174. const instanceInfo = this._instanceInfo;
  20175. const geometryInfoList = this._geometryInfo;
  20176. const matrixWorld = this.matrixWorld;
  20177. const batchGeometry = this.geometry;
  20178. // iterate over each geometry
  20179. _mesh.material = this.material;
  20180. _mesh.geometry.index = batchGeometry.index;
  20181. _mesh.geometry.attributes = batchGeometry.attributes;
  20182. if ( _mesh.geometry.boundingBox === null ) {
  20183. _mesh.geometry.boundingBox = new Box3();
  20184. }
  20185. if ( _mesh.geometry.boundingSphere === null ) {
  20186. _mesh.geometry.boundingSphere = new Sphere();
  20187. }
  20188. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20189. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20190. continue;
  20191. }
  20192. const geometryId = instanceInfo[ i ].geometryIndex;
  20193. const geometryInfo = geometryInfoList[ geometryId ];
  20194. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20195. // get the intersects
  20196. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20197. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20198. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20199. _mesh.raycast( raycaster, _batchIntersects );
  20200. // add batch id to the intersects
  20201. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20202. const intersect = _batchIntersects[ j ];
  20203. intersect.object = this;
  20204. intersect.batchId = i;
  20205. intersects.push( intersect );
  20206. }
  20207. _batchIntersects.length = 0;
  20208. }
  20209. _mesh.material = null;
  20210. _mesh.geometry.index = null;
  20211. _mesh.geometry.attributes = {};
  20212. _mesh.geometry.setDrawRange( 0, Infinity );
  20213. }
  20214. copy( source ) {
  20215. super.copy( source );
  20216. this.geometry = source.geometry.clone();
  20217. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20218. this.sortObjects = source.sortObjects;
  20219. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20220. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20221. this._geometryInfo = source._geometryInfo.map( info => ( {
  20222. ...info,
  20223. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20224. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20225. } ) );
  20226. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20227. this._availableInstanceIds = source._availableInstanceIds.slice();
  20228. this._availableGeometryIds = source._availableGeometryIds.slice();
  20229. this._nextIndexStart = source._nextIndexStart;
  20230. this._nextVertexStart = source._nextVertexStart;
  20231. this._geometryCount = source._geometryCount;
  20232. this._maxInstanceCount = source._maxInstanceCount;
  20233. this._maxVertexCount = source._maxVertexCount;
  20234. this._maxIndexCount = source._maxIndexCount;
  20235. this._geometryInitialized = source._geometryInitialized;
  20236. this._multiDrawCounts = source._multiDrawCounts.slice();
  20237. this._multiDrawStarts = source._multiDrawStarts.slice();
  20238. this._indirectTexture = source._indirectTexture.clone();
  20239. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20240. this._matricesTexture = source._matricesTexture.clone();
  20241. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20242. if ( this._colorsTexture !== null ) {
  20243. this._colorsTexture = source._colorsTexture.clone();
  20244. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20245. }
  20246. return this;
  20247. }
  20248. /**
  20249. * Frees the GPU-related resources allocated by this instance. Call this
  20250. * method whenever this instance is no longer used in your app.
  20251. */
  20252. dispose() {
  20253. // Assuming the geometry is not shared with other meshes
  20254. this.geometry.dispose();
  20255. this._matricesTexture.dispose();
  20256. this._matricesTexture = null;
  20257. this._indirectTexture.dispose();
  20258. this._indirectTexture = null;
  20259. if ( this._colorsTexture !== null ) {
  20260. this._colorsTexture.dispose();
  20261. this._colorsTexture = null;
  20262. }
  20263. }
  20264. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20265. // if visibility has not changed and frustum culling and object sorting is not required
  20266. // then skip iterating over all items
  20267. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20268. return;
  20269. }
  20270. // the indexed version of the multi draw function requires specifying the start
  20271. // offset in bytes.
  20272. const index = geometry.getIndex();
  20273. let bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20274. // the "wireframe" attribute implicitly creates a line attribute in the renderer, which is double
  20275. // the vertices to draw (3 lines per triangle) so we multiply the draw counts / starts and make
  20276. // assumptions about the index buffer byte size.
  20277. let multiDrawMultiplier = 1;
  20278. if ( material.wireframe ) {
  20279. multiDrawMultiplier = 2;
  20280. bytesPerElement = geometry.attributes.position.count > 65535 ? 4 : 2;
  20281. }
  20282. const instanceInfo = this._instanceInfo;
  20283. const multiDrawStarts = this._multiDrawStarts;
  20284. const multiDrawCounts = this._multiDrawCounts;
  20285. const geometryInfoList = this._geometryInfo;
  20286. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20287. const indirectTexture = this._indirectTexture;
  20288. const indirectArray = indirectTexture.image.data;
  20289. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20290. // prepare the frustum in the local frame
  20291. if ( perObjectFrustumCulled ) {
  20292. if ( camera.isArrayCamera ) {
  20293. frustum.setFromArrayCamera( camera );
  20294. } else {
  20295. _matrix$1
  20296. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20297. .multiply( this.matrixWorld );
  20298. frustum.setFromProjectionMatrix(
  20299. _matrix$1,
  20300. camera.coordinateSystem,
  20301. camera.reversedDepth
  20302. );
  20303. }
  20304. }
  20305. let multiDrawCount = 0;
  20306. if ( this.sortObjects ) {
  20307. // get the camera position in the local frame
  20308. _matrix$1.copy( this.matrixWorld ).invert();
  20309. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20310. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20311. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20312. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20313. const geometryId = instanceInfo[ i ].geometryIndex;
  20314. // get the bounds in world space
  20315. this.getMatrixAt( i, _matrix$1 );
  20316. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20317. // determine whether the batched geometry is within the frustum
  20318. let culled = false;
  20319. if ( perObjectFrustumCulled ) {
  20320. culled = ! frustum.intersectsSphere( _sphere$2 );
  20321. }
  20322. if ( ! culled ) {
  20323. // get the distance from camera used for sorting
  20324. const geometryInfo = geometryInfoList[ geometryId ];
  20325. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20326. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20327. }
  20328. }
  20329. }
  20330. // Sort the draw ranges and prep for rendering
  20331. const list = _renderList.list;
  20332. const customSort = this.customSort;
  20333. if ( customSort === null ) {
  20334. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20335. } else {
  20336. customSort.call( this, list, camera );
  20337. }
  20338. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20339. const item = list[ i ];
  20340. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement * multiDrawMultiplier;
  20341. multiDrawCounts[ multiDrawCount ] = item.count * multiDrawMultiplier;
  20342. indirectArray[ multiDrawCount ] = item.index;
  20343. multiDrawCount ++;
  20344. }
  20345. _renderList.reset();
  20346. } else {
  20347. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20348. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20349. const geometryId = instanceInfo[ i ].geometryIndex;
  20350. // determine whether the batched geometry is within the frustum
  20351. let culled = false;
  20352. if ( perObjectFrustumCulled ) {
  20353. // get the bounds in world space
  20354. this.getMatrixAt( i, _matrix$1 );
  20355. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20356. culled = ! frustum.intersectsSphere( _sphere$2 );
  20357. }
  20358. if ( ! culled ) {
  20359. const geometryInfo = geometryInfoList[ geometryId ];
  20360. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement * multiDrawMultiplier;
  20361. multiDrawCounts[ multiDrawCount ] = geometryInfo.count * multiDrawMultiplier;
  20362. indirectArray[ multiDrawCount ] = i;
  20363. multiDrawCount ++;
  20364. }
  20365. }
  20366. }
  20367. }
  20368. indirectTexture.needsUpdate = true;
  20369. this._multiDrawCount = multiDrawCount;
  20370. this._visibilityChanged = false;
  20371. }
  20372. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20373. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20374. }
  20375. }
  20376. /**
  20377. * A material for rendering line primitives.
  20378. *
  20379. * Materials define the appearance of renderable 3D objects.
  20380. *
  20381. * ```js
  20382. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20383. * ```
  20384. *
  20385. * @augments Material
  20386. */
  20387. class LineBasicMaterial extends Material {
  20388. /**
  20389. * Constructs a new line basic material.
  20390. *
  20391. * @param {Object} [parameters] - An object with one or more properties
  20392. * defining the material's appearance. Any property of the material
  20393. * (including any property from inherited materials) can be passed
  20394. * in here. Color values can be passed any type of value accepted
  20395. * by {@link Color#set}.
  20396. */
  20397. constructor( parameters ) {
  20398. super();
  20399. /**
  20400. * This flag can be used for type testing.
  20401. *
  20402. * @type {boolean}
  20403. * @readonly
  20404. * @default true
  20405. */
  20406. this.isLineBasicMaterial = true;
  20407. this.type = 'LineBasicMaterial';
  20408. /**
  20409. * Color of the material.
  20410. *
  20411. * @type {Color}
  20412. * @default (1,1,1)
  20413. */
  20414. this.color = new Color( 0xffffff );
  20415. /**
  20416. * Sets the color of the lines using data from a texture. The texture map
  20417. * color is modulated by the diffuse `color`.
  20418. *
  20419. * `map` represents color data, and the texture must be assigned a
  20420. * {@link Texture#colorSpace}. Most `map` textures set
  20421. * `texture.colorSpace = SRGBColorSpace`.
  20422. *
  20423. * @type {?Texture}
  20424. * @default null
  20425. */
  20426. this.map = null;
  20427. /**
  20428. * Controls line thickness or lines.
  20429. *
  20430. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20431. * ignore this setting and always render line primitives with a
  20432. * width of one pixel.
  20433. *
  20434. * @type {number}
  20435. * @default 1
  20436. */
  20437. this.linewidth = 1;
  20438. /**
  20439. * Defines appearance of line ends.
  20440. *
  20441. * Can only be used with {@link SVGRenderer}.
  20442. *
  20443. * @type {('butt'|'round'|'square')}
  20444. * @default 'round'
  20445. */
  20446. this.linecap = 'round';
  20447. /**
  20448. * Defines appearance of line joints.
  20449. *
  20450. * Can only be used with {@link SVGRenderer}.
  20451. *
  20452. * @type {('round'|'bevel'|'miter')}
  20453. * @default 'round'
  20454. */
  20455. this.linejoin = 'round';
  20456. /**
  20457. * Whether the material is affected by fog or not.
  20458. *
  20459. * @type {boolean}
  20460. * @default true
  20461. */
  20462. this.fog = true;
  20463. this.setValues( parameters );
  20464. }
  20465. copy( source ) {
  20466. super.copy( source );
  20467. this.color.copy( source.color );
  20468. this.map = source.map;
  20469. this.linewidth = source.linewidth;
  20470. this.linecap = source.linecap;
  20471. this.linejoin = source.linejoin;
  20472. this.fog = source.fog;
  20473. return this;
  20474. }
  20475. }
  20476. const _vStart = /*@__PURE__*/ new Vector3();
  20477. const _vEnd = /*@__PURE__*/ new Vector3();
  20478. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20479. const _ray$1 = /*@__PURE__*/ new Ray();
  20480. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20481. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20482. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20483. /**
  20484. * A continuous line. The line are rendered by connecting consecutive
  20485. * vertices with straight lines.
  20486. *
  20487. * ```js
  20488. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20489. *
  20490. * const points = [];
  20491. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20492. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20493. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20494. *
  20495. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20496. *
  20497. * const line = new THREE.Line( geometry, material );
  20498. * scene.add( line );
  20499. * ```
  20500. *
  20501. * @augments Object3D
  20502. */
  20503. class Line extends Object3D {
  20504. /**
  20505. * Constructs a new line.
  20506. *
  20507. * @param {BufferGeometry} [geometry] - The line geometry.
  20508. * @param {Material|Array<Material>} [material] - The line material.
  20509. */
  20510. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20511. super();
  20512. /**
  20513. * This flag can be used for type testing.
  20514. *
  20515. * @type {boolean}
  20516. * @readonly
  20517. * @default true
  20518. */
  20519. this.isLine = true;
  20520. this.type = 'Line';
  20521. /**
  20522. * The line geometry.
  20523. *
  20524. * @type {BufferGeometry}
  20525. */
  20526. this.geometry = geometry;
  20527. /**
  20528. * The line material.
  20529. *
  20530. * @type {Material|Array<Material>}
  20531. * @default LineBasicMaterial
  20532. */
  20533. this.material = material;
  20534. /**
  20535. * A dictionary representing the morph targets in the geometry. The key is the
  20536. * morph targets name, the value its attribute index. This member is `undefined`
  20537. * by default and only set when morph targets are detected in the geometry.
  20538. *
  20539. * @type {Object<string,number>|undefined}
  20540. * @default undefined
  20541. */
  20542. this.morphTargetDictionary = undefined;
  20543. /**
  20544. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20545. * is applied. This member is `undefined` by default and only set when morph targets are
  20546. * detected in the geometry.
  20547. *
  20548. * @type {Array<number>|undefined}
  20549. * @default undefined
  20550. */
  20551. this.morphTargetInfluences = undefined;
  20552. this.updateMorphTargets();
  20553. }
  20554. copy( source, recursive ) {
  20555. super.copy( source, recursive );
  20556. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20557. this.geometry = source.geometry;
  20558. return this;
  20559. }
  20560. /**
  20561. * Computes an array of distance values which are necessary for rendering dashed lines.
  20562. * For each vertex in the geometry, the method calculates the cumulative length from the
  20563. * current point to the very beginning of the line.
  20564. *
  20565. * @return {Line} A reference to this line.
  20566. */
  20567. computeLineDistances() {
  20568. const geometry = this.geometry;
  20569. // we assume non-indexed geometry
  20570. if ( geometry.index === null ) {
  20571. const positionAttribute = geometry.attributes.position;
  20572. const lineDistances = [ 0 ];
  20573. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20574. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20575. _vEnd.fromBufferAttribute( positionAttribute, i );
  20576. lineDistances[ i ] = lineDistances[ i - 1 ];
  20577. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20578. }
  20579. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20580. } else {
  20581. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20582. }
  20583. return this;
  20584. }
  20585. /**
  20586. * Computes intersection points between a casted ray and this line.
  20587. *
  20588. * @param {Raycaster} raycaster - The raycaster.
  20589. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20590. */
  20591. raycast( raycaster, intersects ) {
  20592. const geometry = this.geometry;
  20593. const matrixWorld = this.matrixWorld;
  20594. const threshold = raycaster.params.Line.threshold;
  20595. const drawRange = geometry.drawRange;
  20596. // Checking boundingSphere distance to ray
  20597. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20598. _sphere$1.copy( geometry.boundingSphere );
  20599. _sphere$1.applyMatrix4( matrixWorld );
  20600. _sphere$1.radius += threshold;
  20601. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20602. //
  20603. _inverseMatrix$1.copy( matrixWorld ).invert();
  20604. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20605. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20606. const localThresholdSq = localThreshold * localThreshold;
  20607. const step = this.isLineSegments ? 2 : 1;
  20608. const index = geometry.index;
  20609. const attributes = geometry.attributes;
  20610. const positionAttribute = attributes.position;
  20611. if ( index !== null ) {
  20612. const start = Math.max( 0, drawRange.start );
  20613. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20614. for ( let i = start, l = end - 1; i < l; i += step ) {
  20615. const a = index.getX( i );
  20616. const b = index.getX( i + 1 );
  20617. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  20618. if ( intersect ) {
  20619. intersects.push( intersect );
  20620. }
  20621. }
  20622. if ( this.isLineLoop ) {
  20623. const a = index.getX( end - 1 );
  20624. const b = index.getX( start );
  20625. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  20626. if ( intersect ) {
  20627. intersects.push( intersect );
  20628. }
  20629. }
  20630. } else {
  20631. const start = Math.max( 0, drawRange.start );
  20632. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20633. for ( let i = start, l = end - 1; i < l; i += step ) {
  20634. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  20635. if ( intersect ) {
  20636. intersects.push( intersect );
  20637. }
  20638. }
  20639. if ( this.isLineLoop ) {
  20640. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  20641. if ( intersect ) {
  20642. intersects.push( intersect );
  20643. }
  20644. }
  20645. }
  20646. }
  20647. /**
  20648. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  20649. * to make sure existing morph targets can influence this 3D object.
  20650. */
  20651. updateMorphTargets() {
  20652. const geometry = this.geometry;
  20653. const morphAttributes = geometry.morphAttributes;
  20654. const keys = Object.keys( morphAttributes );
  20655. if ( keys.length > 0 ) {
  20656. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20657. if ( morphAttribute !== undefined ) {
  20658. this.morphTargetInfluences = [];
  20659. this.morphTargetDictionary = {};
  20660. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20661. const name = morphAttribute[ m ].name || String( m );
  20662. this.morphTargetInfluences.push( 0 );
  20663. this.morphTargetDictionary[ name ] = m;
  20664. }
  20665. }
  20666. }
  20667. }
  20668. }
  20669. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  20670. const positionAttribute = object.geometry.attributes.position;
  20671. _vStart.fromBufferAttribute( positionAttribute, a );
  20672. _vEnd.fromBufferAttribute( positionAttribute, b );
  20673. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20674. if ( distSq > thresholdSq ) return;
  20675. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20676. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20677. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20678. return {
  20679. distance: distance,
  20680. // What do we want? intersection point on the ray or on the segment??
  20681. // point: raycaster.ray.at( distance ),
  20682. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20683. index: i,
  20684. face: null,
  20685. faceIndex: null,
  20686. barycoord: null,
  20687. object: object
  20688. };
  20689. }
  20690. const _start = /*@__PURE__*/ new Vector3();
  20691. const _end = /*@__PURE__*/ new Vector3();
  20692. /**
  20693. * A series of lines drawn between pairs of vertices.
  20694. *
  20695. * @augments Line
  20696. */
  20697. class LineSegments extends Line {
  20698. /**
  20699. * Constructs a new line segments.
  20700. *
  20701. * @param {BufferGeometry} [geometry] - The line geometry.
  20702. * @param {Material|Array<Material>} [material] - The line material.
  20703. */
  20704. constructor( geometry, material ) {
  20705. super( geometry, material );
  20706. /**
  20707. * This flag can be used for type testing.
  20708. *
  20709. * @type {boolean}
  20710. * @readonly
  20711. * @default true
  20712. */
  20713. this.isLineSegments = true;
  20714. this.type = 'LineSegments';
  20715. }
  20716. computeLineDistances() {
  20717. const geometry = this.geometry;
  20718. // we assume non-indexed geometry
  20719. if ( geometry.index === null ) {
  20720. const positionAttribute = geometry.attributes.position;
  20721. const lineDistances = [];
  20722. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20723. _start.fromBufferAttribute( positionAttribute, i );
  20724. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20725. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20726. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20727. }
  20728. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20729. } else {
  20730. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20731. }
  20732. return this;
  20733. }
  20734. }
  20735. /**
  20736. * A continuous line. This is nearly the same as {@link Line} the only difference
  20737. * is that the last vertex is connected with the first vertex in order to close
  20738. * the line to form a loop.
  20739. *
  20740. * @augments Line
  20741. */
  20742. class LineLoop extends Line {
  20743. /**
  20744. * Constructs a new line loop.
  20745. *
  20746. * @param {BufferGeometry} [geometry] - The line geometry.
  20747. * @param {Material|Array<Material>} [material] - The line material.
  20748. */
  20749. constructor( geometry, material ) {
  20750. super( geometry, material );
  20751. /**
  20752. * This flag can be used for type testing.
  20753. *
  20754. * @type {boolean}
  20755. * @readonly
  20756. * @default true
  20757. */
  20758. this.isLineLoop = true;
  20759. this.type = 'LineLoop';
  20760. }
  20761. }
  20762. /**
  20763. * A material for rendering point primitives.
  20764. *
  20765. * Materials define the appearance of renderable 3D objects.
  20766. *
  20767. * ```js
  20768. * const vertices = [];
  20769. *
  20770. * for ( let i = 0; i < 10000; i ++ ) {
  20771. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  20772. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  20773. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  20774. *
  20775. * vertices.push( x, y, z );
  20776. * }
  20777. *
  20778. * const geometry = new THREE.BufferGeometry();
  20779. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  20780. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  20781. * const points = new THREE.Points( geometry, material );
  20782. * scene.add( points );
  20783. * ```
  20784. *
  20785. * @augments Material
  20786. */
  20787. class PointsMaterial extends Material {
  20788. /**
  20789. * Constructs a new points material.
  20790. *
  20791. * @param {Object} [parameters] - An object with one or more properties
  20792. * defining the material's appearance. Any property of the material
  20793. * (including any property from inherited materials) can be passed
  20794. * in here. Color values can be passed any type of value accepted
  20795. * by {@link Color#set}.
  20796. */
  20797. constructor( parameters ) {
  20798. super();
  20799. /**
  20800. * This flag can be used for type testing.
  20801. *
  20802. * @type {boolean}
  20803. * @readonly
  20804. * @default true
  20805. */
  20806. this.isPointsMaterial = true;
  20807. this.type = 'PointsMaterial';
  20808. /**
  20809. * Color of the material.
  20810. *
  20811. * @type {Color}
  20812. * @default (1,1,1)
  20813. */
  20814. this.color = new Color( 0xffffff );
  20815. /**
  20816. * The color map. May optionally include an alpha channel, typically combined
  20817. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  20818. * color is modulated by the diffuse `color`.
  20819. *
  20820. * `map` represents color data, and the texture must be assigned a
  20821. * {@link Texture#colorSpace}. Most `map` textures set
  20822. * `texture.colorSpace = SRGBColorSpace`.
  20823. *
  20824. * @type {?Texture}
  20825. * @default null
  20826. */
  20827. this.map = null;
  20828. /**
  20829. * The alpha map is a grayscale texture that controls the opacity across the
  20830. * surface (black: fully transparent; white: fully opaque).
  20831. *
  20832. * Only the color of the texture is used, ignoring the alpha channel if one
  20833. * exists. For RGB and RGBA textures, the renderer will use the green channel
  20834. * when sampling this texture due to the extra bit of precision provided for
  20835. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  20836. * luminance/alpha textures will also still work as expected.
  20837. *
  20838. * `alphaMap` represents non-color data. Any texture assigned must have
  20839. * `texture.colorSpace = NoColorSpace` (default).
  20840. *
  20841. * @type {?Texture}
  20842. * @default null
  20843. */
  20844. this.alphaMap = null;
  20845. /**
  20846. * Defines the size of the points in pixels.
  20847. *
  20848. * 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).
  20849. *
  20850. * @type {number}
  20851. * @default 1
  20852. */
  20853. this.size = 1;
  20854. /**
  20855. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  20856. *
  20857. * @type {boolean}
  20858. * @default true
  20859. */
  20860. this.sizeAttenuation = true;
  20861. /**
  20862. * Whether the material is affected by fog or not.
  20863. *
  20864. * @type {boolean}
  20865. * @default true
  20866. */
  20867. this.fog = true;
  20868. this.setValues( parameters );
  20869. }
  20870. copy( source ) {
  20871. super.copy( source );
  20872. this.color.copy( source.color );
  20873. this.map = source.map;
  20874. this.alphaMap = source.alphaMap;
  20875. this.size = source.size;
  20876. this.sizeAttenuation = source.sizeAttenuation;
  20877. this.fog = source.fog;
  20878. return this;
  20879. }
  20880. }
  20881. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20882. const _ray = /*@__PURE__*/ new Ray();
  20883. const _sphere = /*@__PURE__*/ new Sphere();
  20884. const _position$3 = /*@__PURE__*/ new Vector3();
  20885. /**
  20886. * A class for displaying points or point clouds.
  20887. *
  20888. * @augments Object3D
  20889. */
  20890. class Points extends Object3D {
  20891. /**
  20892. * Constructs a new point cloud.
  20893. *
  20894. * @param {BufferGeometry} [geometry] - The points geometry.
  20895. * @param {Material|Array<Material>} [material] - The points material.
  20896. */
  20897. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20898. super();
  20899. /**
  20900. * This flag can be used for type testing.
  20901. *
  20902. * @type {boolean}
  20903. * @readonly
  20904. * @default true
  20905. */
  20906. this.isPoints = true;
  20907. this.type = 'Points';
  20908. /**
  20909. * The points geometry.
  20910. *
  20911. * @type {BufferGeometry}
  20912. */
  20913. this.geometry = geometry;
  20914. /**
  20915. * The line material.
  20916. *
  20917. * @type {Material|Array<Material>}
  20918. * @default PointsMaterial
  20919. */
  20920. this.material = material;
  20921. /**
  20922. * A dictionary representing the morph targets in the geometry. The key is the
  20923. * morph targets name, the value its attribute index. This member is `undefined`
  20924. * by default and only set when morph targets are detected in the geometry.
  20925. *
  20926. * @type {Object<string,number>|undefined}
  20927. * @default undefined
  20928. */
  20929. this.morphTargetDictionary = undefined;
  20930. /**
  20931. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20932. * is applied. This member is `undefined` by default and only set when morph targets are
  20933. * detected in the geometry.
  20934. *
  20935. * @type {Array<number>|undefined}
  20936. * @default undefined
  20937. */
  20938. this.morphTargetInfluences = undefined;
  20939. this.updateMorphTargets();
  20940. }
  20941. copy( source, recursive ) {
  20942. super.copy( source, recursive );
  20943. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20944. this.geometry = source.geometry;
  20945. return this;
  20946. }
  20947. /**
  20948. * Computes intersection points between a casted ray and this point cloud.
  20949. *
  20950. * @param {Raycaster} raycaster - The raycaster.
  20951. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20952. */
  20953. raycast( raycaster, intersects ) {
  20954. const geometry = this.geometry;
  20955. const matrixWorld = this.matrixWorld;
  20956. const threshold = raycaster.params.Points.threshold;
  20957. const drawRange = geometry.drawRange;
  20958. // Checking boundingSphere distance to ray
  20959. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20960. _sphere.copy( geometry.boundingSphere );
  20961. _sphere.applyMatrix4( matrixWorld );
  20962. _sphere.radius += threshold;
  20963. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20964. //
  20965. _inverseMatrix.copy( matrixWorld ).invert();
  20966. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20967. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20968. const localThresholdSq = localThreshold * localThreshold;
  20969. const index = geometry.index;
  20970. const attributes = geometry.attributes;
  20971. const positionAttribute = attributes.position;
  20972. if ( index !== null ) {
  20973. const start = Math.max( 0, drawRange.start );
  20974. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20975. for ( let i = start, il = end; i < il; i ++ ) {
  20976. const a = index.getX( i );
  20977. _position$3.fromBufferAttribute( positionAttribute, a );
  20978. testPoint( _position$3, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20979. }
  20980. } else {
  20981. const start = Math.max( 0, drawRange.start );
  20982. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20983. for ( let i = start, l = end; i < l; i ++ ) {
  20984. _position$3.fromBufferAttribute( positionAttribute, i );
  20985. testPoint( _position$3, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20986. }
  20987. }
  20988. }
  20989. /**
  20990. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  20991. * to make sure existing morph targets can influence this 3D object.
  20992. */
  20993. updateMorphTargets() {
  20994. const geometry = this.geometry;
  20995. const morphAttributes = geometry.morphAttributes;
  20996. const keys = Object.keys( morphAttributes );
  20997. if ( keys.length > 0 ) {
  20998. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20999. if ( morphAttribute !== undefined ) {
  21000. this.morphTargetInfluences = [];
  21001. this.morphTargetDictionary = {};
  21002. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21003. const name = morphAttribute[ m ].name || String( m );
  21004. this.morphTargetInfluences.push( 0 );
  21005. this.morphTargetDictionary[ name ] = m;
  21006. }
  21007. }
  21008. }
  21009. }
  21010. }
  21011. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21012. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21013. if ( rayPointDistanceSq < localThresholdSq ) {
  21014. const intersectPoint = new Vector3();
  21015. _ray.closestPointToPoint( point, intersectPoint );
  21016. intersectPoint.applyMatrix4( matrixWorld );
  21017. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21018. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21019. intersects.push( {
  21020. distance: distance,
  21021. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21022. point: intersectPoint,
  21023. index: index,
  21024. face: null,
  21025. faceIndex: null,
  21026. barycoord: null,
  21027. object: object
  21028. } );
  21029. }
  21030. }
  21031. /**
  21032. * A texture for use with a video.
  21033. *
  21034. * ```js
  21035. * // assuming you have created a HTML video element with id="video"
  21036. * const video = document.getElementById( 'video' );
  21037. * const texture = new THREE.VideoTexture( video );
  21038. * ```
  21039. *
  21040. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21041. * set to THREE.SRGBColorSpace.
  21042. *
  21043. * Note: After the initial use of a texture, its dimensions, format, and type
  21044. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21045. *
  21046. * @augments Texture
  21047. */
  21048. class VideoTexture extends Texture {
  21049. /**
  21050. * Constructs a new video texture.
  21051. *
  21052. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21053. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21054. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21055. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21056. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21057. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21058. * @param {number} [format=RGBAFormat] - The texture format.
  21059. * @param {number} [type=UnsignedByteType] - The texture type.
  21060. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21061. */
  21062. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21063. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21064. /**
  21065. * This flag can be used for type testing.
  21066. *
  21067. * @type {boolean}
  21068. * @readonly
  21069. * @default true
  21070. */
  21071. this.isVideoTexture = true;
  21072. /**
  21073. * Whether to generate mipmaps (if possible) for a texture.
  21074. *
  21075. * Overwritten and set to `false` by default.
  21076. *
  21077. * @type {boolean}
  21078. * @default false
  21079. */
  21080. this.generateMipmaps = false;
  21081. /**
  21082. * The video frame request callback identifier, which is a positive integer.
  21083. *
  21084. * Value of 0 represents no scheduled rVFC.
  21085. *
  21086. * @private
  21087. * @type {number}
  21088. */
  21089. this._requestVideoFrameCallbackId = 0;
  21090. const scope = this;
  21091. function updateVideo() {
  21092. scope.needsUpdate = true;
  21093. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21094. }
  21095. if ( 'requestVideoFrameCallback' in video ) {
  21096. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21097. }
  21098. }
  21099. clone() {
  21100. return new this.constructor( this.image ).copy( this );
  21101. }
  21102. /**
  21103. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21104. * to `true` every time a new frame is available.
  21105. *
  21106. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21107. */
  21108. update() {
  21109. const video = this.image;
  21110. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21111. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21112. this.needsUpdate = true;
  21113. }
  21114. }
  21115. dispose() {
  21116. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21117. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21118. this._requestVideoFrameCallbackId = 0;
  21119. }
  21120. super.dispose();
  21121. }
  21122. }
  21123. /**
  21124. * This class can be used as an alternative way to define video data. Instead of using
  21125. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21126. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21127. * video frames are decoded with the WebCodecs API.
  21128. *
  21129. * ```js
  21130. * const texture = new THREE.VideoFrameTexture();
  21131. * texture.setFrame( frame );
  21132. * ```
  21133. *
  21134. * @augments VideoTexture
  21135. */
  21136. class VideoFrameTexture extends VideoTexture {
  21137. /**
  21138. * Constructs a new video frame texture.
  21139. *
  21140. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21141. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21142. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21143. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21144. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21145. * @param {number} [format=RGBAFormat] - The texture format.
  21146. * @param {number} [type=UnsignedByteType] - The texture type.
  21147. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21148. */
  21149. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21150. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21151. /**
  21152. * This flag can be used for type testing.
  21153. *
  21154. * @type {boolean}
  21155. * @readonly
  21156. * @default true
  21157. */
  21158. this.isVideoFrameTexture = true;
  21159. }
  21160. /**
  21161. * This method overwritten with an empty implementation since
  21162. * this type of texture is updated via `setFrame()`.
  21163. */
  21164. update() {}
  21165. clone() {
  21166. return new this.constructor().copy( this ); // restoring Texture.clone()
  21167. }
  21168. /**
  21169. * Sets the current frame of the video. This will automatically update the texture
  21170. * so the data can be used for rendering.
  21171. *
  21172. * @param {VideoFrame} frame - The video frame.
  21173. */
  21174. setFrame( frame ) {
  21175. this.image = frame;
  21176. this.needsUpdate = true;
  21177. }
  21178. }
  21179. /**
  21180. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21181. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21182. * as a texture for further usage.
  21183. *
  21184. * ```js
  21185. * const pixelRatio = window.devicePixelRatio;
  21186. * const textureSize = 128 * pixelRatio;
  21187. *
  21188. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21189. *
  21190. * // calculate start position for copying part of the frame data
  21191. * const vector = new Vector2();
  21192. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21193. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21194. *
  21195. * renderer.render( scene, camera );
  21196. *
  21197. * // copy part of the rendered frame into the framebuffer texture
  21198. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21199. * ```
  21200. *
  21201. * @augments Texture
  21202. */
  21203. class FramebufferTexture extends Texture {
  21204. /**
  21205. * Constructs a new framebuffer texture.
  21206. *
  21207. * @param {number} [width] - The width of the texture.
  21208. * @param {number} [height] - The height of the texture.
  21209. */
  21210. constructor( width, height ) {
  21211. super( { width, height } );
  21212. /**
  21213. * This flag can be used for type testing.
  21214. *
  21215. * @type {boolean}
  21216. * @readonly
  21217. * @default true
  21218. */
  21219. this.isFramebufferTexture = true;
  21220. /**
  21221. * How the texture is sampled when a texel covers more than one pixel.
  21222. *
  21223. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21224. *
  21225. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21226. * @default NearestFilter
  21227. */
  21228. this.magFilter = NearestFilter;
  21229. /**
  21230. * How the texture is sampled when a texel covers less than one pixel.
  21231. *
  21232. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21233. *
  21234. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21235. * @default NearestFilter
  21236. */
  21237. this.minFilter = NearestFilter;
  21238. /**
  21239. * Whether to generate mipmaps (if possible) for a texture.
  21240. *
  21241. * Overwritten and set to `false` by default.
  21242. *
  21243. * @type {boolean}
  21244. * @default false
  21245. */
  21246. this.generateMipmaps = false;
  21247. this.needsUpdate = true;
  21248. }
  21249. }
  21250. /**
  21251. * Creates a texture based on data in compressed form.
  21252. *
  21253. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21254. *
  21255. * @augments Texture
  21256. */
  21257. class CompressedTexture extends Texture {
  21258. /**
  21259. * Constructs a new compressed texture.
  21260. *
  21261. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21262. * the data and dimensions.
  21263. * @param {number} width - The width of the texture.
  21264. * @param {number} height - The height of the texture.
  21265. * @param {number} [format=RGBAFormat] - The texture format.
  21266. * @param {number} [type=UnsignedByteType] - The texture type.
  21267. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21268. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21269. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21270. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21271. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21272. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21273. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21274. */
  21275. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21276. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21277. /**
  21278. * This flag can be used for type testing.
  21279. *
  21280. * @type {boolean}
  21281. * @readonly
  21282. * @default true
  21283. */
  21284. this.isCompressedTexture = true;
  21285. /**
  21286. * The image property of a compressed texture just defines its dimensions.
  21287. *
  21288. * @type {{width:number,height:number}}
  21289. */
  21290. this.image = { width: width, height: height };
  21291. /**
  21292. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21293. *
  21294. * @type {Array<Object>}
  21295. */
  21296. this.mipmaps = mipmaps;
  21297. /**
  21298. * If set to `true`, the texture is flipped along the vertical axis when
  21299. * uploaded to the GPU.
  21300. *
  21301. * Overwritten and set to `false` by default since it is not possible to
  21302. * flip compressed textures.
  21303. *
  21304. * @type {boolean}
  21305. * @default false
  21306. * @readonly
  21307. */
  21308. this.flipY = false;
  21309. /**
  21310. * Whether to generate mipmaps (if possible) for a texture.
  21311. *
  21312. * Overwritten and set to `false` by default since it is not
  21313. * possible to generate mipmaps for compressed data. Mipmaps
  21314. * must be embedded in the compressed texture file.
  21315. *
  21316. * @type {boolean}
  21317. * @default false
  21318. * @readonly
  21319. */
  21320. this.generateMipmaps = false;
  21321. }
  21322. }
  21323. /**
  21324. * Creates a texture 2D array based on data in compressed form.
  21325. *
  21326. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21327. *
  21328. * @augments CompressedTexture
  21329. */
  21330. class CompressedArrayTexture extends CompressedTexture {
  21331. /**
  21332. * Constructs a new compressed array texture.
  21333. *
  21334. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21335. * the data and dimensions.
  21336. * @param {number} width - The width of the texture.
  21337. * @param {number} height - The height of the texture.
  21338. * @param {number} depth - The depth of the texture.
  21339. * @param {number} [format=RGBAFormat] - The min filter value.
  21340. * @param {number} [type=UnsignedByteType] - The min filter value.
  21341. */
  21342. constructor( mipmaps, width, height, depth, format, type ) {
  21343. super( mipmaps, width, height, format, type );
  21344. /**
  21345. * This flag can be used for type testing.
  21346. *
  21347. * @type {boolean}
  21348. * @readonly
  21349. * @default true
  21350. */
  21351. this.isCompressedArrayTexture = true;
  21352. /**
  21353. * The image property of a compressed texture just defines its dimensions.
  21354. *
  21355. * @name CompressedArrayTexture#image
  21356. * @type {{width:number,height:number,depth:number}}
  21357. */
  21358. this.image.depth = depth;
  21359. /**
  21360. * This defines how the texture is wrapped in the depth and corresponds to
  21361. * *W* in UVW mapping.
  21362. *
  21363. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21364. * @default ClampToEdgeWrapping
  21365. */
  21366. this.wrapR = ClampToEdgeWrapping;
  21367. /**
  21368. * A set of all layers which need to be updated in the texture.
  21369. *
  21370. * @type {Set<number>}
  21371. */
  21372. this.layerUpdates = new Set();
  21373. }
  21374. /**
  21375. * Describes that a specific layer of the texture needs to be updated.
  21376. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21377. * entire compressed texture array is sent to the GPU. Marking specific
  21378. * layers will only transmit subsets of all mipmaps associated with a
  21379. * specific depth in the array which is often much more performant.
  21380. *
  21381. * @param {number} layerIndex - The layer index that should be updated.
  21382. */
  21383. addLayerUpdate( layerIndex ) {
  21384. this.layerUpdates.add( layerIndex );
  21385. }
  21386. /**
  21387. * Resets the layer updates registry.
  21388. */
  21389. clearLayerUpdates() {
  21390. this.layerUpdates.clear();
  21391. }
  21392. }
  21393. /**
  21394. * Creates a cube texture based on data in compressed form.
  21395. *
  21396. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21397. *
  21398. * @augments CompressedTexture
  21399. */
  21400. class CompressedCubeTexture extends CompressedTexture {
  21401. /**
  21402. * Constructs a new compressed texture.
  21403. *
  21404. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21405. * @param {number} [format=RGBAFormat] - The texture format.
  21406. * @param {number} [type=UnsignedByteType] - The texture type.
  21407. */
  21408. constructor( images, format, type ) {
  21409. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21410. /**
  21411. * This flag can be used for type testing.
  21412. *
  21413. * @type {boolean}
  21414. * @readonly
  21415. * @default true
  21416. */
  21417. this.isCompressedCubeTexture = true;
  21418. /**
  21419. * This flag can be used for type testing.
  21420. *
  21421. * @type {boolean}
  21422. * @readonly
  21423. * @default true
  21424. */
  21425. this.isCubeTexture = true;
  21426. this.image = images;
  21427. }
  21428. }
  21429. /**
  21430. * Creates a cube texture made up of six images.
  21431. *
  21432. * ```js
  21433. * const loader = new THREE.CubeTextureLoader();
  21434. * loader.setPath( 'textures/cube/pisa/' );
  21435. *
  21436. * const textureCube = loader.load( [
  21437. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  21438. * ] );
  21439. *
  21440. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  21441. * ```
  21442. *
  21443. * @augments Texture
  21444. */
  21445. class CubeTexture extends Texture {
  21446. /**
  21447. * Constructs a new cube texture.
  21448. *
  21449. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  21450. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21451. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21452. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21453. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21454. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21455. * @param {number} [format=RGBAFormat] - The texture format.
  21456. * @param {number} [type=UnsignedByteType] - The texture type.
  21457. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21458. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  21459. */
  21460. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  21461. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21462. /**
  21463. * This flag can be used for type testing.
  21464. *
  21465. * @type {boolean}
  21466. * @readonly
  21467. * @default true
  21468. */
  21469. this.isCubeTexture = true;
  21470. /**
  21471. * If set to `true`, the texture is flipped along the vertical axis when
  21472. * uploaded to the GPU.
  21473. *
  21474. * Overwritten and set to `false` by default.
  21475. *
  21476. * @type {boolean}
  21477. * @default false
  21478. */
  21479. this.flipY = false;
  21480. }
  21481. /**
  21482. * Alias for {@link CubeTexture#image}.
  21483. *
  21484. * @type {Array<Image>}
  21485. */
  21486. get images() {
  21487. return this.image;
  21488. }
  21489. set images( value ) {
  21490. this.image = value;
  21491. }
  21492. }
  21493. /**
  21494. * Creates a texture from a canvas element.
  21495. *
  21496. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21497. * to `true` immediately since a canvas can directly be used for rendering.
  21498. *
  21499. * @augments Texture
  21500. */
  21501. class CanvasTexture extends Texture {
  21502. /**
  21503. * Constructs a new texture.
  21504. *
  21505. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21506. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21507. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21508. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21509. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21510. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21511. * @param {number} [format=RGBAFormat] - The texture format.
  21512. * @param {number} [type=UnsignedByteType] - The texture type.
  21513. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21514. */
  21515. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21516. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21517. /**
  21518. * This flag can be used for type testing.
  21519. *
  21520. * @type {boolean}
  21521. * @readonly
  21522. * @default true
  21523. */
  21524. this.isCanvasTexture = true;
  21525. this.needsUpdate = true;
  21526. }
  21527. }
  21528. /**
  21529. * Creates a texture from an HTML element.
  21530. *
  21531. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21532. * to `true` immediately and listens for the parent canvas's paint events to trigger updates.
  21533. *
  21534. * @augments Texture
  21535. */
  21536. class HTMLTexture extends Texture {
  21537. /**
  21538. * Constructs a new texture.
  21539. *
  21540. * @param {HTMLElement} [element] - The HTML element.
  21541. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21542. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21543. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21544. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21545. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21546. * @param {number} [format=RGBAFormat] - The texture format.
  21547. * @param {number} [type=UnsignedByteType] - The texture type.
  21548. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21549. */
  21550. constructor( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21551. super( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21552. /**
  21553. * This flag can be used for type testing.
  21554. *
  21555. * @type {boolean}
  21556. * @readonly
  21557. * @default true
  21558. */
  21559. this.isHTMLTexture = true;
  21560. this.generateMipmaps = false;
  21561. this.needsUpdate = true;
  21562. const parent = element ? element.parentNode : null;
  21563. if ( parent !== null && 'requestPaint' in parent ) {
  21564. parent.onpaint = () => {
  21565. this.needsUpdate = true;
  21566. };
  21567. parent.requestPaint();
  21568. }
  21569. }
  21570. dispose() {
  21571. const parent = this.image ? this.image.parentNode : null;
  21572. if ( parent !== null && 'onpaint' in parent ) {
  21573. parent.onpaint = null;
  21574. }
  21575. super.dispose();
  21576. }
  21577. }
  21578. /**
  21579. * This class can be used to automatically save the depth information of a
  21580. * rendering into a texture.
  21581. *
  21582. * @augments Texture
  21583. */
  21584. class DepthTexture extends Texture {
  21585. /**
  21586. * Constructs a new depth texture.
  21587. *
  21588. * @param {number} width - The width of the texture.
  21589. * @param {number} height - The height of the texture.
  21590. * @param {number} [type=UnsignedIntType] - The texture type.
  21591. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21592. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21593. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21594. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21595. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21596. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21597. * @param {number} [format=DepthFormat] - The texture format.
  21598. * @param {number} [depth=1] - The depth of the texture.
  21599. */
  21600. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  21601. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21602. throw new Error( 'THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21603. }
  21604. const image = { width: width, height: height, depth: depth };
  21605. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21606. /**
  21607. * This flag can be used for type testing.
  21608. *
  21609. * @type {boolean}
  21610. * @readonly
  21611. * @default true
  21612. */
  21613. this.isDepthTexture = true;
  21614. /**
  21615. * If set to `true`, the texture is flipped along the vertical axis when
  21616. * uploaded to the GPU.
  21617. *
  21618. * Overwritten and set to `false` by default.
  21619. *
  21620. * @type {boolean}
  21621. * @default false
  21622. */
  21623. this.flipY = false;
  21624. /**
  21625. * Whether to generate mipmaps (if possible) for a texture.
  21626. *
  21627. * Overwritten and set to `false` by default.
  21628. *
  21629. * @type {boolean}
  21630. * @default false
  21631. */
  21632. this.generateMipmaps = false;
  21633. /**
  21634. * Code corresponding to the depth compare function.
  21635. *
  21636. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21637. * @default null
  21638. */
  21639. this.compareFunction = null;
  21640. }
  21641. copy( source ) {
  21642. super.copy( source );
  21643. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21644. this.compareFunction = source.compareFunction;
  21645. return this;
  21646. }
  21647. toJSON( meta ) {
  21648. const data = super.toJSON( meta );
  21649. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21650. return data;
  21651. }
  21652. }
  21653. /**
  21654. * This class can be used to automatically save the depth information of a
  21655. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  21656. *
  21657. * @augments DepthTexture
  21658. */
  21659. class CubeDepthTexture extends DepthTexture {
  21660. /**
  21661. * Constructs a new cube depth texture.
  21662. *
  21663. * @param {number} size - The size (width and height) of each cube face.
  21664. * @param {number} [type=UnsignedIntType] - The texture type.
  21665. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21666. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21667. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21668. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  21669. * @param {number} [minFilter=NearestFilter] - The min filter value.
  21670. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21671. * @param {number} [format=DepthFormat] - The texture format.
  21672. */
  21673. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21674. // Create 6 identical image descriptors for the cube faces
  21675. const image = { width: size, height: size, depth: 1 };
  21676. const images = [ image, image, image, image, image, image ];
  21677. // Call DepthTexture constructor with width, height
  21678. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  21679. // Replace the single image with the array of 6 images
  21680. this.image = images;
  21681. /**
  21682. * This flag can be used for type testing.
  21683. *
  21684. * @type {boolean}
  21685. * @readonly
  21686. * @default true
  21687. */
  21688. this.isCubeDepthTexture = true;
  21689. /**
  21690. * Set to true for cube texture handling in WebGLTextures.
  21691. *
  21692. * @type {boolean}
  21693. * @readonly
  21694. * @default true
  21695. */
  21696. this.isCubeTexture = true;
  21697. }
  21698. /**
  21699. * Alias for {@link CubeDepthTexture#image}.
  21700. *
  21701. * @type {Array<Image>}
  21702. */
  21703. get images() {
  21704. return this.image;
  21705. }
  21706. set images( value ) {
  21707. this.image = value;
  21708. }
  21709. }
  21710. /**
  21711. * Represents a texture created externally with the same renderer context.
  21712. *
  21713. * This may be a texture from a protected media stream, device camera feed,
  21714. * or other data feeds like a depth sensor.
  21715. *
  21716. * @augments Texture
  21717. */
  21718. class ExternalTexture extends Texture {
  21719. /**
  21720. * Creates a new raw texture.
  21721. *
  21722. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  21723. */
  21724. constructor( sourceTexture = null ) {
  21725. super();
  21726. /**
  21727. * The external source texture.
  21728. *
  21729. * @type {?(WebGLTexture|GPUTexture)}
  21730. * @default null
  21731. */
  21732. this.sourceTexture = sourceTexture;
  21733. /**
  21734. * This flag can be used for type testing.
  21735. *
  21736. * @type {boolean}
  21737. * @readonly
  21738. * @default true
  21739. */
  21740. this.isExternalTexture = true;
  21741. }
  21742. copy( source ) {
  21743. super.copy( source );
  21744. this.sourceTexture = source.sourceTexture;
  21745. return this;
  21746. }
  21747. }
  21748. /**
  21749. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  21750. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  21751. * of the axes.
  21752. *
  21753. * ```js
  21754. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  21755. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21756. * const cube = new THREE.Mesh( geometry, material );
  21757. * scene.add( cube );
  21758. * ```
  21759. *
  21760. * @augments BufferGeometry
  21761. * @demo scenes/geometry-browser.html#BoxGeometry
  21762. */
  21763. class BoxGeometry extends BufferGeometry {
  21764. /**
  21765. * Constructs a new box geometry.
  21766. *
  21767. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  21768. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  21769. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  21770. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  21771. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  21772. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  21773. */
  21774. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  21775. super();
  21776. this.type = 'BoxGeometry';
  21777. /**
  21778. * Holds the constructor parameters that have been
  21779. * used to generate the geometry. Any modification
  21780. * after instantiation does not change the geometry.
  21781. *
  21782. * @type {Object}
  21783. */
  21784. this.parameters = {
  21785. width: width,
  21786. height: height,
  21787. depth: depth,
  21788. widthSegments: widthSegments,
  21789. heightSegments: heightSegments,
  21790. depthSegments: depthSegments
  21791. };
  21792. const scope = this;
  21793. // segments
  21794. widthSegments = Math.floor( widthSegments );
  21795. heightSegments = Math.floor( heightSegments );
  21796. depthSegments = Math.floor( depthSegments );
  21797. // buffers
  21798. const indices = [];
  21799. const vertices = [];
  21800. const normals = [];
  21801. const uvs = [];
  21802. // helper variables
  21803. let numberOfVertices = 0;
  21804. let groupStart = 0;
  21805. // build each side of the box geometry
  21806. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  21807. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  21808. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  21809. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  21810. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  21811. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  21812. // build geometry
  21813. this.setIndex( indices );
  21814. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21815. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21816. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21817. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  21818. const segmentWidth = width / gridX;
  21819. const segmentHeight = height / gridY;
  21820. const widthHalf = width / 2;
  21821. const heightHalf = height / 2;
  21822. const depthHalf = depth / 2;
  21823. const gridX1 = gridX + 1;
  21824. const gridY1 = gridY + 1;
  21825. let vertexCounter = 0;
  21826. let groupCount = 0;
  21827. const vector = new Vector3();
  21828. // generate vertices, normals and uvs
  21829. for ( let iy = 0; iy < gridY1; iy ++ ) {
  21830. const y = iy * segmentHeight - heightHalf;
  21831. for ( let ix = 0; ix < gridX1; ix ++ ) {
  21832. const x = ix * segmentWidth - widthHalf;
  21833. // set values to correct vector component
  21834. vector[ u ] = x * udir;
  21835. vector[ v ] = y * vdir;
  21836. vector[ w ] = depthHalf;
  21837. // now apply vector to vertex buffer
  21838. vertices.push( vector.x, vector.y, vector.z );
  21839. // set values to correct vector component
  21840. vector[ u ] = 0;
  21841. vector[ v ] = 0;
  21842. vector[ w ] = depth > 0 ? 1 : -1;
  21843. // now apply vector to normal buffer
  21844. normals.push( vector.x, vector.y, vector.z );
  21845. // uvs
  21846. uvs.push( ix / gridX );
  21847. uvs.push( 1 - ( iy / gridY ) );
  21848. // counters
  21849. vertexCounter += 1;
  21850. }
  21851. }
  21852. // indices
  21853. // 1. you need three indices to draw a single face
  21854. // 2. a single segment consists of two faces
  21855. // 3. so we need to generate six (2*3) indices per segment
  21856. for ( let iy = 0; iy < gridY; iy ++ ) {
  21857. for ( let ix = 0; ix < gridX; ix ++ ) {
  21858. const a = numberOfVertices + ix + gridX1 * iy;
  21859. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  21860. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  21861. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  21862. // faces
  21863. indices.push( a, b, d );
  21864. indices.push( b, c, d );
  21865. // increase counter
  21866. groupCount += 6;
  21867. }
  21868. }
  21869. // add a group to the geometry. this will ensure multi material support
  21870. scope.addGroup( groupStart, groupCount, materialIndex );
  21871. // calculate new start value for groups
  21872. groupStart += groupCount;
  21873. // update total number of vertices
  21874. numberOfVertices += vertexCounter;
  21875. }
  21876. }
  21877. copy( source ) {
  21878. super.copy( source );
  21879. this.parameters = Object.assign( {}, source.parameters );
  21880. return this;
  21881. }
  21882. /**
  21883. * Factory method for creating an instance of this class from the given
  21884. * JSON object.
  21885. *
  21886. * @param {Object} data - A JSON object representing the serialized geometry.
  21887. * @return {BoxGeometry} A new instance.
  21888. */
  21889. static fromJSON( data ) {
  21890. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  21891. }
  21892. }
  21893. /**
  21894. * A geometry class for representing a capsule.
  21895. *
  21896. * ```js
  21897. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  21898. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21899. * const capsule = new THREE.Mesh( geometry, material );
  21900. * scene.add( capsule );
  21901. * ```
  21902. *
  21903. * @augments BufferGeometry
  21904. * @demo scenes/geometry-browser.html#CapsuleGeometry
  21905. */
  21906. class CapsuleGeometry extends BufferGeometry {
  21907. /**
  21908. * Constructs a new capsule geometry.
  21909. *
  21910. * @param {number} [radius=1] - Radius of the capsule.
  21911. * @param {number} [height=1] - Height of the middle section.
  21912. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  21913. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  21914. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  21915. */
  21916. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  21917. super();
  21918. this.type = 'CapsuleGeometry';
  21919. /**
  21920. * Holds the constructor parameters that have been
  21921. * used to generate the geometry. Any modification
  21922. * after instantiation does not change the geometry.
  21923. *
  21924. * @type {Object}
  21925. */
  21926. this.parameters = {
  21927. radius: radius,
  21928. height: height,
  21929. capSegments: capSegments,
  21930. radialSegments: radialSegments,
  21931. heightSegments: heightSegments,
  21932. };
  21933. height = Math.max( 0, height );
  21934. capSegments = Math.max( 1, Math.floor( capSegments ) );
  21935. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  21936. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  21937. // buffers
  21938. const indices = [];
  21939. const vertices = [];
  21940. const normals = [];
  21941. const uvs = [];
  21942. // helper variables
  21943. const halfHeight = height / 2;
  21944. const capArcLength = ( Math.PI / 2 ) * radius;
  21945. const cylinderPartLength = height;
  21946. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  21947. const numVerticalSegments = capSegments * 2 + heightSegments;
  21948. const verticesPerRow = radialSegments + 1;
  21949. const normal = new Vector3();
  21950. const vertex = new Vector3();
  21951. // generate vertices, normals, and uvs
  21952. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  21953. let currentArcLength = 0;
  21954. let profileY = 0;
  21955. let profileRadius = 0;
  21956. let normalYComponent = 0;
  21957. if ( iy <= capSegments ) {
  21958. // bottom cap
  21959. const segmentProgress = iy / capSegments;
  21960. const angle = ( segmentProgress * Math.PI ) / 2;
  21961. profileY = - halfHeight - radius * Math.cos( angle );
  21962. profileRadius = radius * Math.sin( angle );
  21963. normalYComponent = - radius * Math.cos( angle );
  21964. currentArcLength = segmentProgress * capArcLength;
  21965. } else if ( iy <= capSegments + heightSegments ) {
  21966. // middle section
  21967. const segmentProgress = ( iy - capSegments ) / heightSegments;
  21968. profileY = - halfHeight + segmentProgress * height;
  21969. profileRadius = radius;
  21970. normalYComponent = 0;
  21971. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  21972. } else {
  21973. // top cap
  21974. const segmentProgress =
  21975. ( iy - capSegments - heightSegments ) / capSegments;
  21976. const angle = ( segmentProgress * Math.PI ) / 2;
  21977. profileY = halfHeight + radius * Math.sin( angle );
  21978. profileRadius = radius * Math.cos( angle );
  21979. normalYComponent = radius * Math.sin( angle );
  21980. currentArcLength =
  21981. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  21982. }
  21983. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  21984. // special case for the poles
  21985. let uOffset = 0;
  21986. if ( iy === 0 ) {
  21987. uOffset = 0.5 / radialSegments;
  21988. } else if ( iy === numVerticalSegments ) {
  21989. uOffset = -0.5 / radialSegments;
  21990. }
  21991. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  21992. const u = ix / radialSegments;
  21993. const theta = u * Math.PI * 2;
  21994. const sinTheta = Math.sin( theta );
  21995. const cosTheta = Math.cos( theta );
  21996. // vertex
  21997. vertex.x = - profileRadius * cosTheta;
  21998. vertex.y = profileY;
  21999. vertex.z = profileRadius * sinTheta;
  22000. vertices.push( vertex.x, vertex.y, vertex.z );
  22001. // normal
  22002. normal.set(
  22003. - profileRadius * cosTheta,
  22004. normalYComponent,
  22005. profileRadius * sinTheta
  22006. );
  22007. normal.normalize();
  22008. normals.push( normal.x, normal.y, normal.z );
  22009. // uv
  22010. uvs.push( u + uOffset, v );
  22011. }
  22012. if ( iy > 0 ) {
  22013. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22014. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22015. const i1 = prevIndexRow + ix;
  22016. const i2 = prevIndexRow + ix + 1;
  22017. const i3 = iy * verticesPerRow + ix;
  22018. const i4 = iy * verticesPerRow + ix + 1;
  22019. indices.push( i1, i2, i3 );
  22020. indices.push( i2, i4, i3 );
  22021. }
  22022. }
  22023. }
  22024. // build geometry
  22025. this.setIndex( indices );
  22026. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22027. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22028. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22029. }
  22030. copy( source ) {
  22031. super.copy( source );
  22032. this.parameters = Object.assign( {}, source.parameters );
  22033. return this;
  22034. }
  22035. /**
  22036. * Factory method for creating an instance of this class from the given
  22037. * JSON object.
  22038. *
  22039. * @param {Object} data - A JSON object representing the serialized geometry.
  22040. * @return {CapsuleGeometry} A new instance.
  22041. */
  22042. static fromJSON( data ) {
  22043. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22044. }
  22045. }
  22046. /**
  22047. * A simple shape of Euclidean geometry. It is constructed from a
  22048. * number of triangular segments that are oriented around a central point and
  22049. * extend as far out as a given radius. It is built counter-clockwise from a
  22050. * start angle and a given central angle. It can also be used to create
  22051. * regular polygons, where the number of segments determines the number of
  22052. * sides.
  22053. *
  22054. * ```js
  22055. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22056. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22057. * const circle = new THREE.Mesh( geometry, material );
  22058. * scene.add( circle )
  22059. * ```
  22060. *
  22061. * @augments BufferGeometry
  22062. * @demo scenes/geometry-browser.html#CircleGeometry
  22063. */
  22064. class CircleGeometry extends BufferGeometry {
  22065. /**
  22066. * Constructs a new circle geometry.
  22067. *
  22068. * @param {number} [radius=1] - Radius of the circle.
  22069. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22070. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22071. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22072. * of the circular sector in radians. The default value results in a complete circle.
  22073. */
  22074. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22075. super();
  22076. this.type = 'CircleGeometry';
  22077. /**
  22078. * Holds the constructor parameters that have been
  22079. * used to generate the geometry. Any modification
  22080. * after instantiation does not change the geometry.
  22081. *
  22082. * @type {Object}
  22083. */
  22084. this.parameters = {
  22085. radius: radius,
  22086. segments: segments,
  22087. thetaStart: thetaStart,
  22088. thetaLength: thetaLength
  22089. };
  22090. segments = Math.max( 3, segments );
  22091. // buffers
  22092. const indices = [];
  22093. const vertices = [];
  22094. const normals = [];
  22095. const uvs = [];
  22096. // helper variables
  22097. const vertex = new Vector3();
  22098. const uv = new Vector2();
  22099. // center point
  22100. vertices.push( 0, 0, 0 );
  22101. normals.push( 0, 0, 1 );
  22102. uvs.push( 0.5, 0.5 );
  22103. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22104. const segment = thetaStart + s / segments * thetaLength;
  22105. // vertex
  22106. vertex.x = radius * Math.cos( segment );
  22107. vertex.y = radius * Math.sin( segment );
  22108. vertices.push( vertex.x, vertex.y, vertex.z );
  22109. // normal
  22110. normals.push( 0, 0, 1 );
  22111. // uvs
  22112. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22113. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22114. uvs.push( uv.x, uv.y );
  22115. }
  22116. // indices
  22117. for ( let i = 1; i <= segments; i ++ ) {
  22118. indices.push( i, i + 1, 0 );
  22119. }
  22120. // build geometry
  22121. this.setIndex( indices );
  22122. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22123. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22124. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22125. }
  22126. copy( source ) {
  22127. super.copy( source );
  22128. this.parameters = Object.assign( {}, source.parameters );
  22129. return this;
  22130. }
  22131. /**
  22132. * Factory method for creating an instance of this class from the given
  22133. * JSON object.
  22134. *
  22135. * @param {Object} data - A JSON object representing the serialized geometry.
  22136. * @return {CircleGeometry} A new instance.
  22137. */
  22138. static fromJSON( data ) {
  22139. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22140. }
  22141. }
  22142. /**
  22143. * A geometry class for representing a cylinder.
  22144. *
  22145. * ```js
  22146. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22147. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22148. * const cylinder = new THREE.Mesh( geometry, material );
  22149. * scene.add( cylinder );
  22150. * ```
  22151. *
  22152. * @augments BufferGeometry
  22153. * @demo scenes/geometry-browser.html#CylinderGeometry
  22154. */
  22155. class CylinderGeometry extends BufferGeometry {
  22156. /**
  22157. * Constructs a new cylinder geometry.
  22158. *
  22159. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22160. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22161. * @param {number} [height=1] - Height of the cylinder.
  22162. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22163. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22164. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22165. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22166. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22167. * The default value results in a complete cylinder.
  22168. */
  22169. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22170. super();
  22171. this.type = 'CylinderGeometry';
  22172. /**
  22173. * Holds the constructor parameters that have been
  22174. * used to generate the geometry. Any modification
  22175. * after instantiation does not change the geometry.
  22176. *
  22177. * @type {Object}
  22178. */
  22179. this.parameters = {
  22180. radiusTop: radiusTop,
  22181. radiusBottom: radiusBottom,
  22182. height: height,
  22183. radialSegments: radialSegments,
  22184. heightSegments: heightSegments,
  22185. openEnded: openEnded,
  22186. thetaStart: thetaStart,
  22187. thetaLength: thetaLength
  22188. };
  22189. const scope = this;
  22190. radialSegments = Math.floor( radialSegments );
  22191. heightSegments = Math.floor( heightSegments );
  22192. // buffers
  22193. const indices = [];
  22194. const vertices = [];
  22195. const normals = [];
  22196. const uvs = [];
  22197. // helper variables
  22198. let index = 0;
  22199. const indexArray = [];
  22200. const halfHeight = height / 2;
  22201. let groupStart = 0;
  22202. // generate geometry
  22203. generateTorso();
  22204. if ( openEnded === false ) {
  22205. if ( radiusTop > 0 ) generateCap( true );
  22206. if ( radiusBottom > 0 ) generateCap( false );
  22207. }
  22208. // build geometry
  22209. this.setIndex( indices );
  22210. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22211. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22212. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22213. function generateTorso() {
  22214. const normal = new Vector3();
  22215. const vertex = new Vector3();
  22216. let groupCount = 0;
  22217. // this will be used to calculate the normal
  22218. const slope = ( radiusBottom - radiusTop ) / height;
  22219. // generate vertices, normals and uvs
  22220. for ( let y = 0; y <= heightSegments; y ++ ) {
  22221. const indexRow = [];
  22222. const v = y / heightSegments;
  22223. // calculate the radius of the current row
  22224. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22225. for ( let x = 0; x <= radialSegments; x ++ ) {
  22226. const u = x / radialSegments;
  22227. const theta = u * thetaLength + thetaStart;
  22228. const sinTheta = Math.sin( theta );
  22229. const cosTheta = Math.cos( theta );
  22230. // vertex
  22231. vertex.x = radius * sinTheta;
  22232. vertex.y = - v * height + halfHeight;
  22233. vertex.z = radius * cosTheta;
  22234. vertices.push( vertex.x, vertex.y, vertex.z );
  22235. // normal
  22236. normal.set( sinTheta, slope, cosTheta ).normalize();
  22237. normals.push( normal.x, normal.y, normal.z );
  22238. // uv
  22239. uvs.push( u, 1 - v );
  22240. // save index of vertex in respective row
  22241. indexRow.push( index ++ );
  22242. }
  22243. // now save vertices of the row in our index array
  22244. indexArray.push( indexRow );
  22245. }
  22246. // generate indices
  22247. for ( let x = 0; x < radialSegments; x ++ ) {
  22248. for ( let y = 0; y < heightSegments; y ++ ) {
  22249. // we use the index array to access the correct indices
  22250. const a = indexArray[ y ][ x ];
  22251. const b = indexArray[ y + 1 ][ x ];
  22252. const c = indexArray[ y + 1 ][ x + 1 ];
  22253. const d = indexArray[ y ][ x + 1 ];
  22254. // faces
  22255. if ( radiusTop > 0 || y !== 0 ) {
  22256. indices.push( a, b, d );
  22257. groupCount += 3;
  22258. }
  22259. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22260. indices.push( b, c, d );
  22261. groupCount += 3;
  22262. }
  22263. }
  22264. }
  22265. // add a group to the geometry. this will ensure multi material support
  22266. scope.addGroup( groupStart, groupCount, 0 );
  22267. // calculate new start value for groups
  22268. groupStart += groupCount;
  22269. }
  22270. function generateCap( top ) {
  22271. // save the index of the first center vertex
  22272. const centerIndexStart = index;
  22273. const uv = new Vector2();
  22274. const vertex = new Vector3();
  22275. let groupCount = 0;
  22276. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22277. const sign = ( top === true ) ? 1 : -1;
  22278. // first we generate the center vertex data of the cap.
  22279. // because the geometry needs one set of uvs per face,
  22280. // we must generate a center vertex per face/segment
  22281. for ( let x = 1; x <= radialSegments; x ++ ) {
  22282. // vertex
  22283. vertices.push( 0, halfHeight * sign, 0 );
  22284. // normal
  22285. normals.push( 0, sign, 0 );
  22286. // uv
  22287. uvs.push( 0.5, 0.5 );
  22288. // increase index
  22289. index ++;
  22290. }
  22291. // save the index of the last center vertex
  22292. const centerIndexEnd = index;
  22293. // now we generate the surrounding vertices, normals and uvs
  22294. for ( let x = 0; x <= radialSegments; x ++ ) {
  22295. const u = x / radialSegments;
  22296. const theta = u * thetaLength + thetaStart;
  22297. const cosTheta = Math.cos( theta );
  22298. const sinTheta = Math.sin( theta );
  22299. // vertex
  22300. vertex.x = radius * sinTheta;
  22301. vertex.y = halfHeight * sign;
  22302. vertex.z = radius * cosTheta;
  22303. vertices.push( vertex.x, vertex.y, vertex.z );
  22304. // normal
  22305. normals.push( 0, sign, 0 );
  22306. // uv
  22307. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22308. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22309. uvs.push( uv.x, uv.y );
  22310. // increase index
  22311. index ++;
  22312. }
  22313. // generate indices
  22314. for ( let x = 0; x < radialSegments; x ++ ) {
  22315. const c = centerIndexStart + x;
  22316. const i = centerIndexEnd + x;
  22317. if ( top === true ) {
  22318. // face top
  22319. indices.push( i, i + 1, c );
  22320. } else {
  22321. // face bottom
  22322. indices.push( i + 1, i, c );
  22323. }
  22324. groupCount += 3;
  22325. }
  22326. // add a group to the geometry. this will ensure multi material support
  22327. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22328. // calculate new start value for groups
  22329. groupStart += groupCount;
  22330. }
  22331. }
  22332. copy( source ) {
  22333. super.copy( source );
  22334. this.parameters = Object.assign( {}, source.parameters );
  22335. return this;
  22336. }
  22337. /**
  22338. * Factory method for creating an instance of this class from the given
  22339. * JSON object.
  22340. *
  22341. * @param {Object} data - A JSON object representing the serialized geometry.
  22342. * @return {CylinderGeometry} A new instance.
  22343. */
  22344. static fromJSON( data ) {
  22345. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22346. }
  22347. }
  22348. /**
  22349. * A geometry class for representing a cone.
  22350. *
  22351. * ```js
  22352. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22353. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22354. * const cone = new THREE.Mesh(geometry, material );
  22355. * scene.add( cone );
  22356. * ```
  22357. *
  22358. * @augments CylinderGeometry
  22359. * @demo scenes/geometry-browser.html#ConeGeometry
  22360. */
  22361. class ConeGeometry extends CylinderGeometry {
  22362. /**
  22363. * Constructs a new cone geometry.
  22364. *
  22365. * @param {number} [radius=1] - Radius of the cone base.
  22366. * @param {number} [height=1] - Height of the cone.
  22367. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22368. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22369. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22370. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22371. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22372. * The default value results in a complete cone.
  22373. */
  22374. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22375. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22376. this.type = 'ConeGeometry';
  22377. /**
  22378. * Holds the constructor parameters that have been
  22379. * used to generate the geometry. Any modification
  22380. * after instantiation does not change the geometry.
  22381. *
  22382. * @type {Object}
  22383. */
  22384. this.parameters = {
  22385. radius: radius,
  22386. height: height,
  22387. radialSegments: radialSegments,
  22388. heightSegments: heightSegments,
  22389. openEnded: openEnded,
  22390. thetaStart: thetaStart,
  22391. thetaLength: thetaLength
  22392. };
  22393. }
  22394. /**
  22395. * Factory method for creating an instance of this class from the given
  22396. * JSON object.
  22397. *
  22398. * @param {Object} data - A JSON object representing the serialized geometry.
  22399. * @return {ConeGeometry} A new instance.
  22400. */
  22401. static fromJSON( data ) {
  22402. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22403. }
  22404. }
  22405. /**
  22406. * A polyhedron is a solid in three dimensions with flat faces. This class
  22407. * will take an array of vertices, project them onto a sphere, and then
  22408. * divide them up to the desired level of detail.
  22409. *
  22410. * @augments BufferGeometry
  22411. */
  22412. class PolyhedronGeometry extends BufferGeometry {
  22413. /**
  22414. * Constructs a new polyhedron geometry.
  22415. *
  22416. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22417. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22418. * @param {number} [radius=1] - The radius of the shape.
  22419. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22420. */
  22421. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22422. super();
  22423. this.type = 'PolyhedronGeometry';
  22424. /**
  22425. * Holds the constructor parameters that have been
  22426. * used to generate the geometry. Any modification
  22427. * after instantiation does not change the geometry.
  22428. *
  22429. * @type {Object}
  22430. */
  22431. this.parameters = {
  22432. vertices: vertices,
  22433. indices: indices,
  22434. radius: radius,
  22435. detail: detail
  22436. };
  22437. // default buffer data
  22438. const vertexBuffer = [];
  22439. const uvBuffer = [];
  22440. // the subdivision creates the vertex buffer data
  22441. subdivide( detail );
  22442. // all vertices should lie on a conceptual sphere with a given radius
  22443. applyRadius( radius );
  22444. // finally, create the uv data
  22445. generateUVs();
  22446. // build non-indexed geometry
  22447. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22448. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22449. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22450. if ( detail === 0 ) {
  22451. this.computeVertexNormals(); // flat normals
  22452. } else {
  22453. this.normalizeNormals(); // smooth normals
  22454. }
  22455. // helper functions
  22456. function subdivide( detail ) {
  22457. const a = new Vector3();
  22458. const b = new Vector3();
  22459. const c = new Vector3();
  22460. // iterate over all faces and apply a subdivision with the given detail value
  22461. for ( let i = 0; i < indices.length; i += 3 ) {
  22462. // get the vertices of the face
  22463. getVertexByIndex( indices[ i + 0 ], a );
  22464. getVertexByIndex( indices[ i + 1 ], b );
  22465. getVertexByIndex( indices[ i + 2 ], c );
  22466. // perform subdivision
  22467. subdivideFace( a, b, c, detail );
  22468. }
  22469. }
  22470. function subdivideFace( a, b, c, detail ) {
  22471. const cols = detail + 1;
  22472. // we use this multidimensional array as a data structure for creating the subdivision
  22473. const v = [];
  22474. // construct all of the vertices for this subdivision
  22475. for ( let i = 0; i <= cols; i ++ ) {
  22476. v[ i ] = [];
  22477. const aj = a.clone().lerp( c, i / cols );
  22478. const bj = b.clone().lerp( c, i / cols );
  22479. const rows = cols - i;
  22480. for ( let j = 0; j <= rows; j ++ ) {
  22481. if ( j === 0 && i === cols ) {
  22482. v[ i ][ j ] = aj;
  22483. } else {
  22484. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22485. }
  22486. }
  22487. }
  22488. // construct all of the faces
  22489. for ( let i = 0; i < cols; i ++ ) {
  22490. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22491. const k = Math.floor( j / 2 );
  22492. if ( j % 2 === 0 ) {
  22493. pushVertex( v[ i ][ k + 1 ] );
  22494. pushVertex( v[ i + 1 ][ k ] );
  22495. pushVertex( v[ i ][ k ] );
  22496. } else {
  22497. pushVertex( v[ i ][ k + 1 ] );
  22498. pushVertex( v[ i + 1 ][ k + 1 ] );
  22499. pushVertex( v[ i + 1 ][ k ] );
  22500. }
  22501. }
  22502. }
  22503. }
  22504. function applyRadius( radius ) {
  22505. const vertex = new Vector3();
  22506. // iterate over the entire buffer and apply the radius to each vertex
  22507. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22508. vertex.x = vertexBuffer[ i + 0 ];
  22509. vertex.y = vertexBuffer[ i + 1 ];
  22510. vertex.z = vertexBuffer[ i + 2 ];
  22511. vertex.normalize().multiplyScalar( radius );
  22512. vertexBuffer[ i + 0 ] = vertex.x;
  22513. vertexBuffer[ i + 1 ] = vertex.y;
  22514. vertexBuffer[ i + 2 ] = vertex.z;
  22515. }
  22516. }
  22517. function generateUVs() {
  22518. const vertex = new Vector3();
  22519. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22520. vertex.x = vertexBuffer[ i + 0 ];
  22521. vertex.y = vertexBuffer[ i + 1 ];
  22522. vertex.z = vertexBuffer[ i + 2 ];
  22523. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22524. const v = inclination( vertex ) / Math.PI + 0.5;
  22525. uvBuffer.push( u, 1 - v );
  22526. }
  22527. correctUVs();
  22528. correctSeam();
  22529. }
  22530. function correctSeam() {
  22531. // handle case when face straddles the seam, see #3269
  22532. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22533. // uv data of a single face
  22534. const x0 = uvBuffer[ i + 0 ];
  22535. const x1 = uvBuffer[ i + 2 ];
  22536. const x2 = uvBuffer[ i + 4 ];
  22537. const max = Math.max( x0, x1, x2 );
  22538. const min = Math.min( x0, x1, x2 );
  22539. // 0.9 is somewhat arbitrary
  22540. if ( max > 0.9 && min < 0.1 ) {
  22541. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22542. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22543. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22544. }
  22545. }
  22546. }
  22547. function pushVertex( vertex ) {
  22548. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22549. }
  22550. function getVertexByIndex( index, vertex ) {
  22551. const stride = index * 3;
  22552. vertex.x = vertices[ stride + 0 ];
  22553. vertex.y = vertices[ stride + 1 ];
  22554. vertex.z = vertices[ stride + 2 ];
  22555. }
  22556. function correctUVs() {
  22557. const a = new Vector3();
  22558. const b = new Vector3();
  22559. const c = new Vector3();
  22560. const centroid = new Vector3();
  22561. const uvA = new Vector2();
  22562. const uvB = new Vector2();
  22563. const uvC = new Vector2();
  22564. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22565. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22566. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22567. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22568. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22569. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22570. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22571. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22572. const azi = azimuth( centroid );
  22573. correctUV( uvA, j + 0, a, azi );
  22574. correctUV( uvB, j + 2, b, azi );
  22575. correctUV( uvC, j + 4, c, azi );
  22576. }
  22577. }
  22578. function correctUV( uv, stride, vector, azimuth ) {
  22579. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22580. uvBuffer[ stride ] = uv.x - 1;
  22581. }
  22582. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22583. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22584. }
  22585. }
  22586. // Angle around the Y axis, counter-clockwise when looking from above.
  22587. function azimuth( vector ) {
  22588. return Math.atan2( vector.z, - vector.x );
  22589. }
  22590. // Angle above the XZ plane.
  22591. function inclination( vector ) {
  22592. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22593. }
  22594. }
  22595. copy( source ) {
  22596. super.copy( source );
  22597. this.parameters = Object.assign( {}, source.parameters );
  22598. return this;
  22599. }
  22600. /**
  22601. * Factory method for creating an instance of this class from the given
  22602. * JSON object.
  22603. *
  22604. * @param {Object} data - A JSON object representing the serialized geometry.
  22605. * @return {PolyhedronGeometry} A new instance.
  22606. */
  22607. static fromJSON( data ) {
  22608. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  22609. }
  22610. }
  22611. /**
  22612. * A geometry class for representing a dodecahedron.
  22613. *
  22614. * ```js
  22615. * const geometry = new THREE.DodecahedronGeometry();
  22616. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22617. * const dodecahedron = new THREE.Mesh( geometry, material );
  22618. * scene.add( dodecahedron );
  22619. * ```
  22620. *
  22621. * @augments PolyhedronGeometry
  22622. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  22623. */
  22624. class DodecahedronGeometry extends PolyhedronGeometry {
  22625. /**
  22626. * Constructs a new dodecahedron geometry.
  22627. *
  22628. * @param {number} [radius=1] - Radius of the dodecahedron.
  22629. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22630. */
  22631. constructor( radius = 1, detail = 0 ) {
  22632. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22633. const r = 1 / t;
  22634. const vertices = [
  22635. // (±1, ±1, ±1)
  22636. -1, -1, -1, -1, -1, 1,
  22637. -1, 1, -1, -1, 1, 1,
  22638. 1, -1, -1, 1, -1, 1,
  22639. 1, 1, -1, 1, 1, 1,
  22640. // (0, ±1/φ, ±φ)
  22641. 0, - r, - t, 0, - r, t,
  22642. 0, r, - t, 0, r, t,
  22643. // (±1/φ, ±φ, 0)
  22644. - r, - t, 0, - r, t, 0,
  22645. r, - t, 0, r, t, 0,
  22646. // (±φ, 0, ±1/φ)
  22647. - t, 0, - r, t, 0, - r,
  22648. - t, 0, r, t, 0, r
  22649. ];
  22650. const indices = [
  22651. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22652. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22653. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22654. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22655. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22656. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22657. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22658. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22659. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22660. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22661. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22662. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22663. ];
  22664. super( vertices, indices, radius, detail );
  22665. this.type = 'DodecahedronGeometry';
  22666. /**
  22667. * Holds the constructor parameters that have been
  22668. * used to generate the geometry. Any modification
  22669. * after instantiation does not change the geometry.
  22670. *
  22671. * @type {Object}
  22672. */
  22673. this.parameters = {
  22674. radius: radius,
  22675. detail: detail
  22676. };
  22677. }
  22678. /**
  22679. * Factory method for creating an instance of this class from the given
  22680. * JSON object.
  22681. *
  22682. * @param {Object} data - A JSON object representing the serialized geometry.
  22683. * @return {DodecahedronGeometry} A new instance.
  22684. */
  22685. static fromJSON( data ) {
  22686. return new DodecahedronGeometry( data.radius, data.detail );
  22687. }
  22688. }
  22689. const _v0 = /*@__PURE__*/ new Vector3();
  22690. const _v1$1 = /*@__PURE__*/ new Vector3();
  22691. const _normal = /*@__PURE__*/ new Vector3();
  22692. const _triangle = /*@__PURE__*/ new Triangle();
  22693. /**
  22694. * Can be used as a helper object to view the edges of a geometry.
  22695. *
  22696. * ```js
  22697. * const geometry = new THREE.BoxGeometry();
  22698. * const edges = new THREE.EdgesGeometry( geometry );
  22699. * const line = new THREE.LineSegments( edges );
  22700. * scene.add( line );
  22701. * ```
  22702. *
  22703. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22704. *
  22705. * @augments BufferGeometry
  22706. */
  22707. class EdgesGeometry extends BufferGeometry {
  22708. /**
  22709. * Constructs a new edges geometry.
  22710. *
  22711. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22712. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22713. * between the face normals of the adjoining faces exceeds this value.
  22714. */
  22715. constructor( geometry = null, thresholdAngle = 1 ) {
  22716. super();
  22717. this.type = 'EdgesGeometry';
  22718. /**
  22719. * Holds the constructor parameters that have been
  22720. * used to generate the geometry. Any modification
  22721. * after instantiation does not change the geometry.
  22722. *
  22723. * @type {Object}
  22724. */
  22725. this.parameters = {
  22726. geometry: geometry,
  22727. thresholdAngle: thresholdAngle
  22728. };
  22729. if ( geometry !== null ) {
  22730. const precisionPoints = 4;
  22731. const precision = Math.pow( 10, precisionPoints );
  22732. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22733. const indexAttr = geometry.getIndex();
  22734. const positionAttr = geometry.getAttribute( 'position' );
  22735. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22736. const indexArr = [ 0, 0, 0 ];
  22737. const vertKeys = [ 'a', 'b', 'c' ];
  22738. const hashes = new Array( 3 );
  22739. const edgeData = {};
  22740. const vertices = [];
  22741. for ( let i = 0; i < indexCount; i += 3 ) {
  22742. if ( indexAttr ) {
  22743. indexArr[ 0 ] = indexAttr.getX( i );
  22744. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22745. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22746. } else {
  22747. indexArr[ 0 ] = i;
  22748. indexArr[ 1 ] = i + 1;
  22749. indexArr[ 2 ] = i + 2;
  22750. }
  22751. const { a, b, c } = _triangle;
  22752. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22753. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22754. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22755. _triangle.getNormal( _normal );
  22756. // create hashes for the edge from the vertices
  22757. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22758. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22759. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22760. // skip degenerate triangles
  22761. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22762. continue;
  22763. }
  22764. // iterate over every edge
  22765. for ( let j = 0; j < 3; j ++ ) {
  22766. // get the first and next vertex making up the edge
  22767. const jNext = ( j + 1 ) % 3;
  22768. const vecHash0 = hashes[ j ];
  22769. const vecHash1 = hashes[ jNext ];
  22770. const v0 = _triangle[ vertKeys[ j ] ];
  22771. const v1 = _triangle[ vertKeys[ jNext ] ];
  22772. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22773. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22774. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22775. // if we found a sibling edge add it into the vertex array if
  22776. // it meets the angle threshold and delete the edge from the map.
  22777. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22778. vertices.push( v0.x, v0.y, v0.z );
  22779. vertices.push( v1.x, v1.y, v1.z );
  22780. }
  22781. edgeData[ reverseHash ] = null;
  22782. } else if ( ! ( hash in edgeData ) ) {
  22783. // if we've already got an edge here then skip adding a new one
  22784. edgeData[ hash ] = {
  22785. index0: indexArr[ j ],
  22786. index1: indexArr[ jNext ],
  22787. normal: _normal.clone(),
  22788. };
  22789. }
  22790. }
  22791. }
  22792. // iterate over all remaining, unmatched edges and add them to the vertex array
  22793. for ( const key in edgeData ) {
  22794. if ( edgeData[ key ] ) {
  22795. const { index0, index1 } = edgeData[ key ];
  22796. _v0.fromBufferAttribute( positionAttr, index0 );
  22797. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22798. vertices.push( _v0.x, _v0.y, _v0.z );
  22799. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22800. }
  22801. }
  22802. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22803. }
  22804. }
  22805. copy( source ) {
  22806. super.copy( source );
  22807. this.parameters = Object.assign( {}, source.parameters );
  22808. return this;
  22809. }
  22810. }
  22811. /**
  22812. * An abstract base class for creating an analytic curve object that contains methods
  22813. * for interpolation.
  22814. *
  22815. * @abstract
  22816. */
  22817. class Curve {
  22818. /**
  22819. * Constructs a new curve.
  22820. */
  22821. constructor() {
  22822. /**
  22823. * The type property is used for detecting the object type
  22824. * in context of serialization/deserialization.
  22825. *
  22826. * @type {string}
  22827. * @readonly
  22828. */
  22829. this.type = 'Curve';
  22830. /**
  22831. * This value determines the amount of divisions when calculating the
  22832. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  22833. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  22834. * recommended to increase the value of this property if the curve is very large.
  22835. *
  22836. * @type {number}
  22837. * @default 200
  22838. */
  22839. this.arcLengthDivisions = 200;
  22840. /**
  22841. * Must be set to `true` if the curve parameters have changed.
  22842. *
  22843. * @type {boolean}
  22844. * @default false
  22845. */
  22846. this.needsUpdate = false;
  22847. /**
  22848. * An internal cache that holds precomputed curve length values.
  22849. *
  22850. * @private
  22851. * @type {?Array<number>}
  22852. * @default null
  22853. */
  22854. this.cacheArcLengths = null;
  22855. }
  22856. /**
  22857. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22858. * for the given interpolation factor.
  22859. *
  22860. * @abstract
  22861. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22862. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22863. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22864. */
  22865. getPoint( /* t, optionalTarget */ ) {
  22866. warn( 'Curve: .getPoint() not implemented.' );
  22867. }
  22868. /**
  22869. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22870. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  22871. * of the curve which equidistant samples.
  22872. *
  22873. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22874. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22875. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22876. */
  22877. getPointAt( u, optionalTarget ) {
  22878. const t = this.getUtoTmapping( u );
  22879. return this.getPoint( t, optionalTarget );
  22880. }
  22881. /**
  22882. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  22883. * the curve shape.
  22884. *
  22885. * @param {number} [divisions=5] - The number of divisions.
  22886. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22887. */
  22888. getPoints( divisions = 5 ) {
  22889. const points = [];
  22890. for ( let d = 0; d <= divisions; d ++ ) {
  22891. points.push( this.getPoint( d / divisions ) );
  22892. }
  22893. return points;
  22894. }
  22895. // Get sequence of points using getPointAt( u )
  22896. /**
  22897. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  22898. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  22899. * curve.
  22900. *
  22901. * @param {number} [divisions=5] - The number of divisions.
  22902. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22903. */
  22904. getSpacedPoints( divisions = 5 ) {
  22905. const points = [];
  22906. for ( let d = 0; d <= divisions; d ++ ) {
  22907. points.push( this.getPointAt( d / divisions ) );
  22908. }
  22909. return points;
  22910. }
  22911. /**
  22912. * Returns the total arc length of the curve.
  22913. *
  22914. * @return {number} The length of the curve.
  22915. */
  22916. getLength() {
  22917. const lengths = this.getLengths();
  22918. return lengths[ lengths.length - 1 ];
  22919. }
  22920. /**
  22921. * Returns an array of cumulative segment lengths of the curve.
  22922. *
  22923. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  22924. * @return {Array<number>} An array holding the cumulative segment lengths.
  22925. */
  22926. getLengths( divisions = this.arcLengthDivisions ) {
  22927. if ( this.cacheArcLengths &&
  22928. ( this.cacheArcLengths.length === divisions + 1 ) &&
  22929. ! this.needsUpdate ) {
  22930. return this.cacheArcLengths;
  22931. }
  22932. this.needsUpdate = false;
  22933. const cache = [];
  22934. let current, last = this.getPoint( 0 );
  22935. let sum = 0;
  22936. cache.push( 0 );
  22937. for ( let p = 1; p <= divisions; p ++ ) {
  22938. current = this.getPoint( p / divisions );
  22939. sum += current.distanceTo( last );
  22940. cache.push( sum );
  22941. last = current;
  22942. }
  22943. this.cacheArcLengths = cache;
  22944. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22945. }
  22946. /**
  22947. * Update the cumulative segment distance cache. The method must be called
  22948. * every time curve parameters are changed. If an updated curve is part of a
  22949. * composed curve like {@link CurvePath}, this method must be called on the
  22950. * composed curve, too.
  22951. */
  22952. updateArcLengths() {
  22953. this.needsUpdate = true;
  22954. this.getLengths();
  22955. }
  22956. /**
  22957. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  22958. * interpolation factor in the same range that can be ued to sample equidistant points
  22959. * from a curve.
  22960. *
  22961. * @param {number} u - The interpolation factor.
  22962. * @param {?number} distance - An optional distance on the curve.
  22963. * @return {number} The updated interpolation factor.
  22964. */
  22965. getUtoTmapping( u, distance = null ) {
  22966. const arcLengths = this.getLengths();
  22967. let i = 0;
  22968. const il = arcLengths.length;
  22969. let targetArcLength; // The targeted u distance value to get
  22970. if ( distance ) {
  22971. targetArcLength = distance;
  22972. } else {
  22973. targetArcLength = u * arcLengths[ il - 1 ];
  22974. }
  22975. // binary search for the index with largest value smaller than target u distance
  22976. let low = 0, high = il - 1, comparison;
  22977. while ( low <= high ) {
  22978. 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
  22979. comparison = arcLengths[ i ] - targetArcLength;
  22980. if ( comparison < 0 ) {
  22981. low = i + 1;
  22982. } else if ( comparison > 0 ) {
  22983. high = i - 1;
  22984. } else {
  22985. high = i;
  22986. break;
  22987. // DONE
  22988. }
  22989. }
  22990. i = high;
  22991. if ( arcLengths[ i ] === targetArcLength ) {
  22992. return i / ( il - 1 );
  22993. }
  22994. // we could get finer grain at lengths, or use simple interpolation between two points
  22995. const lengthBefore = arcLengths[ i ];
  22996. const lengthAfter = arcLengths[ i + 1 ];
  22997. const segmentLength = lengthAfter - lengthBefore;
  22998. // determine where we are between the 'before' and 'after' points
  22999. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23000. // add that fractional amount to t
  23001. const t = ( i + segmentFraction ) / ( il - 1 );
  23002. return t;
  23003. }
  23004. /**
  23005. * Returns a unit vector tangent for the given interpolation factor.
  23006. * If the derived curve does not implement its tangent derivation,
  23007. * two points a small delta apart will be used to find its gradient
  23008. * which seems to give a reasonable approximation.
  23009. *
  23010. * @param {number} t - The interpolation factor.
  23011. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23012. * @return {(Vector2|Vector3)} The tangent vector.
  23013. */
  23014. getTangent( t, optionalTarget ) {
  23015. const delta = 0.0001;
  23016. let t1 = t - delta;
  23017. let t2 = t + delta;
  23018. // Capping in case of danger
  23019. if ( t1 < 0 ) t1 = 0;
  23020. if ( t2 > 1 ) t2 = 1;
  23021. const pt1 = this.getPoint( t1 );
  23022. const pt2 = this.getPoint( t2 );
  23023. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23024. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23025. return tangent;
  23026. }
  23027. /**
  23028. * Same as {@link Curve#getTangent} but with equidistant samples.
  23029. *
  23030. * @param {number} u - The interpolation factor.
  23031. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23032. * @return {(Vector2|Vector3)} The tangent vector.
  23033. * @see {@link Curve#getPointAt}
  23034. */
  23035. getTangentAt( u, optionalTarget ) {
  23036. const t = this.getUtoTmapping( u );
  23037. return this.getTangent( t, optionalTarget );
  23038. }
  23039. /**
  23040. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23041. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23042. *
  23043. * @param {number} segments - The number of segments.
  23044. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23045. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23046. */
  23047. computeFrenetFrames( segments, closed = false ) {
  23048. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23049. const normal = new Vector3();
  23050. const tangents = [];
  23051. const normals = [];
  23052. const binormals = [];
  23053. const vec = new Vector3();
  23054. const mat = new Matrix4();
  23055. // compute the tangent vectors for each segment on the curve
  23056. for ( let i = 0; i <= segments; i ++ ) {
  23057. const u = i / segments;
  23058. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23059. }
  23060. // select an initial normal vector perpendicular to the first tangent vector,
  23061. // and in the direction of the minimum tangent xyz component
  23062. normals[ 0 ] = new Vector3();
  23063. binormals[ 0 ] = new Vector3();
  23064. let min = Number.MAX_VALUE;
  23065. const tx = Math.abs( tangents[ 0 ].x );
  23066. const ty = Math.abs( tangents[ 0 ].y );
  23067. const tz = Math.abs( tangents[ 0 ].z );
  23068. if ( tx <= min ) {
  23069. min = tx;
  23070. normal.set( 1, 0, 0 );
  23071. }
  23072. if ( ty <= min ) {
  23073. min = ty;
  23074. normal.set( 0, 1, 0 );
  23075. }
  23076. if ( tz <= min ) {
  23077. normal.set( 0, 0, 1 );
  23078. }
  23079. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23080. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23081. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23082. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23083. for ( let i = 1; i <= segments; i ++ ) {
  23084. normals[ i ] = normals[ i - 1 ].clone();
  23085. binormals[ i ] = binormals[ i - 1 ].clone();
  23086. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23087. if ( vec.length() > Number.EPSILON ) {
  23088. vec.normalize();
  23089. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23090. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23091. }
  23092. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23093. }
  23094. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23095. if ( closed === true ) {
  23096. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23097. theta /= segments;
  23098. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23099. theta = - theta;
  23100. }
  23101. for ( let i = 1; i <= segments; i ++ ) {
  23102. // twist a little...
  23103. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23104. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23105. }
  23106. }
  23107. return {
  23108. tangents: tangents,
  23109. normals: normals,
  23110. binormals: binormals
  23111. };
  23112. }
  23113. /**
  23114. * Returns a new curve with copied values from this instance.
  23115. *
  23116. * @return {Curve} A clone of this instance.
  23117. */
  23118. clone() {
  23119. return new this.constructor().copy( this );
  23120. }
  23121. /**
  23122. * Copies the values of the given curve to this instance.
  23123. *
  23124. * @param {Curve} source - The curve to copy.
  23125. * @return {Curve} A reference to this curve.
  23126. */
  23127. copy( source ) {
  23128. this.arcLengthDivisions = source.arcLengthDivisions;
  23129. return this;
  23130. }
  23131. /**
  23132. * Serializes the curve into JSON.
  23133. *
  23134. * @return {Object} A JSON object representing the serialized curve.
  23135. * @see {@link ObjectLoader#parse}
  23136. */
  23137. toJSON() {
  23138. const data = {
  23139. metadata: {
  23140. version: 4.7,
  23141. type: 'Curve',
  23142. generator: 'Curve.toJSON'
  23143. }
  23144. };
  23145. data.arcLengthDivisions = this.arcLengthDivisions;
  23146. data.type = this.type;
  23147. return data;
  23148. }
  23149. /**
  23150. * Deserializes the curve from the given JSON.
  23151. *
  23152. * @param {Object} json - The JSON holding the serialized curve.
  23153. * @return {Curve} A reference to this curve.
  23154. */
  23155. fromJSON( json ) {
  23156. this.arcLengthDivisions = json.arcLengthDivisions;
  23157. return this;
  23158. }
  23159. }
  23160. /**
  23161. * A curve representing an ellipse.
  23162. *
  23163. * ```js
  23164. * const curve = new THREE.EllipseCurve(
  23165. * 0, 0,
  23166. * 10, 10,
  23167. * 0, 2 * Math.PI,
  23168. * false,
  23169. * 0
  23170. * );
  23171. *
  23172. * const points = curve.getPoints( 50 );
  23173. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23174. *
  23175. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23176. *
  23177. * // Create the final object to add to the scene
  23178. * const ellipse = new THREE.Line( geometry, material );
  23179. * ```
  23180. *
  23181. * @augments Curve
  23182. */
  23183. class EllipseCurve extends Curve {
  23184. /**
  23185. * Constructs a new ellipse curve.
  23186. *
  23187. * @param {number} [aX=0] - The X center of the ellipse.
  23188. * @param {number} [aY=0] - The Y center of the ellipse.
  23189. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23190. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23191. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23192. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23193. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23194. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23195. */
  23196. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23197. super();
  23198. /**
  23199. * This flag can be used for type testing.
  23200. *
  23201. * @type {boolean}
  23202. * @readonly
  23203. * @default true
  23204. */
  23205. this.isEllipseCurve = true;
  23206. this.type = 'EllipseCurve';
  23207. /**
  23208. * The X center of the ellipse.
  23209. *
  23210. * @type {number}
  23211. * @default 0
  23212. */
  23213. this.aX = aX;
  23214. /**
  23215. * The Y center of the ellipse.
  23216. *
  23217. * @type {number}
  23218. * @default 0
  23219. */
  23220. this.aY = aY;
  23221. /**
  23222. * The radius of the ellipse in the x direction.
  23223. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23224. *
  23225. * @type {number}
  23226. * @default 1
  23227. */
  23228. this.xRadius = xRadius;
  23229. /**
  23230. * The radius of the ellipse in the y direction.
  23231. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23232. *
  23233. * @type {number}
  23234. * @default 1
  23235. */
  23236. this.yRadius = yRadius;
  23237. /**
  23238. * The start angle of the curve in radians starting from the positive X axis.
  23239. *
  23240. * @type {number}
  23241. * @default 0
  23242. */
  23243. this.aStartAngle = aStartAngle;
  23244. /**
  23245. * The end angle of the curve in radians starting from the positive X axis.
  23246. *
  23247. * @type {number}
  23248. * @default Math.PI*2
  23249. */
  23250. this.aEndAngle = aEndAngle;
  23251. /**
  23252. * Whether the ellipse is drawn clockwise or not.
  23253. *
  23254. * @type {boolean}
  23255. * @default false
  23256. */
  23257. this.aClockwise = aClockwise;
  23258. /**
  23259. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23260. *
  23261. * @type {number}
  23262. * @default 0
  23263. */
  23264. this.aRotation = aRotation;
  23265. }
  23266. /**
  23267. * Returns a point on the curve.
  23268. *
  23269. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23270. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23271. * @return {Vector2} The position on the curve.
  23272. */
  23273. getPoint( t, optionalTarget = new Vector2() ) {
  23274. const point = optionalTarget;
  23275. const twoPi = Math.PI * 2;
  23276. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23277. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23278. // ensures that deltaAngle is 0 .. 2 PI
  23279. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23280. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23281. if ( deltaAngle < Number.EPSILON ) {
  23282. if ( samePoints ) {
  23283. deltaAngle = 0;
  23284. } else {
  23285. deltaAngle = twoPi;
  23286. }
  23287. }
  23288. if ( this.aClockwise === true && ! samePoints ) {
  23289. if ( deltaAngle === twoPi ) {
  23290. deltaAngle = - twoPi;
  23291. } else {
  23292. deltaAngle = deltaAngle - twoPi;
  23293. }
  23294. }
  23295. const angle = this.aStartAngle + t * deltaAngle;
  23296. let x = this.aX + this.xRadius * Math.cos( angle );
  23297. let y = this.aY + this.yRadius * Math.sin( angle );
  23298. if ( this.aRotation !== 0 ) {
  23299. const cos = Math.cos( this.aRotation );
  23300. const sin = Math.sin( this.aRotation );
  23301. const tx = x - this.aX;
  23302. const ty = y - this.aY;
  23303. // Rotate the point about the center of the ellipse.
  23304. x = tx * cos - ty * sin + this.aX;
  23305. y = tx * sin + ty * cos + this.aY;
  23306. }
  23307. return point.set( x, y );
  23308. }
  23309. copy( source ) {
  23310. super.copy( source );
  23311. this.aX = source.aX;
  23312. this.aY = source.aY;
  23313. this.xRadius = source.xRadius;
  23314. this.yRadius = source.yRadius;
  23315. this.aStartAngle = source.aStartAngle;
  23316. this.aEndAngle = source.aEndAngle;
  23317. this.aClockwise = source.aClockwise;
  23318. this.aRotation = source.aRotation;
  23319. return this;
  23320. }
  23321. toJSON() {
  23322. const data = super.toJSON();
  23323. data.aX = this.aX;
  23324. data.aY = this.aY;
  23325. data.xRadius = this.xRadius;
  23326. data.yRadius = this.yRadius;
  23327. data.aStartAngle = this.aStartAngle;
  23328. data.aEndAngle = this.aEndAngle;
  23329. data.aClockwise = this.aClockwise;
  23330. data.aRotation = this.aRotation;
  23331. return data;
  23332. }
  23333. fromJSON( json ) {
  23334. super.fromJSON( json );
  23335. this.aX = json.aX;
  23336. this.aY = json.aY;
  23337. this.xRadius = json.xRadius;
  23338. this.yRadius = json.yRadius;
  23339. this.aStartAngle = json.aStartAngle;
  23340. this.aEndAngle = json.aEndAngle;
  23341. this.aClockwise = json.aClockwise;
  23342. this.aRotation = json.aRotation;
  23343. return this;
  23344. }
  23345. }
  23346. /**
  23347. * A curve representing an arc.
  23348. *
  23349. * @augments EllipseCurve
  23350. */
  23351. class ArcCurve extends EllipseCurve {
  23352. /**
  23353. * Constructs a new arc curve.
  23354. *
  23355. * @param {number} [aX=0] - The X center of the ellipse.
  23356. * @param {number} [aY=0] - The Y center of the ellipse.
  23357. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23358. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23359. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23360. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23361. */
  23362. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23363. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23364. /**
  23365. * This flag can be used for type testing.
  23366. *
  23367. * @type {boolean}
  23368. * @readonly
  23369. * @default true
  23370. */
  23371. this.isArcCurve = true;
  23372. this.type = 'ArcCurve';
  23373. }
  23374. }
  23375. function CubicPoly() {
  23376. /**
  23377. * Centripetal CatmullRom Curve - which is useful for avoiding
  23378. * cusps and self-intersections in non-uniform catmull rom curves.
  23379. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23380. *
  23381. * curve.type accepts centripetal(default), chordal and catmullrom
  23382. * curve.tension is used for catmullrom which defaults to 0.5
  23383. */
  23384. /*
  23385. Based on an optimized c++ solution in
  23386. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23387. - http://ideone.com/NoEbVM
  23388. This CubicPoly class could be used for reusing some variables and calculations,
  23389. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23390. which can be placed in CurveUtils.
  23391. */
  23392. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23393. /*
  23394. * Compute coefficients for a cubic polynomial
  23395. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23396. * such that
  23397. * p(0) = x0, p(1) = x1
  23398. * and
  23399. * p'(0) = t0, p'(1) = t1.
  23400. */
  23401. function init( x0, x1, t0, t1 ) {
  23402. c0 = x0;
  23403. c1 = t0;
  23404. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23405. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23406. }
  23407. return {
  23408. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23409. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23410. },
  23411. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23412. // compute tangents when parameterized in [t1,t2]
  23413. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23414. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23415. // rescale tangents for parametrization in [0,1]
  23416. t1 *= dt1;
  23417. t2 *= dt1;
  23418. init( x1, x2, t1, t2 );
  23419. },
  23420. calc: function ( t ) {
  23421. const t2 = t * t;
  23422. const t3 = t2 * t;
  23423. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23424. }
  23425. };
  23426. }
  23427. //
  23428. const tmp = /*@__PURE__*/ new Vector3();
  23429. const tmp2 = /*@__PURE__*/ new Vector3();
  23430. const px = /*@__PURE__*/ new CubicPoly();
  23431. const py = /*@__PURE__*/ new CubicPoly();
  23432. const pz = /*@__PURE__*/ new CubicPoly();
  23433. /**
  23434. * A curve representing a Catmull-Rom spline.
  23435. *
  23436. * ```js
  23437. * //Create a closed wavey loop
  23438. * const curve = new THREE.CatmullRomCurve3( [
  23439. * new THREE.Vector3( -10, 0, 10 ),
  23440. * new THREE.Vector3( -5, 5, 5 ),
  23441. * new THREE.Vector3( 0, 0, 0 ),
  23442. * new THREE.Vector3( 5, -5, 5 ),
  23443. * new THREE.Vector3( 10, 0, 10 )
  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 CatmullRomCurve3 extends Curve {
  23458. /**
  23459. * Constructs a new Catmull-Rom curve.
  23460. *
  23461. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23462. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23463. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23464. * @param {number} [tension=0.5] - Tension of the curve.
  23465. */
  23466. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23467. super();
  23468. /**
  23469. * This flag can be used for type testing.
  23470. *
  23471. * @type {boolean}
  23472. * @readonly
  23473. * @default true
  23474. */
  23475. this.isCatmullRomCurve3 = true;
  23476. this.type = 'CatmullRomCurve3';
  23477. /**
  23478. * An array of 3D points defining the curve.
  23479. *
  23480. * @type {Array<Vector3>}
  23481. */
  23482. this.points = points;
  23483. /**
  23484. * Whether the curve is closed or not.
  23485. *
  23486. * @type {boolean}
  23487. * @default false
  23488. */
  23489. this.closed = closed;
  23490. /**
  23491. * The curve type.
  23492. *
  23493. * @type {('centripetal'|'chordal'|'catmullrom')}
  23494. * @default 'centripetal'
  23495. */
  23496. this.curveType = curveType;
  23497. /**
  23498. * Tension of the curve.
  23499. *
  23500. * @type {number}
  23501. * @default 0.5
  23502. */
  23503. this.tension = tension;
  23504. }
  23505. /**
  23506. * Returns a point on the curve.
  23507. *
  23508. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23509. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23510. * @return {Vector3} The position on the curve.
  23511. */
  23512. getPoint( t, optionalTarget = new Vector3() ) {
  23513. const point = optionalTarget;
  23514. const points = this.points;
  23515. const l = points.length;
  23516. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23517. let intPoint = Math.floor( p );
  23518. let weight = p - intPoint;
  23519. if ( this.closed ) {
  23520. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23521. } else if ( weight === 0 && intPoint === l - 1 ) {
  23522. intPoint = l - 2;
  23523. weight = 1;
  23524. }
  23525. let p0, p3; // 4 points (p1 & p2 defined below)
  23526. if ( this.closed || intPoint > 0 ) {
  23527. p0 = points[ ( intPoint - 1 ) % l ];
  23528. } else {
  23529. // extrapolate first point
  23530. tmp2.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23531. p0 = tmp2;
  23532. }
  23533. const p1 = points[ intPoint % l ];
  23534. const p2 = points[ ( intPoint + 1 ) % l ];
  23535. if ( this.closed || intPoint + 2 < l ) {
  23536. p3 = points[ ( intPoint + 2 ) % l ];
  23537. } else {
  23538. // extrapolate last point
  23539. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23540. p3 = tmp;
  23541. }
  23542. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23543. // init Centripetal / Chordal Catmull-Rom
  23544. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23545. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23546. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23547. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23548. // safety check for repeated points
  23549. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23550. if ( dt0 < 1e-4 ) dt0 = dt1;
  23551. if ( dt2 < 1e-4 ) dt2 = dt1;
  23552. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23553. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23554. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23555. } else if ( this.curveType === 'catmullrom' ) {
  23556. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23557. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23558. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23559. }
  23560. point.set(
  23561. px.calc( weight ),
  23562. py.calc( weight ),
  23563. pz.calc( weight )
  23564. );
  23565. return point;
  23566. }
  23567. copy( source ) {
  23568. super.copy( source );
  23569. this.points = [];
  23570. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23571. const point = source.points[ i ];
  23572. this.points.push( point.clone() );
  23573. }
  23574. this.closed = source.closed;
  23575. this.curveType = source.curveType;
  23576. this.tension = source.tension;
  23577. return this;
  23578. }
  23579. toJSON() {
  23580. const data = super.toJSON();
  23581. data.points = [];
  23582. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23583. const point = this.points[ i ];
  23584. data.points.push( point.toArray() );
  23585. }
  23586. data.closed = this.closed;
  23587. data.curveType = this.curveType;
  23588. data.tension = this.tension;
  23589. return data;
  23590. }
  23591. fromJSON( json ) {
  23592. super.fromJSON( json );
  23593. this.points = [];
  23594. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23595. const point = json.points[ i ];
  23596. this.points.push( new Vector3().fromArray( point ) );
  23597. }
  23598. this.closed = json.closed;
  23599. this.curveType = json.curveType;
  23600. this.tension = json.tension;
  23601. return this;
  23602. }
  23603. }
  23604. /**
  23605. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  23606. *
  23607. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23608. *
  23609. * @module Interpolations
  23610. */
  23611. /**
  23612. * Computes a point on a Catmull-Rom spline.
  23613. *
  23614. * @param {number} t - The interpolation factor.
  23615. * @param {number} p0 - The first control point.
  23616. * @param {number} p1 - The second control point.
  23617. * @param {number} p2 - The third control point.
  23618. * @param {number} p3 - The fourth control point.
  23619. * @return {number} The calculated point on a Catmull-Rom spline.
  23620. */
  23621. function CatmullRom( t, p0, p1, p2, p3 ) {
  23622. const v0 = ( p2 - p0 ) * 0.5;
  23623. const v1 = ( p3 - p1 ) * 0.5;
  23624. const t2 = t * t;
  23625. const t3 = t * t2;
  23626. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23627. }
  23628. //
  23629. function QuadraticBezierP0( t, p ) {
  23630. const k = 1 - t;
  23631. return k * k * p;
  23632. }
  23633. function QuadraticBezierP1( t, p ) {
  23634. return 2 * ( 1 - t ) * t * p;
  23635. }
  23636. function QuadraticBezierP2( t, p ) {
  23637. return t * t * p;
  23638. }
  23639. /**
  23640. * Computes a point on a Quadratic Bezier curve.
  23641. *
  23642. * @param {number} t - The interpolation factor.
  23643. * @param {number} p0 - The first control point.
  23644. * @param {number} p1 - The second control point.
  23645. * @param {number} p2 - The third control point.
  23646. * @return {number} The calculated point on a Quadratic Bezier curve.
  23647. */
  23648. function QuadraticBezier( t, p0, p1, p2 ) {
  23649. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23650. QuadraticBezierP2( t, p2 );
  23651. }
  23652. //
  23653. function CubicBezierP0( t, p ) {
  23654. const k = 1 - t;
  23655. return k * k * k * p;
  23656. }
  23657. function CubicBezierP1( t, p ) {
  23658. const k = 1 - t;
  23659. return 3 * k * k * t * p;
  23660. }
  23661. function CubicBezierP2( t, p ) {
  23662. return 3 * ( 1 - t ) * t * t * p;
  23663. }
  23664. function CubicBezierP3( t, p ) {
  23665. return t * t * t * p;
  23666. }
  23667. /**
  23668. * Computes a point on a Cubic Bezier curve.
  23669. *
  23670. * @param {number} t - The interpolation factor.
  23671. * @param {number} p0 - The first control point.
  23672. * @param {number} p1 - The second control point.
  23673. * @param {number} p2 - The third control point.
  23674. * @param {number} p3 - The fourth control point.
  23675. * @return {number} The calculated point on a Cubic Bezier curve.
  23676. */
  23677. function CubicBezier( t, p0, p1, p2, p3 ) {
  23678. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23679. CubicBezierP3( t, p3 );
  23680. }
  23681. /**
  23682. * A curve representing a 2D Cubic Bezier curve.
  23683. *
  23684. * ```js
  23685. * const curve = new THREE.CubicBezierCurve(
  23686. * new THREE.Vector2( - 0, 0 ),
  23687. * new THREE.Vector2( - 5, 15 ),
  23688. * new THREE.Vector2( 20, 15 ),
  23689. * new THREE.Vector2( 10, 0 )
  23690. * );
  23691. *
  23692. * const points = curve.getPoints( 50 );
  23693. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23694. *
  23695. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23696. *
  23697. * // Create the final object to add to the scene
  23698. * const curveObject = new THREE.Line( geometry, material );
  23699. * ```
  23700. *
  23701. * @augments Curve
  23702. */
  23703. class CubicBezierCurve extends Curve {
  23704. /**
  23705. * Constructs a new Cubic Bezier curve.
  23706. *
  23707. * @param {Vector2} [v0] - The start point.
  23708. * @param {Vector2} [v1] - The first control point.
  23709. * @param {Vector2} [v2] - The second control point.
  23710. * @param {Vector2} [v3] - The end point.
  23711. */
  23712. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23713. super();
  23714. /**
  23715. * This flag can be used for type testing.
  23716. *
  23717. * @type {boolean}
  23718. * @readonly
  23719. * @default true
  23720. */
  23721. this.isCubicBezierCurve = true;
  23722. this.type = 'CubicBezierCurve';
  23723. /**
  23724. * The start point.
  23725. *
  23726. * @type {Vector2}
  23727. */
  23728. this.v0 = v0;
  23729. /**
  23730. * The first control point.
  23731. *
  23732. * @type {Vector2}
  23733. */
  23734. this.v1 = v1;
  23735. /**
  23736. * The second control point.
  23737. *
  23738. * @type {Vector2}
  23739. */
  23740. this.v2 = v2;
  23741. /**
  23742. * The end point.
  23743. *
  23744. * @type {Vector2}
  23745. */
  23746. this.v3 = v3;
  23747. }
  23748. /**
  23749. * Returns a point on the curve.
  23750. *
  23751. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23752. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23753. * @return {Vector2} The position on the curve.
  23754. */
  23755. getPoint( t, optionalTarget = new Vector2() ) {
  23756. const point = optionalTarget;
  23757. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23758. point.set(
  23759. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23760. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23761. );
  23762. return point;
  23763. }
  23764. copy( source ) {
  23765. super.copy( source );
  23766. this.v0.copy( source.v0 );
  23767. this.v1.copy( source.v1 );
  23768. this.v2.copy( source.v2 );
  23769. this.v3.copy( source.v3 );
  23770. return this;
  23771. }
  23772. toJSON() {
  23773. const data = super.toJSON();
  23774. data.v0 = this.v0.toArray();
  23775. data.v1 = this.v1.toArray();
  23776. data.v2 = this.v2.toArray();
  23777. data.v3 = this.v3.toArray();
  23778. return data;
  23779. }
  23780. fromJSON( json ) {
  23781. super.fromJSON( json );
  23782. this.v0.fromArray( json.v0 );
  23783. this.v1.fromArray( json.v1 );
  23784. this.v2.fromArray( json.v2 );
  23785. this.v3.fromArray( json.v3 );
  23786. return this;
  23787. }
  23788. }
  23789. /**
  23790. * A curve representing a 3D Cubic Bezier curve.
  23791. *
  23792. * @augments Curve
  23793. */
  23794. class CubicBezierCurve3 extends Curve {
  23795. /**
  23796. * Constructs a new Cubic Bezier curve.
  23797. *
  23798. * @param {Vector3} [v0] - The start point.
  23799. * @param {Vector3} [v1] - The first control point.
  23800. * @param {Vector3} [v2] - The second control point.
  23801. * @param {Vector3} [v3] - The end point.
  23802. */
  23803. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23804. super();
  23805. /**
  23806. * This flag can be used for type testing.
  23807. *
  23808. * @type {boolean}
  23809. * @readonly
  23810. * @default true
  23811. */
  23812. this.isCubicBezierCurve3 = true;
  23813. this.type = 'CubicBezierCurve3';
  23814. /**
  23815. * The start point.
  23816. *
  23817. * @type {Vector3}
  23818. */
  23819. this.v0 = v0;
  23820. /**
  23821. * The first control point.
  23822. *
  23823. * @type {Vector3}
  23824. */
  23825. this.v1 = v1;
  23826. /**
  23827. * The second control point.
  23828. *
  23829. * @type {Vector3}
  23830. */
  23831. this.v2 = v2;
  23832. /**
  23833. * The end point.
  23834. *
  23835. * @type {Vector3}
  23836. */
  23837. this.v3 = v3;
  23838. }
  23839. /**
  23840. * Returns a point on the curve.
  23841. *
  23842. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23843. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23844. * @return {Vector3} The position on the curve.
  23845. */
  23846. getPoint( t, optionalTarget = new Vector3() ) {
  23847. const point = optionalTarget;
  23848. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23849. point.set(
  23850. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23851. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23852. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23853. );
  23854. return point;
  23855. }
  23856. copy( source ) {
  23857. super.copy( source );
  23858. this.v0.copy( source.v0 );
  23859. this.v1.copy( source.v1 );
  23860. this.v2.copy( source.v2 );
  23861. this.v3.copy( source.v3 );
  23862. return this;
  23863. }
  23864. toJSON() {
  23865. const data = super.toJSON();
  23866. data.v0 = this.v0.toArray();
  23867. data.v1 = this.v1.toArray();
  23868. data.v2 = this.v2.toArray();
  23869. data.v3 = this.v3.toArray();
  23870. return data;
  23871. }
  23872. fromJSON( json ) {
  23873. super.fromJSON( json );
  23874. this.v0.fromArray( json.v0 );
  23875. this.v1.fromArray( json.v1 );
  23876. this.v2.fromArray( json.v2 );
  23877. this.v3.fromArray( json.v3 );
  23878. return this;
  23879. }
  23880. }
  23881. /**
  23882. * A curve representing a 2D line segment.
  23883. *
  23884. * @augments Curve
  23885. */
  23886. class LineCurve extends Curve {
  23887. /**
  23888. * Constructs a new line curve.
  23889. *
  23890. * @param {Vector2} [v1] - The start point.
  23891. * @param {Vector2} [v2] - The end point.
  23892. */
  23893. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  23894. super();
  23895. /**
  23896. * This flag can be used for type testing.
  23897. *
  23898. * @type {boolean}
  23899. * @readonly
  23900. * @default true
  23901. */
  23902. this.isLineCurve = true;
  23903. this.type = 'LineCurve';
  23904. /**
  23905. * The start point.
  23906. *
  23907. * @type {Vector2}
  23908. */
  23909. this.v1 = v1;
  23910. /**
  23911. * The end point.
  23912. *
  23913. * @type {Vector2}
  23914. */
  23915. this.v2 = v2;
  23916. }
  23917. /**
  23918. * Returns a point on the line.
  23919. *
  23920. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23921. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23922. * @return {Vector2} The position on the line.
  23923. */
  23924. getPoint( t, optionalTarget = new Vector2() ) {
  23925. const point = optionalTarget;
  23926. if ( t === 1 ) {
  23927. point.copy( this.v2 );
  23928. } else {
  23929. point.copy( this.v2 ).sub( this.v1 );
  23930. point.multiplyScalar( t ).add( this.v1 );
  23931. }
  23932. return point;
  23933. }
  23934. // Line curve is linear, so we can overwrite default getPointAt
  23935. getPointAt( u, optionalTarget ) {
  23936. return this.getPoint( u, optionalTarget );
  23937. }
  23938. getTangent( t, optionalTarget = new Vector2() ) {
  23939. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23940. }
  23941. getTangentAt( u, optionalTarget ) {
  23942. return this.getTangent( u, optionalTarget );
  23943. }
  23944. copy( source ) {
  23945. super.copy( source );
  23946. this.v1.copy( source.v1 );
  23947. this.v2.copy( source.v2 );
  23948. return this;
  23949. }
  23950. toJSON() {
  23951. const data = super.toJSON();
  23952. data.v1 = this.v1.toArray();
  23953. data.v2 = this.v2.toArray();
  23954. return data;
  23955. }
  23956. fromJSON( json ) {
  23957. super.fromJSON( json );
  23958. this.v1.fromArray( json.v1 );
  23959. this.v2.fromArray( json.v2 );
  23960. return this;
  23961. }
  23962. }
  23963. /**
  23964. * A curve representing a 3D line segment.
  23965. *
  23966. * @augments Curve
  23967. */
  23968. class LineCurve3 extends Curve {
  23969. /**
  23970. * Constructs a new line curve.
  23971. *
  23972. * @param {Vector3} [v1] - The start point.
  23973. * @param {Vector3} [v2] - The end point.
  23974. */
  23975. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  23976. super();
  23977. /**
  23978. * This flag can be used for type testing.
  23979. *
  23980. * @type {boolean}
  23981. * @readonly
  23982. * @default true
  23983. */
  23984. this.isLineCurve3 = true;
  23985. this.type = 'LineCurve3';
  23986. /**
  23987. * The start point.
  23988. *
  23989. * @type {Vector3}
  23990. */
  23991. this.v1 = v1;
  23992. /**
  23993. * The end point.
  23994. *
  23995. * @type {Vector2}
  23996. */
  23997. this.v2 = v2;
  23998. }
  23999. /**
  24000. * Returns a point on the line.
  24001. *
  24002. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24003. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24004. * @return {Vector3} The position on the line.
  24005. */
  24006. getPoint( t, optionalTarget = new Vector3() ) {
  24007. const point = optionalTarget;
  24008. if ( t === 1 ) {
  24009. point.copy( this.v2 );
  24010. } else {
  24011. point.copy( this.v2 ).sub( this.v1 );
  24012. point.multiplyScalar( t ).add( this.v1 );
  24013. }
  24014. return point;
  24015. }
  24016. // Line curve is linear, so we can overwrite default getPointAt
  24017. getPointAt( u, optionalTarget ) {
  24018. return this.getPoint( u, optionalTarget );
  24019. }
  24020. getTangent( t, optionalTarget = new Vector3() ) {
  24021. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24022. }
  24023. getTangentAt( u, optionalTarget ) {
  24024. return this.getTangent( u, optionalTarget );
  24025. }
  24026. copy( source ) {
  24027. super.copy( source );
  24028. this.v1.copy( source.v1 );
  24029. this.v2.copy( source.v2 );
  24030. return this;
  24031. }
  24032. toJSON() {
  24033. const data = super.toJSON();
  24034. data.v1 = this.v1.toArray();
  24035. data.v2 = this.v2.toArray();
  24036. return data;
  24037. }
  24038. fromJSON( json ) {
  24039. super.fromJSON( json );
  24040. this.v1.fromArray( json.v1 );
  24041. this.v2.fromArray( json.v2 );
  24042. return this;
  24043. }
  24044. }
  24045. /**
  24046. * A curve representing a 2D Quadratic Bezier curve.
  24047. *
  24048. * ```js
  24049. * const curve = new THREE.QuadraticBezierCurve(
  24050. * new THREE.Vector2( - 10, 0 ),
  24051. * new THREE.Vector2( 20, 15 ),
  24052. * new THREE.Vector2( 10, 0 )
  24053. * )
  24054. *
  24055. * const points = curve.getPoints( 50 );
  24056. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24057. *
  24058. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24059. *
  24060. * // Create the final object to add to the scene
  24061. * const curveObject = new THREE.Line( geometry, material );
  24062. * ```
  24063. *
  24064. * @augments Curve
  24065. */
  24066. class QuadraticBezierCurve extends Curve {
  24067. /**
  24068. * Constructs a new Quadratic Bezier curve.
  24069. *
  24070. * @param {Vector2} [v0] - The start point.
  24071. * @param {Vector2} [v1] - The control point.
  24072. * @param {Vector2} [v2] - The end point.
  24073. */
  24074. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24075. super();
  24076. /**
  24077. * This flag can be used for type testing.
  24078. *
  24079. * @type {boolean}
  24080. * @readonly
  24081. * @default true
  24082. */
  24083. this.isQuadraticBezierCurve = true;
  24084. this.type = 'QuadraticBezierCurve';
  24085. /**
  24086. * The start point.
  24087. *
  24088. * @type {Vector2}
  24089. */
  24090. this.v0 = v0;
  24091. /**
  24092. * The control point.
  24093. *
  24094. * @type {Vector2}
  24095. */
  24096. this.v1 = v1;
  24097. /**
  24098. * The end point.
  24099. *
  24100. * @type {Vector2}
  24101. */
  24102. this.v2 = v2;
  24103. }
  24104. /**
  24105. * Returns a point on the curve.
  24106. *
  24107. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24108. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24109. * @return {Vector2} The position on the curve.
  24110. */
  24111. getPoint( t, optionalTarget = new Vector2() ) {
  24112. const point = optionalTarget;
  24113. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24114. point.set(
  24115. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24116. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24117. );
  24118. return point;
  24119. }
  24120. copy( source ) {
  24121. super.copy( source );
  24122. this.v0.copy( source.v0 );
  24123. this.v1.copy( source.v1 );
  24124. this.v2.copy( source.v2 );
  24125. return this;
  24126. }
  24127. toJSON() {
  24128. const data = super.toJSON();
  24129. data.v0 = this.v0.toArray();
  24130. data.v1 = this.v1.toArray();
  24131. data.v2 = this.v2.toArray();
  24132. return data;
  24133. }
  24134. fromJSON( json ) {
  24135. super.fromJSON( json );
  24136. this.v0.fromArray( json.v0 );
  24137. this.v1.fromArray( json.v1 );
  24138. this.v2.fromArray( json.v2 );
  24139. return this;
  24140. }
  24141. }
  24142. /**
  24143. * A curve representing a 3D Quadratic Bezier curve.
  24144. *
  24145. * @augments Curve
  24146. */
  24147. class QuadraticBezierCurve3 extends Curve {
  24148. /**
  24149. * Constructs a new Quadratic Bezier curve.
  24150. *
  24151. * @param {Vector3} [v0] - The start point.
  24152. * @param {Vector3} [v1] - The control point.
  24153. * @param {Vector3} [v2] - The end point.
  24154. */
  24155. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24156. super();
  24157. /**
  24158. * This flag can be used for type testing.
  24159. *
  24160. * @type {boolean}
  24161. * @readonly
  24162. * @default true
  24163. */
  24164. this.isQuadraticBezierCurve3 = true;
  24165. this.type = 'QuadraticBezierCurve3';
  24166. /**
  24167. * The start point.
  24168. *
  24169. * @type {Vector3}
  24170. */
  24171. this.v0 = v0;
  24172. /**
  24173. * The control point.
  24174. *
  24175. * @type {Vector3}
  24176. */
  24177. this.v1 = v1;
  24178. /**
  24179. * The end point.
  24180. *
  24181. * @type {Vector3}
  24182. */
  24183. this.v2 = v2;
  24184. }
  24185. /**
  24186. * Returns a point on the curve.
  24187. *
  24188. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24189. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24190. * @return {Vector3} The position on the curve.
  24191. */
  24192. getPoint( t, optionalTarget = new Vector3() ) {
  24193. const point = optionalTarget;
  24194. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24195. point.set(
  24196. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24197. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24198. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24199. );
  24200. return point;
  24201. }
  24202. copy( source ) {
  24203. super.copy( source );
  24204. this.v0.copy( source.v0 );
  24205. this.v1.copy( source.v1 );
  24206. this.v2.copy( source.v2 );
  24207. return this;
  24208. }
  24209. toJSON() {
  24210. const data = super.toJSON();
  24211. data.v0 = this.v0.toArray();
  24212. data.v1 = this.v1.toArray();
  24213. data.v2 = this.v2.toArray();
  24214. return data;
  24215. }
  24216. fromJSON( json ) {
  24217. super.fromJSON( json );
  24218. this.v0.fromArray( json.v0 );
  24219. this.v1.fromArray( json.v1 );
  24220. this.v2.fromArray( json.v2 );
  24221. return this;
  24222. }
  24223. }
  24224. /**
  24225. * A curve representing a 2D spline curve.
  24226. *
  24227. * ```js
  24228. * // Create a sine-like wave
  24229. * const curve = new THREE.SplineCurve( [
  24230. * new THREE.Vector2( -10, 0 ),
  24231. * new THREE.Vector2( -5, 5 ),
  24232. * new THREE.Vector2( 0, 0 ),
  24233. * new THREE.Vector2( 5, -5 ),
  24234. * new THREE.Vector2( 10, 0 )
  24235. * ] );
  24236. *
  24237. * const points = curve.getPoints( 50 );
  24238. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24239. *
  24240. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24241. *
  24242. * // Create the final object to add to the scene
  24243. * const splineObject = new THREE.Line( geometry, material );
  24244. * ```
  24245. *
  24246. * @augments Curve
  24247. */
  24248. class SplineCurve extends Curve {
  24249. /**
  24250. * Constructs a new 2D spline curve.
  24251. *
  24252. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24253. */
  24254. constructor( points = [] ) {
  24255. super();
  24256. /**
  24257. * This flag can be used for type testing.
  24258. *
  24259. * @type {boolean}
  24260. * @readonly
  24261. * @default true
  24262. */
  24263. this.isSplineCurve = true;
  24264. this.type = 'SplineCurve';
  24265. /**
  24266. * An array of 2D points defining the curve.
  24267. *
  24268. * @type {Array<Vector2>}
  24269. */
  24270. this.points = points;
  24271. }
  24272. /**
  24273. * Returns a point on the curve.
  24274. *
  24275. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24276. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24277. * @return {Vector2} The position on the curve.
  24278. */
  24279. getPoint( t, optionalTarget = new Vector2() ) {
  24280. const point = optionalTarget;
  24281. const points = this.points;
  24282. const p = ( points.length - 1 ) * t;
  24283. const intPoint = Math.floor( p );
  24284. const weight = p - intPoint;
  24285. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24286. const p1 = points[ intPoint ];
  24287. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24288. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24289. point.set(
  24290. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24291. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24292. );
  24293. return point;
  24294. }
  24295. copy( source ) {
  24296. super.copy( source );
  24297. this.points = [];
  24298. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24299. const point = source.points[ i ];
  24300. this.points.push( point.clone() );
  24301. }
  24302. return this;
  24303. }
  24304. toJSON() {
  24305. const data = super.toJSON();
  24306. data.points = [];
  24307. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24308. const point = this.points[ i ];
  24309. data.points.push( point.toArray() );
  24310. }
  24311. return data;
  24312. }
  24313. fromJSON( json ) {
  24314. super.fromJSON( json );
  24315. this.points = [];
  24316. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24317. const point = json.points[ i ];
  24318. this.points.push( new Vector2().fromArray( point ) );
  24319. }
  24320. return this;
  24321. }
  24322. }
  24323. var Curves = /*#__PURE__*/Object.freeze({
  24324. __proto__: null,
  24325. ArcCurve: ArcCurve,
  24326. CatmullRomCurve3: CatmullRomCurve3,
  24327. CubicBezierCurve: CubicBezierCurve,
  24328. CubicBezierCurve3: CubicBezierCurve3,
  24329. EllipseCurve: EllipseCurve,
  24330. LineCurve: LineCurve,
  24331. LineCurve3: LineCurve3,
  24332. QuadraticBezierCurve: QuadraticBezierCurve,
  24333. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24334. SplineCurve: SplineCurve
  24335. });
  24336. /**
  24337. * A base class extending {@link Curve}. `CurvePath` is simply an
  24338. * array of connected curves, but retains the API of a curve.
  24339. *
  24340. * @augments Curve
  24341. */
  24342. class CurvePath extends Curve {
  24343. /**
  24344. * Constructs a new curve path.
  24345. */
  24346. constructor() {
  24347. super();
  24348. this.type = 'CurvePath';
  24349. /**
  24350. * An array of curves defining the
  24351. * path.
  24352. *
  24353. * @type {Array<Curve>}
  24354. */
  24355. this.curves = [];
  24356. /**
  24357. * Whether the path should automatically be closed
  24358. * by a line curve.
  24359. *
  24360. * @type {boolean}
  24361. * @default false
  24362. */
  24363. this.autoClose = false;
  24364. }
  24365. /**
  24366. * Adds a curve to this curve path.
  24367. *
  24368. * @param {Curve} curve - The curve to add.
  24369. */
  24370. add( curve ) {
  24371. this.curves.push( curve );
  24372. }
  24373. /**
  24374. * Adds a line curve to close the path.
  24375. *
  24376. * @return {CurvePath} A reference to this curve path.
  24377. */
  24378. closePath() {
  24379. // Add a line curve if start and end of lines are not connected
  24380. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24381. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24382. if ( ! startPoint.equals( endPoint ) ) {
  24383. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24384. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24385. }
  24386. return this;
  24387. }
  24388. /**
  24389. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24390. * for the given interpolation factor.
  24391. *
  24392. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24393. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24394. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24395. */
  24396. getPoint( t, optionalTarget ) {
  24397. // To get accurate point with reference to
  24398. // entire path distance at time t,
  24399. // following has to be done:
  24400. // 1. Length of each sub path have to be known
  24401. // 2. Locate and identify type of curve
  24402. // 3. Get t for the curve
  24403. // 4. Return curve.getPointAt(t')
  24404. const d = t * this.getLength();
  24405. const curveLengths = this.getCurveLengths();
  24406. let i = 0;
  24407. // To think about boundaries points.
  24408. while ( i < curveLengths.length ) {
  24409. if ( curveLengths[ i ] >= d ) {
  24410. const diff = curveLengths[ i ] - d;
  24411. const curve = this.curves[ i ];
  24412. const segmentLength = curve.getLength();
  24413. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24414. return curve.getPointAt( u, optionalTarget );
  24415. }
  24416. i ++;
  24417. }
  24418. return null;
  24419. // loop where sum != 0, sum > d , sum+1 <d
  24420. }
  24421. getLength() {
  24422. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24423. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24424. // getPoint() depends on getLength
  24425. const lens = this.getCurveLengths();
  24426. return lens[ lens.length - 1 ];
  24427. }
  24428. updateArcLengths() {
  24429. // cacheLengths must be recalculated.
  24430. this.needsUpdate = true;
  24431. this.cacheLengths = null;
  24432. this.getCurveLengths();
  24433. }
  24434. /**
  24435. * Returns list of cumulative curve lengths of the defined curves.
  24436. *
  24437. * @return {Array<number>} The curve lengths.
  24438. */
  24439. getCurveLengths() {
  24440. // Compute lengths and cache them
  24441. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24442. // We use cache values if curves and cache array are same length
  24443. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24444. return this.cacheLengths;
  24445. }
  24446. // Get length of sub-curve
  24447. // Push sums into cached array
  24448. const lengths = [];
  24449. let sums = 0;
  24450. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24451. sums += this.curves[ i ].getLength();
  24452. lengths.push( sums );
  24453. }
  24454. this.cacheLengths = lengths;
  24455. return lengths;
  24456. }
  24457. getSpacedPoints( divisions = 40 ) {
  24458. const points = [];
  24459. for ( let i = 0; i <= divisions; i ++ ) {
  24460. points.push( this.getPoint( i / divisions ) );
  24461. }
  24462. if ( this.autoClose ) {
  24463. points.push( points[ 0 ] );
  24464. }
  24465. return points;
  24466. }
  24467. getPoints( divisions = 12 ) {
  24468. const points = [];
  24469. let last;
  24470. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24471. const curve = curves[ i ];
  24472. const resolution = curve.isEllipseCurve ? divisions * 2
  24473. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24474. : curve.isSplineCurve ? divisions * curve.points.length
  24475. : divisions;
  24476. const pts = curve.getPoints( resolution );
  24477. for ( let j = 0; j < pts.length; j ++ ) {
  24478. const point = pts[ j ];
  24479. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24480. points.push( point );
  24481. last = point;
  24482. }
  24483. }
  24484. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24485. points.push( points[ 0 ] );
  24486. }
  24487. return points;
  24488. }
  24489. copy( source ) {
  24490. super.copy( source );
  24491. this.curves = [];
  24492. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24493. const curve = source.curves[ i ];
  24494. this.curves.push( curve.clone() );
  24495. }
  24496. this.autoClose = source.autoClose;
  24497. return this;
  24498. }
  24499. toJSON() {
  24500. const data = super.toJSON();
  24501. data.autoClose = this.autoClose;
  24502. data.curves = [];
  24503. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24504. const curve = this.curves[ i ];
  24505. data.curves.push( curve.toJSON() );
  24506. }
  24507. return data;
  24508. }
  24509. fromJSON( json ) {
  24510. super.fromJSON( json );
  24511. this.autoClose = json.autoClose;
  24512. this.curves = [];
  24513. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24514. const curve = json.curves[ i ];
  24515. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24516. }
  24517. return this;
  24518. }
  24519. }
  24520. /**
  24521. * A 2D path representation. The class provides methods for creating paths
  24522. * and contours of 2D shapes similar to the 2D Canvas API.
  24523. *
  24524. * ```js
  24525. * const path = new THREE.Path();
  24526. *
  24527. * path.lineTo( 0, 0.8 );
  24528. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24529. * path.lineTo( 1, 1 );
  24530. *
  24531. * const points = path.getPoints();
  24532. *
  24533. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24534. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24535. *
  24536. * const line = new THREE.Line( geometry, material );
  24537. * scene.add( line );
  24538. * ```
  24539. *
  24540. * @augments CurvePath
  24541. */
  24542. class Path extends CurvePath {
  24543. /**
  24544. * Constructs a new path.
  24545. *
  24546. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24547. */
  24548. constructor( points ) {
  24549. super();
  24550. this.type = 'Path';
  24551. /**
  24552. * The current offset of the path. Any new curve added will start here.
  24553. *
  24554. * @type {Vector2}
  24555. */
  24556. this.currentPoint = new Vector2();
  24557. if ( points ) {
  24558. this.setFromPoints( points );
  24559. }
  24560. }
  24561. /**
  24562. * Creates a path from the given list of points. The points are added
  24563. * to the path as instances of {@link LineCurve}.
  24564. *
  24565. * @param {Array<Vector2>} points - An array of 2D points.
  24566. * @return {Path} A reference to this path.
  24567. */
  24568. setFromPoints( points ) {
  24569. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24570. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24571. this.lineTo( points[ i ].x, points[ i ].y );
  24572. }
  24573. return this;
  24574. }
  24575. /**
  24576. * Moves {@link Path#currentPoint} to the given point.
  24577. *
  24578. * @param {number} x - The x coordinate.
  24579. * @param {number} y - The y coordinate.
  24580. * @return {Path} A reference to this path.
  24581. */
  24582. moveTo( x, y ) {
  24583. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24584. return this;
  24585. }
  24586. /**
  24587. * Adds an instance of {@link LineCurve} to the path by connecting
  24588. * the current point with the given one.
  24589. *
  24590. * @param {number} x - The x coordinate of the end point.
  24591. * @param {number} y - The y coordinate of the end point.
  24592. * @return {Path} A reference to this path.
  24593. */
  24594. lineTo( x, y ) {
  24595. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24596. this.curves.push( curve );
  24597. this.currentPoint.set( x, y );
  24598. return this;
  24599. }
  24600. /**
  24601. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24602. * the current point with the given one.
  24603. *
  24604. * @param {number} aCPx - The x coordinate of the control point.
  24605. * @param {number} aCPy - The y coordinate of the control point.
  24606. * @param {number} aX - The x coordinate of the end point.
  24607. * @param {number} aY - The y coordinate of the end point.
  24608. * @return {Path} A reference to this path.
  24609. */
  24610. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24611. const curve = new QuadraticBezierCurve(
  24612. this.currentPoint.clone(),
  24613. new Vector2( aCPx, aCPy ),
  24614. new Vector2( aX, aY )
  24615. );
  24616. this.curves.push( curve );
  24617. this.currentPoint.set( aX, aY );
  24618. return this;
  24619. }
  24620. /**
  24621. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24622. * the current point with the given one.
  24623. *
  24624. * @param {number} aCP1x - The x coordinate of the first control point.
  24625. * @param {number} aCP1y - The y coordinate of the first control point.
  24626. * @param {number} aCP2x - The x coordinate of the second control point.
  24627. * @param {number} aCP2y - The y coordinate of the second control point.
  24628. * @param {number} aX - The x coordinate of the end point.
  24629. * @param {number} aY - The y coordinate of the end point.
  24630. * @return {Path} A reference to this path.
  24631. */
  24632. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24633. const curve = new CubicBezierCurve(
  24634. this.currentPoint.clone(),
  24635. new Vector2( aCP1x, aCP1y ),
  24636. new Vector2( aCP2x, aCP2y ),
  24637. new Vector2( aX, aY )
  24638. );
  24639. this.curves.push( curve );
  24640. this.currentPoint.set( aX, aY );
  24641. return this;
  24642. }
  24643. /**
  24644. * Adds an instance of {@link SplineCurve} to the path by connecting
  24645. * the current point with the given list of points.
  24646. *
  24647. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24648. * @return {Path} A reference to this path.
  24649. */
  24650. splineThru( pts ) {
  24651. const npts = [ this.currentPoint.clone() ].concat( pts );
  24652. const curve = new SplineCurve( npts );
  24653. this.curves.push( curve );
  24654. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24655. return this;
  24656. }
  24657. /**
  24658. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24659. * to the current point.
  24660. *
  24661. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24662. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24663. * @param {number} [aRadius=1] - The radius of the arc.
  24664. * @param {number} [aStartAngle=0] - The start angle in radians.
  24665. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24666. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24667. * @return {Path} A reference to this path.
  24668. */
  24669. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24670. const x0 = this.currentPoint.x;
  24671. const y0 = this.currentPoint.y;
  24672. this.absarc( aX + x0, aY + y0, aRadius,
  24673. aStartAngle, aEndAngle, aClockwise );
  24674. return this;
  24675. }
  24676. /**
  24677. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24678. *
  24679. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24680. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24681. * @param {number} [aRadius=1] - The radius of the arc.
  24682. * @param {number} [aStartAngle=0] - The start angle in radians.
  24683. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24684. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24685. * @return {Path} A reference to this path.
  24686. */
  24687. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24688. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24689. return this;
  24690. }
  24691. /**
  24692. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24693. * to the current point
  24694. *
  24695. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24696. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24697. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24698. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24699. * @param {number} [aStartAngle=0] - The start angle in radians.
  24700. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24701. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24702. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24703. * @return {Path} A reference to this path.
  24704. */
  24705. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24706. const x0 = this.currentPoint.x;
  24707. const y0 = this.currentPoint.y;
  24708. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24709. return this;
  24710. }
  24711. /**
  24712. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24713. *
  24714. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24715. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24716. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24717. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24718. * @param {number} [aStartAngle=0] - The start angle in radians.
  24719. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24720. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24721. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24722. * @return {Path} A reference to this path.
  24723. */
  24724. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24725. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24726. if ( this.curves.length > 0 ) {
  24727. // if a previous curve is present, attempt to join
  24728. const firstPoint = curve.getPoint( 0 );
  24729. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24730. this.lineTo( firstPoint.x, firstPoint.y );
  24731. }
  24732. }
  24733. this.curves.push( curve );
  24734. const lastPoint = curve.getPoint( 1 );
  24735. this.currentPoint.copy( lastPoint );
  24736. return this;
  24737. }
  24738. copy( source ) {
  24739. super.copy( source );
  24740. this.currentPoint.copy( source.currentPoint );
  24741. return this;
  24742. }
  24743. toJSON() {
  24744. const data = super.toJSON();
  24745. data.currentPoint = this.currentPoint.toArray();
  24746. return data;
  24747. }
  24748. fromJSON( json ) {
  24749. super.fromJSON( json );
  24750. this.currentPoint.fromArray( json.currentPoint );
  24751. return this;
  24752. }
  24753. }
  24754. /**
  24755. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24756. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24757. * points, or to get triangulated faces.
  24758. *
  24759. * ```js
  24760. * const heartShape = new THREE.Shape();
  24761. *
  24762. * heartShape.moveTo( 25, 25 );
  24763. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24764. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24765. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24766. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24767. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24768. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24769. *
  24770. * const extrudeSettings = {
  24771. * depth: 8,
  24772. * bevelEnabled: true,
  24773. * bevelSegments: 2,
  24774. * steps: 2,
  24775. * bevelSize: 1,
  24776. * bevelThickness: 1
  24777. * };
  24778. *
  24779. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24780. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24781. * ```
  24782. *
  24783. * @augments Path
  24784. */
  24785. class Shape extends Path {
  24786. /**
  24787. * Constructs a new shape.
  24788. *
  24789. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24790. */
  24791. constructor( points ) {
  24792. super( points );
  24793. /**
  24794. * The UUID of the shape.
  24795. *
  24796. * @type {string}
  24797. * @readonly
  24798. */
  24799. this.uuid = generateUUID();
  24800. this.type = 'Shape';
  24801. /**
  24802. * Defines the holes in the shape. Hole definitions must use the
  24803. * opposite winding order (CW/CCW) than the outer shape.
  24804. *
  24805. * @type {Array<Path>}
  24806. * @readonly
  24807. */
  24808. this.holes = [];
  24809. }
  24810. /**
  24811. * Returns an array representing each contour of the holes
  24812. * as a list of 2D points.
  24813. *
  24814. * @param {number} divisions - The fineness of the result.
  24815. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24816. */
  24817. getPointsHoles( divisions ) {
  24818. const holesPts = [];
  24819. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24820. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24821. }
  24822. return holesPts;
  24823. }
  24824. // get points of shape and holes (keypoints based on segments parameter)
  24825. /**
  24826. * Returns an object that holds contour data for the shape and its holes as
  24827. * arrays of 2D points.
  24828. *
  24829. * @param {number} divisions - The fineness of the result.
  24830. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24831. */
  24832. extractPoints( divisions ) {
  24833. return {
  24834. shape: this.getPoints( divisions ),
  24835. holes: this.getPointsHoles( divisions )
  24836. };
  24837. }
  24838. copy( source ) {
  24839. super.copy( source );
  24840. this.holes = [];
  24841. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24842. const hole = source.holes[ i ];
  24843. this.holes.push( hole.clone() );
  24844. }
  24845. return this;
  24846. }
  24847. toJSON() {
  24848. const data = super.toJSON();
  24849. data.uuid = this.uuid;
  24850. data.holes = [];
  24851. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24852. const hole = this.holes[ i ];
  24853. data.holes.push( hole.toJSON() );
  24854. }
  24855. return data;
  24856. }
  24857. fromJSON( json ) {
  24858. super.fromJSON( json );
  24859. this.uuid = json.uuid;
  24860. this.holes = [];
  24861. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24862. const hole = json.holes[ i ];
  24863. this.holes.push( new Path().fromJSON( hole ) );
  24864. }
  24865. return this;
  24866. }
  24867. }
  24868. /* eslint-disable */
  24869. // copy of mapbox/earcut version 3.0.2
  24870. // https://github.com/mapbox/earcut/tree/v3.0.2
  24871. function earcut(data, holeIndices, dim = 2) {
  24872. const hasHoles = holeIndices && holeIndices.length;
  24873. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24874. let outerNode = linkedList(data, 0, outerLen, dim, true);
  24875. const triangles = [];
  24876. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24877. let minX, minY, invSize;
  24878. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  24879. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24880. if (data.length > 80 * dim) {
  24881. minX = data[0];
  24882. minY = data[1];
  24883. let maxX = minX;
  24884. let maxY = minY;
  24885. for (let i = dim; i < outerLen; i += dim) {
  24886. const x = data[i];
  24887. const y = data[i + 1];
  24888. if (x < minX) minX = x;
  24889. if (y < minY) minY = y;
  24890. if (x > maxX) maxX = x;
  24891. if (y > maxY) maxY = y;
  24892. }
  24893. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24894. invSize = Math.max(maxX - minX, maxY - minY);
  24895. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24896. }
  24897. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  24898. return triangles;
  24899. }
  24900. // create a circular doubly linked list from polygon points in the specified winding order
  24901. function linkedList(data, start, end, dim, clockwise) {
  24902. let last;
  24903. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  24904. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24905. } else {
  24906. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24907. }
  24908. if (last && equals(last, last.next)) {
  24909. removeNode(last);
  24910. last = last.next;
  24911. }
  24912. return last;
  24913. }
  24914. // eliminate colinear or duplicate points
  24915. function filterPoints(start, end) {
  24916. if (!start) return start;
  24917. if (!end) end = start;
  24918. let p = start,
  24919. again;
  24920. do {
  24921. again = false;
  24922. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24923. removeNode(p);
  24924. p = end = p.prev;
  24925. if (p === p.next) break;
  24926. again = true;
  24927. } else {
  24928. p = p.next;
  24929. }
  24930. } while (again || p !== end);
  24931. return end;
  24932. }
  24933. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24934. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  24935. if (!ear) return;
  24936. // interlink polygon nodes in z-order
  24937. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  24938. let stop = ear;
  24939. // iterate through ears, slicing them one by one
  24940. while (ear.prev !== ear.next) {
  24941. const prev = ear.prev;
  24942. const next = ear.next;
  24943. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  24944. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  24945. removeNode(ear);
  24946. // skipping the next vertex leads to less sliver triangles
  24947. ear = next.next;
  24948. stop = next.next;
  24949. continue;
  24950. }
  24951. ear = next;
  24952. // if we looped through the whole remaining polygon and can't find any more ears
  24953. if (ear === stop) {
  24954. // try filtering points and slicing again
  24955. if (!pass) {
  24956. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  24957. // if this didn't work, try curing all small self-intersections locally
  24958. } else if (pass === 1) {
  24959. ear = cureLocalIntersections(filterPoints(ear), triangles);
  24960. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  24961. // as a last resort, try splitting the remaining polygon into two
  24962. } else if (pass === 2) {
  24963. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  24964. }
  24965. break;
  24966. }
  24967. }
  24968. }
  24969. // check whether a polygon node forms a valid ear with adjacent nodes
  24970. function isEar(ear) {
  24971. const a = ear.prev,
  24972. b = ear,
  24973. c = ear.next;
  24974. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24975. // now make sure we don't have other points inside the potential ear
  24976. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24977. // triangle bbox
  24978. const x0 = Math.min(ax, bx, cx),
  24979. y0 = Math.min(ay, by, cy),
  24980. x1 = Math.max(ax, bx, cx),
  24981. y1 = Math.max(ay, by, cy);
  24982. let p = c.next;
  24983. while (p !== a) {
  24984. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  24985. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  24986. area(p.prev, p, p.next) >= 0) return false;
  24987. p = p.next;
  24988. }
  24989. return true;
  24990. }
  24991. function isEarHashed(ear, minX, minY, invSize) {
  24992. const a = ear.prev,
  24993. b = ear,
  24994. c = ear.next;
  24995. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24996. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24997. // triangle bbox
  24998. const x0 = Math.min(ax, bx, cx),
  24999. y0 = Math.min(ay, by, cy),
  25000. x1 = Math.max(ax, bx, cx),
  25001. y1 = Math.max(ay, by, cy);
  25002. // z-order range for the current triangle bbox;
  25003. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25004. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25005. let p = ear.prevZ,
  25006. n = ear.nextZ;
  25007. // look for points inside the triangle in both directions
  25008. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25009. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25010. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25011. p = p.prevZ;
  25012. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25013. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25014. n = n.nextZ;
  25015. }
  25016. // look for remaining points in decreasing z-order
  25017. while (p && p.z >= minZ) {
  25018. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25019. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25020. p = p.prevZ;
  25021. }
  25022. // look for remaining points in increasing z-order
  25023. while (n && n.z <= maxZ) {
  25024. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25025. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25026. n = n.nextZ;
  25027. }
  25028. return true;
  25029. }
  25030. // go through all polygon nodes and cure small local self-intersections
  25031. function cureLocalIntersections(start, triangles) {
  25032. let p = start;
  25033. do {
  25034. const a = p.prev,
  25035. b = p.next.next;
  25036. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25037. triangles.push(a.i, p.i, b.i);
  25038. // remove two nodes involved
  25039. removeNode(p);
  25040. removeNode(p.next);
  25041. p = start = b;
  25042. }
  25043. p = p.next;
  25044. } while (p !== start);
  25045. return filterPoints(p);
  25046. }
  25047. // try splitting polygon into two and triangulate them independently
  25048. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25049. // look for a valid diagonal that divides the polygon into two
  25050. let a = start;
  25051. do {
  25052. let b = a.next.next;
  25053. while (b !== a.prev) {
  25054. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25055. // split the polygon in two by the diagonal
  25056. let c = splitPolygon(a, b);
  25057. // filter colinear points around the cuts
  25058. a = filterPoints(a, a.next);
  25059. c = filterPoints(c, c.next);
  25060. // run earcut on each half
  25061. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25062. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25063. return;
  25064. }
  25065. b = b.next;
  25066. }
  25067. a = a.next;
  25068. } while (a !== start);
  25069. }
  25070. // link every hole into the outer loop, producing a single-ring polygon without holes
  25071. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25072. const queue = [];
  25073. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25074. const start = holeIndices[i] * dim;
  25075. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25076. const list = linkedList(data, start, end, dim, false);
  25077. if (list === list.next) list.steiner = true;
  25078. queue.push(getLeftmost(list));
  25079. }
  25080. queue.sort(compareXYSlope);
  25081. // process holes from left to right
  25082. for (let i = 0; i < queue.length; i++) {
  25083. outerNode = eliminateHole(queue[i], outerNode);
  25084. }
  25085. return outerNode;
  25086. }
  25087. function compareXYSlope(a, b) {
  25088. let result = a.x - b.x;
  25089. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25090. // the bridge to the outer shell is always the point that they meet at.
  25091. if (result === 0) {
  25092. result = a.y - b.y;
  25093. if (result === 0) {
  25094. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25095. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25096. result = aSlope - bSlope;
  25097. }
  25098. }
  25099. return result;
  25100. }
  25101. // find a bridge between vertices that connects hole with an outer ring and link it
  25102. function eliminateHole(hole, outerNode) {
  25103. const bridge = findHoleBridge(hole, outerNode);
  25104. if (!bridge) {
  25105. return outerNode;
  25106. }
  25107. const bridgeReverse = splitPolygon(bridge, hole);
  25108. // filter collinear points around the cuts
  25109. filterPoints(bridgeReverse, bridgeReverse.next);
  25110. return filterPoints(bridge, bridge.next);
  25111. }
  25112. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25113. function findHoleBridge(hole, outerNode) {
  25114. let p = outerNode;
  25115. const hx = hole.x;
  25116. const hy = hole.y;
  25117. let qx = -Infinity;
  25118. let m;
  25119. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25120. // segment's endpoint with lesser x will be potential connection point
  25121. // unless they intersect at a vertex, then choose the vertex
  25122. if (equals(hole, p)) return p;
  25123. do {
  25124. if (equals(hole, p.next)) return p.next;
  25125. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25126. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25127. if (x <= hx && x > qx) {
  25128. qx = x;
  25129. m = p.x < p.next.x ? p : p.next;
  25130. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25131. }
  25132. }
  25133. p = p.next;
  25134. } while (p !== outerNode);
  25135. if (!m) return null;
  25136. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25137. // if there are no points found, we have a valid connection;
  25138. // otherwise choose the point of the minimum angle with the ray as connection point
  25139. const stop = m;
  25140. const mx = m.x;
  25141. const my = m.y;
  25142. let tanMin = Infinity;
  25143. p = m;
  25144. do {
  25145. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25146. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25147. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25148. if (locallyInside(p, hole) &&
  25149. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25150. m = p;
  25151. tanMin = tan;
  25152. }
  25153. }
  25154. p = p.next;
  25155. } while (p !== stop);
  25156. return m;
  25157. }
  25158. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25159. function sectorContainsSector(m, p) {
  25160. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25161. }
  25162. // interlink polygon nodes in z-order
  25163. function indexCurve(start, minX, minY, invSize) {
  25164. let p = start;
  25165. do {
  25166. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25167. p.prevZ = p.prev;
  25168. p.nextZ = p.next;
  25169. p = p.next;
  25170. } while (p !== start);
  25171. p.prevZ.nextZ = null;
  25172. p.prevZ = null;
  25173. sortLinked(p);
  25174. }
  25175. // Simon Tatham's linked list merge sort algorithm
  25176. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25177. function sortLinked(list) {
  25178. let numMerges;
  25179. let inSize = 1;
  25180. do {
  25181. let p = list;
  25182. let e;
  25183. list = null;
  25184. let tail = null;
  25185. numMerges = 0;
  25186. while (p) {
  25187. numMerges++;
  25188. let q = p;
  25189. let pSize = 0;
  25190. for (let i = 0; i < inSize; i++) {
  25191. pSize++;
  25192. q = q.nextZ;
  25193. if (!q) break;
  25194. }
  25195. let qSize = inSize;
  25196. while (pSize > 0 || (qSize > 0 && q)) {
  25197. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25198. e = p;
  25199. p = p.nextZ;
  25200. pSize--;
  25201. } else {
  25202. e = q;
  25203. q = q.nextZ;
  25204. qSize--;
  25205. }
  25206. if (tail) tail.nextZ = e;
  25207. else list = e;
  25208. e.prevZ = tail;
  25209. tail = e;
  25210. }
  25211. p = q;
  25212. }
  25213. tail.nextZ = null;
  25214. inSize *= 2;
  25215. } while (numMerges > 1);
  25216. return list;
  25217. }
  25218. // z-order of a point given coords and inverse of the longer side of data bbox
  25219. function zOrder(x, y, minX, minY, invSize) {
  25220. // coords are transformed into non-negative 15-bit integer range
  25221. x = (x - minX) * invSize | 0;
  25222. y = (y - minY) * invSize | 0;
  25223. x = (x | (x << 8)) & 0x00FF00FF;
  25224. x = (x | (x << 4)) & 0x0F0F0F0F;
  25225. x = (x | (x << 2)) & 0x33333333;
  25226. x = (x | (x << 1)) & 0x55555555;
  25227. y = (y | (y << 8)) & 0x00FF00FF;
  25228. y = (y | (y << 4)) & 0x0F0F0F0F;
  25229. y = (y | (y << 2)) & 0x33333333;
  25230. y = (y | (y << 1)) & 0x55555555;
  25231. return x | (y << 1);
  25232. }
  25233. // find the leftmost node of a polygon ring
  25234. function getLeftmost(start) {
  25235. let p = start,
  25236. leftmost = start;
  25237. do {
  25238. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25239. p = p.next;
  25240. } while (p !== start);
  25241. return leftmost;
  25242. }
  25243. // check if a point lies within a convex triangle
  25244. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25245. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25246. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25247. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25248. }
  25249. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25250. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25251. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25252. }
  25253. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25254. function isValidDiagonal(a, b) {
  25255. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25256. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25257. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25258. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25259. }
  25260. // signed area of a triangle
  25261. function area(p, q, r) {
  25262. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25263. }
  25264. // check if two points are equal
  25265. function equals(p1, p2) {
  25266. return p1.x === p2.x && p1.y === p2.y;
  25267. }
  25268. // check if two segments intersect
  25269. function intersects(p1, q1, p2, q2) {
  25270. const o1 = sign(area(p1, q1, p2));
  25271. const o2 = sign(area(p1, q1, q2));
  25272. const o3 = sign(area(p2, q2, p1));
  25273. const o4 = sign(area(p2, q2, q1));
  25274. if (o1 !== o2 && o3 !== o4) return true; // general case
  25275. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25276. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25277. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25278. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25279. return false;
  25280. }
  25281. // for collinear points p, q, r, check if point q lies on segment pr
  25282. function onSegment(p, q, r) {
  25283. 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);
  25284. }
  25285. function sign(num) {
  25286. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25287. }
  25288. // check if a polygon diagonal intersects any polygon segments
  25289. function intersectsPolygon(a, b) {
  25290. let p = a;
  25291. do {
  25292. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25293. intersects(p, p.next, a, b)) return true;
  25294. p = p.next;
  25295. } while (p !== a);
  25296. return false;
  25297. }
  25298. // check if a polygon diagonal is locally inside the polygon
  25299. function locallyInside(a, b) {
  25300. return area(a.prev, a, a.next) < 0 ?
  25301. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25302. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25303. }
  25304. // check if the middle point of a polygon diagonal is inside the polygon
  25305. function middleInside(a, b) {
  25306. let p = a;
  25307. let inside = false;
  25308. const px = (a.x + b.x) / 2;
  25309. const py = (a.y + b.y) / 2;
  25310. do {
  25311. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25312. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25313. inside = !inside;
  25314. p = p.next;
  25315. } while (p !== a);
  25316. return inside;
  25317. }
  25318. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25319. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25320. function splitPolygon(a, b) {
  25321. const a2 = createNode(a.i, a.x, a.y),
  25322. b2 = createNode(b.i, b.x, b.y),
  25323. an = a.next,
  25324. bp = b.prev;
  25325. a.next = b;
  25326. b.prev = a;
  25327. a2.next = an;
  25328. an.prev = a2;
  25329. b2.next = a2;
  25330. a2.prev = b2;
  25331. bp.next = b2;
  25332. b2.prev = bp;
  25333. return b2;
  25334. }
  25335. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25336. function insertNode(i, x, y, last) {
  25337. const p = createNode(i, x, y);
  25338. if (!last) {
  25339. p.prev = p;
  25340. p.next = p;
  25341. } else {
  25342. p.next = last.next;
  25343. p.prev = last;
  25344. last.next.prev = p;
  25345. last.next = p;
  25346. }
  25347. return p;
  25348. }
  25349. function removeNode(p) {
  25350. p.next.prev = p.prev;
  25351. p.prev.next = p.next;
  25352. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25353. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25354. }
  25355. function createNode(i, x, y) {
  25356. return {
  25357. i, // vertex index in coordinates array
  25358. x, y, // vertex coordinates
  25359. prev: null, // previous and next vertex nodes in a polygon ring
  25360. next: null,
  25361. z: 0, // z-order curve value
  25362. prevZ: null, // previous and next nodes in z-order
  25363. nextZ: null,
  25364. steiner: false // indicates whether this is a steiner point
  25365. };
  25366. }
  25367. function signedArea(data, start, end, dim) {
  25368. let sum = 0;
  25369. for (let i = start, j = end - dim; i < end; i += dim) {
  25370. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25371. j = i;
  25372. }
  25373. return sum;
  25374. }
  25375. /**
  25376. * An implementation of the earcut polygon triangulation algorithm.
  25377. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25378. *
  25379. * @see https://github.com/mapbox/earcut
  25380. */
  25381. class Earcut {
  25382. /**
  25383. * Triangulates the given shape definition by returning an array of triangles.
  25384. *
  25385. * @param {Array<number>} data - An array with 2D points.
  25386. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25387. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25388. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25389. * representing vertex indices.
  25390. */
  25391. static triangulate( data, holeIndices, dim = 2 ) {
  25392. return earcut( data, holeIndices, dim );
  25393. }
  25394. }
  25395. /**
  25396. * A class containing utility functions for shapes.
  25397. *
  25398. * @hideconstructor
  25399. */
  25400. class ShapeUtils {
  25401. /**
  25402. * Calculate area of a ( 2D ) contour polygon.
  25403. *
  25404. * @param {Array<Vector2>} contour - An array of 2D points.
  25405. * @return {number} The area.
  25406. */
  25407. static area( contour ) {
  25408. const n = contour.length;
  25409. let a = 0.0;
  25410. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25411. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25412. }
  25413. return a * 0.5;
  25414. }
  25415. /**
  25416. * Returns `true` if the given contour uses a clockwise winding order.
  25417. *
  25418. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25419. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25420. */
  25421. static isClockWise( pts ) {
  25422. return ShapeUtils.area( pts ) < 0;
  25423. }
  25424. /**
  25425. * Triangulates the given shape definition.
  25426. *
  25427. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25428. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25429. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25430. */
  25431. static triangulateShape( contour, holes ) {
  25432. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25433. const holeIndices = []; // array of hole indices
  25434. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25435. removeDupEndPts( contour );
  25436. addContour( vertices, contour );
  25437. //
  25438. let holeIndex = contour.length;
  25439. holes.forEach( removeDupEndPts );
  25440. for ( let i = 0; i < holes.length; i ++ ) {
  25441. holeIndices.push( holeIndex );
  25442. holeIndex += holes[ i ].length;
  25443. addContour( vertices, holes[ i ] );
  25444. }
  25445. //
  25446. const triangles = Earcut.triangulate( vertices, holeIndices );
  25447. //
  25448. for ( let i = 0; i < triangles.length; i += 3 ) {
  25449. faces.push( triangles.slice( i, i + 3 ) );
  25450. }
  25451. return faces;
  25452. }
  25453. }
  25454. function removeDupEndPts( points ) {
  25455. const l = points.length;
  25456. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25457. points.pop();
  25458. }
  25459. }
  25460. function addContour( vertices, contour ) {
  25461. for ( let i = 0; i < contour.length; i ++ ) {
  25462. vertices.push( contour[ i ].x );
  25463. vertices.push( contour[ i ].y );
  25464. }
  25465. }
  25466. /**
  25467. * Creates extruded geometry from a path shape.
  25468. *
  25469. * ```js
  25470. * const length = 12, width = 8;
  25471. *
  25472. * const shape = new THREE.Shape();
  25473. * shape.moveTo( 0,0 );
  25474. * shape.lineTo( 0, width );
  25475. * shape.lineTo( length, width );
  25476. * shape.lineTo( length, 0 );
  25477. * shape.lineTo( 0, 0 );
  25478. *
  25479. * const geometry = new THREE.ExtrudeGeometry( shape );
  25480. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25481. * const mesh = new THREE.Mesh( geometry, material ) ;
  25482. * scene.add( mesh );
  25483. * ```
  25484. *
  25485. * @augments BufferGeometry
  25486. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25487. */
  25488. class ExtrudeGeometry extends BufferGeometry {
  25489. /**
  25490. * Constructs a new extrude geometry.
  25491. *
  25492. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25493. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25494. */
  25495. 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 = {} ) {
  25496. super();
  25497. this.type = 'ExtrudeGeometry';
  25498. /**
  25499. * Holds the constructor parameters that have been
  25500. * used to generate the geometry. Any modification
  25501. * after instantiation does not change the geometry.
  25502. *
  25503. * @type {Object}
  25504. */
  25505. this.parameters = {
  25506. shapes: shapes,
  25507. options: options
  25508. };
  25509. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25510. const scope = this;
  25511. const verticesArray = [];
  25512. const uvArray = [];
  25513. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25514. const shape = shapes[ i ];
  25515. addShape( shape );
  25516. }
  25517. // build geometry
  25518. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25519. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25520. this.computeVertexNormals();
  25521. // functions
  25522. function addShape( shape ) {
  25523. const placeholder = [];
  25524. // options
  25525. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25526. const steps = options.steps !== undefined ? options.steps : 1;
  25527. const depth = options.depth !== undefined ? options.depth : 1;
  25528. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25529. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25530. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25531. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25532. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25533. const extrudePath = options.extrudePath;
  25534. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25535. //
  25536. let extrudePts, extrudeByPath = false;
  25537. let splineTube, binormal, normal, position2;
  25538. if ( extrudePath ) {
  25539. extrudePts = extrudePath.getSpacedPoints( steps );
  25540. extrudeByPath = true;
  25541. bevelEnabled = false; // bevels not supported for path extrusion
  25542. // SETUP TNB variables
  25543. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  25544. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  25545. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25546. binormal = new Vector3();
  25547. normal = new Vector3();
  25548. position2 = new Vector3();
  25549. }
  25550. // Safeguards if bevels are not enabled
  25551. if ( ! bevelEnabled ) {
  25552. bevelSegments = 0;
  25553. bevelThickness = 0;
  25554. bevelSize = 0;
  25555. bevelOffset = 0;
  25556. }
  25557. // Variables initialization
  25558. const shapePoints = shape.extractPoints( curveSegments );
  25559. let vertices = shapePoints.shape;
  25560. const holes = shapePoints.holes;
  25561. const reverse = ! ShapeUtils.isClockWise( vertices );
  25562. if ( reverse ) {
  25563. vertices = vertices.reverse();
  25564. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25565. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25566. const ahole = holes[ h ];
  25567. if ( ShapeUtils.isClockWise( ahole ) ) {
  25568. holes[ h ] = ahole.reverse();
  25569. }
  25570. }
  25571. }
  25572. /**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.
  25573. * @param {Array<Vector2>} points
  25574. */
  25575. function mergeOverlappingPoints( points ) {
  25576. const THRESHOLD = 1e-10;
  25577. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25578. let prevPos = points[ 0 ];
  25579. for ( let i = 1; i <= points.length; i ++ ) {
  25580. const currentIndex = i % points.length;
  25581. const currentPos = points[ currentIndex ];
  25582. const dx = currentPos.x - prevPos.x;
  25583. const dy = currentPos.y - prevPos.y;
  25584. const distSq = dx * dx + dy * dy;
  25585. const scalingFactorSqrt = Math.max(
  25586. Math.abs( currentPos.x ),
  25587. Math.abs( currentPos.y ),
  25588. Math.abs( prevPos.x ),
  25589. Math.abs( prevPos.y )
  25590. );
  25591. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25592. if ( distSq <= thresholdSqScaled ) {
  25593. points.splice( currentIndex, 1 );
  25594. i --;
  25595. continue;
  25596. }
  25597. prevPos = currentPos;
  25598. }
  25599. }
  25600. mergeOverlappingPoints( vertices );
  25601. holes.forEach( mergeOverlappingPoints );
  25602. const numHoles = holes.length;
  25603. /* Vertices */
  25604. const contour = vertices; // vertices has all points but contour has only points of circumference
  25605. for ( let h = 0; h < numHoles; h ++ ) {
  25606. const ahole = holes[ h ];
  25607. vertices = vertices.concat( ahole );
  25608. }
  25609. function scalePt2( pt, vec, size ) {
  25610. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  25611. return pt.clone().addScaledVector( vec, size );
  25612. }
  25613. const vlen = vertices.length;
  25614. // Find directions for point movement
  25615. function getBevelVec( inPt, inPrev, inNext ) {
  25616. // computes for inPt the corresponding point inPt' on a new contour
  25617. // shifted by 1 unit (length of normalized vector) to the left
  25618. // if we walk along contour clockwise, this new contour is outside the old one
  25619. //
  25620. // inPt' is the intersection of the two lines parallel to the two
  25621. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25622. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25623. // good reading for geometry algorithms (here: line-line intersection)
  25624. // http://geomalgorithms.com/a05-_intersect-1.html
  25625. const v_prev_x = inPt.x - inPrev.x,
  25626. v_prev_y = inPt.y - inPrev.y;
  25627. const v_next_x = inNext.x - inPt.x,
  25628. v_next_y = inNext.y - inPt.y;
  25629. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25630. // check for collinear edges
  25631. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25632. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25633. // not collinear
  25634. // length of vectors for normalizing
  25635. const v_prev_len = Math.sqrt( v_prev_lensq );
  25636. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25637. // shift adjacent points by unit vectors to the left
  25638. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25639. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25640. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25641. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25642. // scaling factor for v_prev to intersection point
  25643. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25644. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25645. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25646. // vector from inPt to intersection point
  25647. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25648. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25649. // Don't normalize!, otherwise sharp corners become ugly
  25650. // but prevent crazy spikes
  25651. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25652. if ( v_trans_lensq <= 2 ) {
  25653. return new Vector2( v_trans_x, v_trans_y );
  25654. } else {
  25655. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25656. }
  25657. } else {
  25658. // handle special case of collinear edges
  25659. let direction_eq = false; // assumes: opposite
  25660. if ( v_prev_x > Number.EPSILON ) {
  25661. if ( v_next_x > Number.EPSILON ) {
  25662. direction_eq = true;
  25663. }
  25664. } else {
  25665. if ( v_prev_x < - Number.EPSILON ) {
  25666. if ( v_next_x < - Number.EPSILON ) {
  25667. direction_eq = true;
  25668. }
  25669. } else {
  25670. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25671. direction_eq = true;
  25672. }
  25673. }
  25674. }
  25675. if ( direction_eq ) {
  25676. // log("Warning: lines are a straight sequence");
  25677. v_trans_x = - v_prev_y;
  25678. v_trans_y = v_prev_x;
  25679. shrink_by = Math.sqrt( v_prev_lensq );
  25680. } else {
  25681. // log("Warning: lines are a straight spike");
  25682. v_trans_x = v_prev_x;
  25683. v_trans_y = v_prev_y;
  25684. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25685. }
  25686. }
  25687. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25688. }
  25689. const contourMovements = [];
  25690. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25691. if ( j === il ) j = 0;
  25692. if ( k === il ) k = 0;
  25693. // (j)---(i)---(k)
  25694. // log('i,j,k', i, j , k)
  25695. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25696. }
  25697. const holesMovements = [];
  25698. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25699. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25700. const ahole = holes[ h ];
  25701. oneHoleMovements = [];
  25702. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25703. if ( j === il ) j = 0;
  25704. if ( k === il ) k = 0;
  25705. // (j)---(i)---(k)
  25706. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25707. }
  25708. holesMovements.push( oneHoleMovements );
  25709. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25710. }
  25711. let faces;
  25712. if ( bevelSegments === 0 ) {
  25713. faces = ShapeUtils.triangulateShape( contour, holes );
  25714. } else {
  25715. const contractedContourVertices = [];
  25716. const expandedHoleVertices = [];
  25717. // Loop bevelSegments, 1 for the front, 1 for the back
  25718. for ( let b = 0; b < bevelSegments; b ++ ) {
  25719. //for ( b = bevelSegments; b > 0; b -- ) {
  25720. const t = b / bevelSegments;
  25721. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25722. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25723. // contract shape
  25724. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25725. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25726. v( vert.x, vert.y, - z );
  25727. if ( t === 0 ) contractedContourVertices.push( vert );
  25728. }
  25729. // expand holes
  25730. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25731. const ahole = holes[ h ];
  25732. oneHoleMovements = holesMovements[ h ];
  25733. const oneHoleVertices = [];
  25734. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25735. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25736. v( vert.x, vert.y, - z );
  25737. if ( t === 0 ) oneHoleVertices.push( vert );
  25738. }
  25739. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25740. }
  25741. }
  25742. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25743. }
  25744. const flen = faces.length;
  25745. const bs = bevelSize + bevelOffset;
  25746. // Back facing vertices
  25747. for ( let i = 0; i < vlen; i ++ ) {
  25748. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25749. if ( ! extrudeByPath ) {
  25750. v( vert.x, vert.y, 0 );
  25751. } else {
  25752. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25753. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25754. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25755. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25756. v( position2.x, position2.y, position2.z );
  25757. }
  25758. }
  25759. // Add stepped vertices...
  25760. // Including front facing vertices
  25761. for ( let s = 1; s <= steps; s ++ ) {
  25762. for ( let i = 0; i < vlen; i ++ ) {
  25763. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25764. if ( ! extrudeByPath ) {
  25765. v( vert.x, vert.y, depth / steps * s );
  25766. } else {
  25767. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25768. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25769. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25770. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25771. v( position2.x, position2.y, position2.z );
  25772. }
  25773. }
  25774. }
  25775. // Add bevel segments planes
  25776. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25777. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25778. const t = b / bevelSegments;
  25779. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25780. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25781. // contract shape
  25782. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25783. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25784. v( vert.x, vert.y, depth + z );
  25785. }
  25786. // expand holes
  25787. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25788. const ahole = holes[ h ];
  25789. oneHoleMovements = holesMovements[ h ];
  25790. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25791. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25792. if ( ! extrudeByPath ) {
  25793. v( vert.x, vert.y, depth + z );
  25794. } else {
  25795. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25796. }
  25797. }
  25798. }
  25799. }
  25800. /* Faces */
  25801. // Top and bottom faces
  25802. buildLidFaces();
  25803. // Sides faces
  25804. buildSideFaces();
  25805. ///// Internal functions
  25806. function buildLidFaces() {
  25807. const start = verticesArray.length / 3;
  25808. if ( bevelEnabled ) {
  25809. let layer = 0; // steps + 1
  25810. let offset = vlen * layer;
  25811. // Bottom faces
  25812. for ( let i = 0; i < flen; i ++ ) {
  25813. const face = faces[ i ];
  25814. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25815. }
  25816. layer = steps + bevelSegments * 2;
  25817. offset = vlen * layer;
  25818. // Top faces
  25819. for ( let i = 0; i < flen; i ++ ) {
  25820. const face = faces[ i ];
  25821. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25822. }
  25823. } else {
  25824. // Bottom faces
  25825. for ( let i = 0; i < flen; i ++ ) {
  25826. const face = faces[ i ];
  25827. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25828. }
  25829. // Top faces
  25830. for ( let i = 0; i < flen; i ++ ) {
  25831. const face = faces[ i ];
  25832. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25833. }
  25834. }
  25835. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25836. }
  25837. // Create faces for the z-sides of the shape
  25838. function buildSideFaces() {
  25839. const start = verticesArray.length / 3;
  25840. let layeroffset = 0;
  25841. sidewalls( contour, layeroffset );
  25842. layeroffset += contour.length;
  25843. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25844. const ahole = holes[ h ];
  25845. sidewalls( ahole, layeroffset );
  25846. //, true
  25847. layeroffset += ahole.length;
  25848. }
  25849. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25850. }
  25851. function sidewalls( contour, layeroffset ) {
  25852. let i = contour.length;
  25853. while ( -- i >= 0 ) {
  25854. const j = i;
  25855. let k = i - 1;
  25856. if ( k < 0 ) k = contour.length - 1;
  25857. //log('b', i,j, i-1, k,vertices.length);
  25858. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25859. const slen1 = vlen * s;
  25860. const slen2 = vlen * ( s + 1 );
  25861. const a = layeroffset + j + slen1,
  25862. b = layeroffset + k + slen1,
  25863. c = layeroffset + k + slen2,
  25864. d = layeroffset + j + slen2;
  25865. f4( a, b, c, d );
  25866. }
  25867. }
  25868. }
  25869. function v( x, y, z ) {
  25870. placeholder.push( x );
  25871. placeholder.push( y );
  25872. placeholder.push( z );
  25873. }
  25874. function f3( a, b, c ) {
  25875. addVertex( a );
  25876. addVertex( b );
  25877. addVertex( c );
  25878. const nextIndex = verticesArray.length / 3;
  25879. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25880. addUV( uvs[ 0 ] );
  25881. addUV( uvs[ 1 ] );
  25882. addUV( uvs[ 2 ] );
  25883. }
  25884. function f4( a, b, c, d ) {
  25885. addVertex( a );
  25886. addVertex( b );
  25887. addVertex( d );
  25888. addVertex( b );
  25889. addVertex( c );
  25890. addVertex( d );
  25891. const nextIndex = verticesArray.length / 3;
  25892. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25893. addUV( uvs[ 0 ] );
  25894. addUV( uvs[ 1 ] );
  25895. addUV( uvs[ 3 ] );
  25896. addUV( uvs[ 1 ] );
  25897. addUV( uvs[ 2 ] );
  25898. addUV( uvs[ 3 ] );
  25899. }
  25900. function addVertex( index ) {
  25901. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25902. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25903. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25904. }
  25905. function addUV( vector2 ) {
  25906. uvArray.push( vector2.x );
  25907. uvArray.push( vector2.y );
  25908. }
  25909. }
  25910. }
  25911. copy( source ) {
  25912. super.copy( source );
  25913. this.parameters = Object.assign( {}, source.parameters );
  25914. return this;
  25915. }
  25916. toJSON() {
  25917. const data = super.toJSON();
  25918. const shapes = this.parameters.shapes;
  25919. const options = this.parameters.options;
  25920. return toJSON$1( shapes, options, data );
  25921. }
  25922. /**
  25923. * Factory method for creating an instance of this class from the given
  25924. * JSON object.
  25925. *
  25926. * @param {Object} data - A JSON object representing the serialized geometry.
  25927. * @param {Array<Shape>} shapes - An array of shapes.
  25928. * @return {ExtrudeGeometry} A new instance.
  25929. */
  25930. static fromJSON( data, shapes ) {
  25931. const geometryShapes = [];
  25932. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25933. const shape = shapes[ data.shapes[ j ] ];
  25934. geometryShapes.push( shape );
  25935. }
  25936. const extrudePath = data.options.extrudePath;
  25937. if ( extrudePath !== undefined ) {
  25938. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25939. }
  25940. return new ExtrudeGeometry( geometryShapes, data.options );
  25941. }
  25942. }
  25943. const WorldUVGenerator = {
  25944. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  25945. const a_x = vertices[ indexA * 3 ];
  25946. const a_y = vertices[ indexA * 3 + 1 ];
  25947. const b_x = vertices[ indexB * 3 ];
  25948. const b_y = vertices[ indexB * 3 + 1 ];
  25949. const c_x = vertices[ indexC * 3 ];
  25950. const c_y = vertices[ indexC * 3 + 1 ];
  25951. return [
  25952. new Vector2( a_x, a_y ),
  25953. new Vector2( b_x, b_y ),
  25954. new Vector2( c_x, c_y )
  25955. ];
  25956. },
  25957. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  25958. const a_x = vertices[ indexA * 3 ];
  25959. const a_y = vertices[ indexA * 3 + 1 ];
  25960. const a_z = vertices[ indexA * 3 + 2 ];
  25961. const b_x = vertices[ indexB * 3 ];
  25962. const b_y = vertices[ indexB * 3 + 1 ];
  25963. const b_z = vertices[ indexB * 3 + 2 ];
  25964. const c_x = vertices[ indexC * 3 ];
  25965. const c_y = vertices[ indexC * 3 + 1 ];
  25966. const c_z = vertices[ indexC * 3 + 2 ];
  25967. const d_x = vertices[ indexD * 3 ];
  25968. const d_y = vertices[ indexD * 3 + 1 ];
  25969. const d_z = vertices[ indexD * 3 + 2 ];
  25970. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  25971. return [
  25972. new Vector2( a_x, 1 - a_z ),
  25973. new Vector2( b_x, 1 - b_z ),
  25974. new Vector2( c_x, 1 - c_z ),
  25975. new Vector2( d_x, 1 - d_z )
  25976. ];
  25977. } else {
  25978. return [
  25979. new Vector2( a_y, 1 - a_z ),
  25980. new Vector2( b_y, 1 - b_z ),
  25981. new Vector2( c_y, 1 - c_z ),
  25982. new Vector2( d_y, 1 - d_z )
  25983. ];
  25984. }
  25985. }
  25986. };
  25987. function toJSON$1( shapes, options, data ) {
  25988. data.shapes = [];
  25989. if ( Array.isArray( shapes ) ) {
  25990. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25991. const shape = shapes[ i ];
  25992. data.shapes.push( shape.uuid );
  25993. }
  25994. } else {
  25995. data.shapes.push( shapes.uuid );
  25996. }
  25997. data.options = Object.assign( {}, options );
  25998. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  25999. return data;
  26000. }
  26001. /**
  26002. * A geometry class for representing an icosahedron.
  26003. *
  26004. * ```js
  26005. * const geometry = new THREE.IcosahedronGeometry();
  26006. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26007. * const icosahedron = new THREE.Mesh( geometry, material );
  26008. * scene.add( icosahedron );
  26009. * ```
  26010. *
  26011. * @augments PolyhedronGeometry
  26012. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26013. */
  26014. class IcosahedronGeometry extends PolyhedronGeometry {
  26015. /**
  26016. * Constructs a new icosahedron geometry.
  26017. *
  26018. * @param {number} [radius=1] - Radius of the icosahedron.
  26019. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26020. */
  26021. constructor( radius = 1, detail = 0 ) {
  26022. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26023. const vertices = [
  26024. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26025. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26026. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26027. ];
  26028. const indices = [
  26029. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26030. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26031. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26032. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26033. ];
  26034. super( vertices, indices, radius, detail );
  26035. this.type = 'IcosahedronGeometry';
  26036. /**
  26037. * Holds the constructor parameters that have been
  26038. * used to generate the geometry. Any modification
  26039. * after instantiation does not change the geometry.
  26040. *
  26041. * @type {Object}
  26042. */
  26043. this.parameters = {
  26044. radius: radius,
  26045. detail: detail
  26046. };
  26047. }
  26048. /**
  26049. * Factory method for creating an instance of this class from the given
  26050. * JSON object.
  26051. *
  26052. * @param {Object} data - A JSON object representing the serialized geometry.
  26053. * @return {IcosahedronGeometry} A new instance.
  26054. */
  26055. static fromJSON( data ) {
  26056. return new IcosahedronGeometry( data.radius, data.detail );
  26057. }
  26058. }
  26059. /**
  26060. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26061. *
  26062. * ```js
  26063. * const points = [];
  26064. * for ( let i = 0; i < 10; i ++ ) {
  26065. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26066. * }
  26067. * const geometry = new THREE.LatheGeometry( points );
  26068. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26069. * const lathe = new THREE.Mesh( geometry, material );
  26070. * scene.add( lathe );
  26071. * ```
  26072. *
  26073. * @augments BufferGeometry
  26074. * @demo scenes/geometry-browser.html#LatheGeometry
  26075. */
  26076. class LatheGeometry extends BufferGeometry {
  26077. /**
  26078. * Constructs a new lathe geometry.
  26079. *
  26080. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26081. * must be greater than zero.
  26082. * @param {number} [segments=12] - The number of circumference segments to generate.
  26083. * @param {number} [phiStart=0] - The starting angle in radians.
  26084. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26085. * closed lathe, less than 2PI is a portion.
  26086. */
  26087. 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 ) {
  26088. super();
  26089. this.type = 'LatheGeometry';
  26090. /**
  26091. * Holds the constructor parameters that have been
  26092. * used to generate the geometry. Any modification
  26093. * after instantiation does not change the geometry.
  26094. *
  26095. * @type {Object}
  26096. */
  26097. this.parameters = {
  26098. points: points,
  26099. segments: segments,
  26100. phiStart: phiStart,
  26101. phiLength: phiLength
  26102. };
  26103. segments = Math.floor( segments );
  26104. // clamp phiLength so it's in range of [ 0, 2PI ]
  26105. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26106. // buffers
  26107. const indices = [];
  26108. const vertices = [];
  26109. const uvs = [];
  26110. const initNormals = [];
  26111. const normals = [];
  26112. // helper variables
  26113. const inverseSegments = 1.0 / segments;
  26114. const vertex = new Vector3();
  26115. const uv = new Vector2();
  26116. const normal = new Vector3();
  26117. const curNormal = new Vector3();
  26118. const prevNormal = new Vector3();
  26119. let dx = 0;
  26120. let dy = 0;
  26121. // pre-compute normals for initial "meridian"
  26122. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26123. switch ( j ) {
  26124. case 0: // special handling for 1st vertex on path
  26125. dx = points[ j + 1 ].x - points[ j ].x;
  26126. dy = points[ j + 1 ].y - points[ j ].y;
  26127. normal.x = dy * 1.0;
  26128. normal.y = - dx;
  26129. normal.z = dy * 0.0;
  26130. prevNormal.copy( normal );
  26131. normal.normalize();
  26132. initNormals.push( normal.x, normal.y, normal.z );
  26133. break;
  26134. case ( points.length - 1 ): // special handling for last Vertex on path
  26135. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26136. break;
  26137. default: // default handling for all vertices in between
  26138. dx = points[ j + 1 ].x - points[ j ].x;
  26139. dy = points[ j + 1 ].y - points[ j ].y;
  26140. normal.x = dy * 1.0;
  26141. normal.y = - dx;
  26142. normal.z = dy * 0.0;
  26143. curNormal.copy( normal );
  26144. normal.x += prevNormal.x;
  26145. normal.y += prevNormal.y;
  26146. normal.z += prevNormal.z;
  26147. normal.normalize();
  26148. initNormals.push( normal.x, normal.y, normal.z );
  26149. prevNormal.copy( curNormal );
  26150. }
  26151. }
  26152. // generate vertices, uvs and normals
  26153. for ( let i = 0; i <= segments; i ++ ) {
  26154. const phi = phiStart + i * inverseSegments * phiLength;
  26155. const sin = Math.sin( phi );
  26156. const cos = Math.cos( phi );
  26157. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26158. // vertex
  26159. vertex.x = points[ j ].x * sin;
  26160. vertex.y = points[ j ].y;
  26161. vertex.z = points[ j ].x * cos;
  26162. vertices.push( vertex.x, vertex.y, vertex.z );
  26163. // uv
  26164. uv.x = i / segments;
  26165. uv.y = j / ( points.length - 1 );
  26166. uvs.push( uv.x, uv.y );
  26167. // normal
  26168. const x = initNormals[ 3 * j + 0 ] * sin;
  26169. const y = initNormals[ 3 * j + 1 ];
  26170. const z = initNormals[ 3 * j + 0 ] * cos;
  26171. normals.push( x, y, z );
  26172. }
  26173. }
  26174. // indices
  26175. for ( let i = 0; i < segments; i ++ ) {
  26176. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26177. const base = j + i * points.length;
  26178. const a = base;
  26179. const b = base + points.length;
  26180. const c = base + points.length + 1;
  26181. const d = base + 1;
  26182. // faces
  26183. indices.push( a, b, d );
  26184. indices.push( c, d, b );
  26185. }
  26186. }
  26187. // build geometry
  26188. this.setIndex( indices );
  26189. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26190. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26191. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26192. }
  26193. copy( source ) {
  26194. super.copy( source );
  26195. this.parameters = Object.assign( {}, source.parameters );
  26196. return this;
  26197. }
  26198. /**
  26199. * Factory method for creating an instance of this class from the given
  26200. * JSON object.
  26201. *
  26202. * @param {Object} data - A JSON object representing the serialized geometry.
  26203. * @return {LatheGeometry} A new instance.
  26204. */
  26205. static fromJSON( data ) {
  26206. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26207. }
  26208. }
  26209. /**
  26210. * A geometry class for representing an octahedron.
  26211. *
  26212. * ```js
  26213. * const geometry = new THREE.OctahedronGeometry();
  26214. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26215. * const octahedron = new THREE.Mesh( geometry, material );
  26216. * scene.add( octahedron );
  26217. * ```
  26218. *
  26219. * @augments PolyhedronGeometry
  26220. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26221. */
  26222. class OctahedronGeometry extends PolyhedronGeometry {
  26223. /**
  26224. * Constructs a new octahedron geometry.
  26225. *
  26226. * @param {number} [radius=1] - Radius of the octahedron.
  26227. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26228. */
  26229. constructor( radius = 1, detail = 0 ) {
  26230. const vertices = [
  26231. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26232. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26233. ];
  26234. const indices = [
  26235. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26236. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26237. 1, 3, 4, 1, 4, 2
  26238. ];
  26239. super( vertices, indices, radius, detail );
  26240. this.type = 'OctahedronGeometry';
  26241. /**
  26242. * Holds the constructor parameters that have been
  26243. * used to generate the geometry. Any modification
  26244. * after instantiation does not change the geometry.
  26245. *
  26246. * @type {Object}
  26247. */
  26248. this.parameters = {
  26249. radius: radius,
  26250. detail: detail
  26251. };
  26252. }
  26253. /**
  26254. * Factory method for creating an instance of this class from the given
  26255. * JSON object.
  26256. *
  26257. * @param {Object} data - A JSON object representing the serialized geometry.
  26258. * @return {OctahedronGeometry} A new instance.
  26259. */
  26260. static fromJSON( data ) {
  26261. return new OctahedronGeometry( data.radius, data.detail );
  26262. }
  26263. }
  26264. /**
  26265. * A geometry class for representing a plane.
  26266. *
  26267. * ```js
  26268. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26269. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26270. * const plane = new THREE.Mesh( geometry, material );
  26271. * scene.add( plane );
  26272. * ```
  26273. *
  26274. * @augments BufferGeometry
  26275. * @demo scenes/geometry-browser.html#PlaneGeometry
  26276. */
  26277. class PlaneGeometry extends BufferGeometry {
  26278. /**
  26279. * Constructs a new plane geometry.
  26280. *
  26281. * @param {number} [width=1] - The width along the X axis.
  26282. * @param {number} [height=1] - The height along the Y axis
  26283. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26284. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26285. */
  26286. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26287. super();
  26288. this.type = 'PlaneGeometry';
  26289. /**
  26290. * Holds the constructor parameters that have been
  26291. * used to generate the geometry. Any modification
  26292. * after instantiation does not change the geometry.
  26293. *
  26294. * @type {Object}
  26295. */
  26296. this.parameters = {
  26297. width: width,
  26298. height: height,
  26299. widthSegments: widthSegments,
  26300. heightSegments: heightSegments
  26301. };
  26302. const width_half = width / 2;
  26303. const height_half = height / 2;
  26304. const gridX = Math.floor( widthSegments );
  26305. const gridY = Math.floor( heightSegments );
  26306. const gridX1 = gridX + 1;
  26307. const gridY1 = gridY + 1;
  26308. const segment_width = width / gridX;
  26309. const segment_height = height / gridY;
  26310. //
  26311. const indices = [];
  26312. const vertices = [];
  26313. const normals = [];
  26314. const uvs = [];
  26315. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26316. const y = iy * segment_height - height_half;
  26317. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26318. const x = ix * segment_width - width_half;
  26319. vertices.push( x, - y, 0 );
  26320. normals.push( 0, 0, 1 );
  26321. uvs.push( ix / gridX );
  26322. uvs.push( 1 - ( iy / gridY ) );
  26323. }
  26324. }
  26325. for ( let iy = 0; iy < gridY; iy ++ ) {
  26326. for ( let ix = 0; ix < gridX; ix ++ ) {
  26327. const a = ix + gridX1 * iy;
  26328. const b = ix + gridX1 * ( iy + 1 );
  26329. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26330. const d = ( ix + 1 ) + gridX1 * iy;
  26331. indices.push( a, b, d );
  26332. indices.push( b, c, d );
  26333. }
  26334. }
  26335. this.setIndex( indices );
  26336. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26337. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26338. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26339. }
  26340. copy( source ) {
  26341. super.copy( source );
  26342. this.parameters = Object.assign( {}, source.parameters );
  26343. return this;
  26344. }
  26345. /**
  26346. * Factory method for creating an instance of this class from the given
  26347. * JSON object.
  26348. *
  26349. * @param {Object} data - A JSON object representing the serialized geometry.
  26350. * @return {PlaneGeometry} A new instance.
  26351. */
  26352. static fromJSON( data ) {
  26353. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26354. }
  26355. }
  26356. /**
  26357. * A class for generating a two-dimensional ring geometry.
  26358. *
  26359. * ```js
  26360. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26361. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26362. * const mesh = new THREE.Mesh( geometry, material );
  26363. * scene.add( mesh );
  26364. * ```
  26365. *
  26366. * @augments BufferGeometry
  26367. * @demo scenes/geometry-browser.html#RingGeometry
  26368. */
  26369. class RingGeometry extends BufferGeometry {
  26370. /**
  26371. * Constructs a new ring geometry.
  26372. *
  26373. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26374. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26375. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26376. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26377. * @param {number} [thetaStart=0] - Starting angle in radians.
  26378. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26379. */
  26380. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26381. super();
  26382. this.type = 'RingGeometry';
  26383. /**
  26384. * Holds the constructor parameters that have been
  26385. * used to generate the geometry. Any modification
  26386. * after instantiation does not change the geometry.
  26387. *
  26388. * @type {Object}
  26389. */
  26390. this.parameters = {
  26391. innerRadius: innerRadius,
  26392. outerRadius: outerRadius,
  26393. thetaSegments: thetaSegments,
  26394. phiSegments: phiSegments,
  26395. thetaStart: thetaStart,
  26396. thetaLength: thetaLength
  26397. };
  26398. thetaSegments = Math.max( 3, thetaSegments );
  26399. phiSegments = Math.max( 1, phiSegments );
  26400. // buffers
  26401. const indices = [];
  26402. const vertices = [];
  26403. const normals = [];
  26404. const uvs = [];
  26405. // some helper variables
  26406. let radius = innerRadius;
  26407. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26408. const vertex = new Vector3();
  26409. const uv = new Vector2();
  26410. // generate vertices, normals and uvs
  26411. for ( let j = 0; j <= phiSegments; j ++ ) {
  26412. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26413. // values are generate from the inside of the ring to the outside
  26414. const segment = thetaStart + i / thetaSegments * thetaLength;
  26415. // vertex
  26416. vertex.x = radius * Math.cos( segment );
  26417. vertex.y = radius * Math.sin( segment );
  26418. vertices.push( vertex.x, vertex.y, vertex.z );
  26419. // normal
  26420. normals.push( 0, 0, 1 );
  26421. // uv
  26422. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26423. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26424. uvs.push( uv.x, uv.y );
  26425. }
  26426. // increase the radius for next row of vertices
  26427. radius += radiusStep;
  26428. }
  26429. // indices
  26430. for ( let j = 0; j < phiSegments; j ++ ) {
  26431. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26432. for ( let i = 0; i < thetaSegments; i ++ ) {
  26433. const segment = i + thetaSegmentLevel;
  26434. const a = segment;
  26435. const b = segment + thetaSegments + 1;
  26436. const c = segment + thetaSegments + 2;
  26437. const d = segment + 1;
  26438. // faces
  26439. indices.push( a, b, d );
  26440. indices.push( b, c, d );
  26441. }
  26442. }
  26443. // build geometry
  26444. this.setIndex( indices );
  26445. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26446. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26447. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26448. }
  26449. copy( source ) {
  26450. super.copy( source );
  26451. this.parameters = Object.assign( {}, source.parameters );
  26452. return this;
  26453. }
  26454. /**
  26455. * Factory method for creating an instance of this class from the given
  26456. * JSON object.
  26457. *
  26458. * @param {Object} data - A JSON object representing the serialized geometry.
  26459. * @return {RingGeometry} A new instance.
  26460. */
  26461. static fromJSON( data ) {
  26462. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26463. }
  26464. }
  26465. /**
  26466. * Creates an one-sided polygonal geometry from one or more path shapes.
  26467. *
  26468. * ```js
  26469. * const arcShape = new THREE.Shape()
  26470. * .moveTo( 5, 1 )
  26471. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26472. *
  26473. * const geometry = new THREE.ShapeGeometry( arcShape );
  26474. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26475. * const mesh = new THREE.Mesh( geometry, material ) ;
  26476. * scene.add( mesh );
  26477. * ```
  26478. *
  26479. * @augments BufferGeometry
  26480. * @demo scenes/geometry-browser.html#ShapeGeometry
  26481. */
  26482. class ShapeGeometry extends BufferGeometry {
  26483. /**
  26484. * Constructs a new shape geometry.
  26485. *
  26486. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26487. * @param {number} [curveSegments=12] - Number of segments per shape.
  26488. */
  26489. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26490. super();
  26491. this.type = 'ShapeGeometry';
  26492. /**
  26493. * Holds the constructor parameters that have been
  26494. * used to generate the geometry. Any modification
  26495. * after instantiation does not change the geometry.
  26496. *
  26497. * @type {Object}
  26498. */
  26499. this.parameters = {
  26500. shapes: shapes,
  26501. curveSegments: curveSegments
  26502. };
  26503. // buffers
  26504. const indices = [];
  26505. const vertices = [];
  26506. const normals = [];
  26507. const uvs = [];
  26508. // helper variables
  26509. let groupStart = 0;
  26510. let groupCount = 0;
  26511. // allow single and array values for "shapes" parameter
  26512. if ( Array.isArray( shapes ) === false ) {
  26513. addShape( shapes );
  26514. } else {
  26515. for ( let i = 0; i < shapes.length; i ++ ) {
  26516. addShape( shapes[ i ] );
  26517. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26518. groupStart += groupCount;
  26519. groupCount = 0;
  26520. }
  26521. }
  26522. // build geometry
  26523. this.setIndex( indices );
  26524. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26525. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26526. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26527. // helper functions
  26528. function addShape( shape ) {
  26529. const indexOffset = vertices.length / 3;
  26530. const points = shape.extractPoints( curveSegments );
  26531. let shapeVertices = points.shape;
  26532. const shapeHoles = points.holes;
  26533. // check direction of vertices
  26534. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26535. shapeVertices = shapeVertices.reverse();
  26536. }
  26537. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26538. const shapeHole = shapeHoles[ i ];
  26539. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26540. shapeHoles[ i ] = shapeHole.reverse();
  26541. }
  26542. }
  26543. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26544. // join vertices of inner and outer paths to a single array
  26545. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26546. const shapeHole = shapeHoles[ i ];
  26547. shapeVertices = shapeVertices.concat( shapeHole );
  26548. }
  26549. // vertices, normals, uvs
  26550. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26551. const vertex = shapeVertices[ i ];
  26552. vertices.push( vertex.x, vertex.y, 0 );
  26553. normals.push( 0, 0, 1 );
  26554. uvs.push( vertex.x, vertex.y ); // world uvs
  26555. }
  26556. // indices
  26557. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26558. const face = faces[ i ];
  26559. const a = face[ 0 ] + indexOffset;
  26560. const b = face[ 1 ] + indexOffset;
  26561. const c = face[ 2 ] + indexOffset;
  26562. indices.push( a, b, c );
  26563. groupCount += 3;
  26564. }
  26565. }
  26566. }
  26567. copy( source ) {
  26568. super.copy( source );
  26569. this.parameters = Object.assign( {}, source.parameters );
  26570. return this;
  26571. }
  26572. toJSON() {
  26573. const data = super.toJSON();
  26574. const shapes = this.parameters.shapes;
  26575. return toJSON( shapes, data );
  26576. }
  26577. /**
  26578. * Factory method for creating an instance of this class from the given
  26579. * JSON object.
  26580. *
  26581. * @param {Object} data - A JSON object representing the serialized geometry.
  26582. * @param {Array<Shape>} shapes - An array of shapes.
  26583. * @return {ShapeGeometry} A new instance.
  26584. */
  26585. static fromJSON( data, shapes ) {
  26586. const geometryShapes = [];
  26587. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26588. const shape = shapes[ data.shapes[ j ] ];
  26589. geometryShapes.push( shape );
  26590. }
  26591. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26592. }
  26593. }
  26594. function toJSON( shapes, data ) {
  26595. data.shapes = [];
  26596. if ( Array.isArray( shapes ) ) {
  26597. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26598. const shape = shapes[ i ];
  26599. data.shapes.push( shape.uuid );
  26600. }
  26601. } else {
  26602. data.shapes.push( shapes.uuid );
  26603. }
  26604. return data;
  26605. }
  26606. /**
  26607. * A class for generating a sphere geometry.
  26608. *
  26609. * ```js
  26610. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26611. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26612. * const sphere = new THREE.Mesh( geometry, material );
  26613. * scene.add( sphere );
  26614. * ```
  26615. *
  26616. * @augments BufferGeometry
  26617. * @demo scenes/geometry-browser.html#SphereGeometry
  26618. */
  26619. class SphereGeometry extends BufferGeometry {
  26620. /**
  26621. * Constructs a new sphere geometry.
  26622. *
  26623. * @param {number} [radius=1] - The sphere radius.
  26624. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26625. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26626. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26627. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26628. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26629. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26630. */
  26631. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26632. super();
  26633. this.type = 'SphereGeometry';
  26634. /**
  26635. * Holds the constructor parameters that have been
  26636. * used to generate the geometry. Any modification
  26637. * after instantiation does not change the geometry.
  26638. *
  26639. * @type {Object}
  26640. */
  26641. this.parameters = {
  26642. radius: radius,
  26643. widthSegments: widthSegments,
  26644. heightSegments: heightSegments,
  26645. phiStart: phiStart,
  26646. phiLength: phiLength,
  26647. thetaStart: thetaStart,
  26648. thetaLength: thetaLength
  26649. };
  26650. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26651. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26652. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26653. let index = 0;
  26654. const grid = [];
  26655. const vertex = new Vector3();
  26656. const normal = new Vector3();
  26657. // buffers
  26658. const indices = [];
  26659. const vertices = [];
  26660. const normals = [];
  26661. const uvs = [];
  26662. // generate vertices, normals and uvs
  26663. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26664. const verticesRow = [];
  26665. const v = iy / heightSegments;
  26666. const theta = thetaStart + v * thetaLength;
  26667. const y = radius * Math.cos( theta );
  26668. const ringRadius = Math.sqrt( radius * radius - y * y );
  26669. // special case for the poles
  26670. let uOffset = 0;
  26671. if ( iy === 0 && thetaStart === 0 ) {
  26672. uOffset = 0.5 / widthSegments;
  26673. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26674. uOffset = -0.5 / widthSegments;
  26675. }
  26676. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26677. const u = ix / widthSegments;
  26678. const phi = phiStart + u * phiLength;
  26679. // vertex
  26680. vertex.x = - ringRadius * Math.cos( phi );
  26681. vertex.y = y;
  26682. vertex.z = ringRadius * Math.sin( phi );
  26683. vertices.push( vertex.x, vertex.y, vertex.z );
  26684. // normal
  26685. normal.copy( vertex ).normalize();
  26686. normals.push( normal.x, normal.y, normal.z );
  26687. // uv
  26688. uvs.push( u + uOffset, 1 - v );
  26689. verticesRow.push( index ++ );
  26690. }
  26691. grid.push( verticesRow );
  26692. }
  26693. // indices
  26694. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26695. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26696. const a = grid[ iy ][ ix + 1 ];
  26697. const b = grid[ iy ][ ix ];
  26698. const c = grid[ iy + 1 ][ ix ];
  26699. const d = grid[ iy + 1 ][ ix + 1 ];
  26700. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26701. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26702. }
  26703. }
  26704. // build geometry
  26705. this.setIndex( indices );
  26706. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26707. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26708. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26709. }
  26710. copy( source ) {
  26711. super.copy( source );
  26712. this.parameters = Object.assign( {}, source.parameters );
  26713. return this;
  26714. }
  26715. /**
  26716. * Factory method for creating an instance of this class from the given
  26717. * JSON object.
  26718. *
  26719. * @param {Object} data - A JSON object representing the serialized geometry.
  26720. * @return {SphereGeometry} A new instance.
  26721. */
  26722. static fromJSON( data ) {
  26723. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26724. }
  26725. }
  26726. /**
  26727. * A geometry class for representing an tetrahedron.
  26728. *
  26729. * ```js
  26730. * const geometry = new THREE.TetrahedronGeometry();
  26731. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26732. * const tetrahedron = new THREE.Mesh( geometry, material );
  26733. * scene.add( tetrahedron );
  26734. * ```
  26735. *
  26736. * @augments PolyhedronGeometry
  26737. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  26738. */
  26739. class TetrahedronGeometry extends PolyhedronGeometry {
  26740. /**
  26741. * Constructs a new tetrahedron geometry.
  26742. *
  26743. * @param {number} [radius=1] - Radius of the tetrahedron.
  26744. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26745. */
  26746. constructor( radius = 1, detail = 0 ) {
  26747. const vertices = [
  26748. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26749. ];
  26750. const indices = [
  26751. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26752. ];
  26753. super( vertices, indices, radius, detail );
  26754. this.type = 'TetrahedronGeometry';
  26755. /**
  26756. * Holds the constructor parameters that have been
  26757. * used to generate the geometry. Any modification
  26758. * after instantiation does not change the geometry.
  26759. *
  26760. * @type {Object}
  26761. */
  26762. this.parameters = {
  26763. radius: radius,
  26764. detail: detail
  26765. };
  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 {TetrahedronGeometry} A new instance.
  26773. */
  26774. static fromJSON( data ) {
  26775. return new TetrahedronGeometry( data.radius, data.detail );
  26776. }
  26777. }
  26778. /**
  26779. * A geometry class for representing an torus.
  26780. *
  26781. * ```js
  26782. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26783. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26784. * const torus = new THREE.Mesh( geometry, material );
  26785. * scene.add( torus );
  26786. * ```
  26787. *
  26788. * @augments BufferGeometry
  26789. * @demo scenes/geometry-browser.html#TorusGeometry
  26790. */
  26791. class TorusGeometry extends BufferGeometry {
  26792. /**
  26793. * Constructs a new torus geometry.
  26794. *
  26795. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26796. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26797. * @param {number} [radialSegments=12] - The number of radial segments.
  26798. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26799. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26800. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  26801. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  26802. */
  26803. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26804. super();
  26805. this.type = 'TorusGeometry';
  26806. /**
  26807. * Holds the constructor parameters that have been
  26808. * used to generate the geometry. Any modification
  26809. * after instantiation does not change the geometry.
  26810. *
  26811. * @type {Object}
  26812. */
  26813. this.parameters = {
  26814. radius: radius,
  26815. tube: tube,
  26816. radialSegments: radialSegments,
  26817. tubularSegments: tubularSegments,
  26818. arc: arc,
  26819. thetaStart: thetaStart,
  26820. thetaLength: thetaLength,
  26821. };
  26822. radialSegments = Math.floor( radialSegments );
  26823. tubularSegments = Math.floor( tubularSegments );
  26824. // buffers
  26825. const indices = [];
  26826. const vertices = [];
  26827. const normals = [];
  26828. const uvs = [];
  26829. // helper variables
  26830. const center = new Vector3();
  26831. const vertex = new Vector3();
  26832. const normal = new Vector3();
  26833. // generate vertices, normals and uvs
  26834. for ( let j = 0; j <= radialSegments; j ++ ) {
  26835. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  26836. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26837. const u = i / tubularSegments * arc;
  26838. // vertex
  26839. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26840. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26841. vertex.z = tube * Math.sin( v );
  26842. vertices.push( vertex.x, vertex.y, vertex.z );
  26843. // normal
  26844. center.x = radius * Math.cos( u );
  26845. center.y = radius * Math.sin( u );
  26846. normal.subVectors( vertex, center ).normalize();
  26847. normals.push( normal.x, normal.y, normal.z );
  26848. // uv
  26849. uvs.push( i / tubularSegments );
  26850. uvs.push( j / radialSegments );
  26851. }
  26852. }
  26853. // generate indices
  26854. for ( let j = 1; j <= radialSegments; j ++ ) {
  26855. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26856. // indices
  26857. const a = ( tubularSegments + 1 ) * j + i - 1;
  26858. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26859. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26860. const d = ( tubularSegments + 1 ) * j + i;
  26861. // faces
  26862. indices.push( a, b, d );
  26863. indices.push( b, c, d );
  26864. }
  26865. }
  26866. // build geometry
  26867. this.setIndex( indices );
  26868. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26869. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26870. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26871. }
  26872. copy( source ) {
  26873. super.copy( source );
  26874. this.parameters = Object.assign( {}, source.parameters );
  26875. return this;
  26876. }
  26877. /**
  26878. * Factory method for creating an instance of this class from the given
  26879. * JSON object.
  26880. *
  26881. * @param {Object} data - A JSON object representing the serialized geometry.
  26882. * @return {TorusGeometry} A new instance.
  26883. */
  26884. static fromJSON( data ) {
  26885. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26886. }
  26887. }
  26888. /**
  26889. * Creates a torus knot, the particular shape of which is defined by a pair
  26890. * of coprime integers, p and q. If p and q are not coprime, the result will
  26891. * be a torus link.
  26892. *
  26893. * ```js
  26894. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26895. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26896. * const torusKnot = new THREE.Mesh( geometry, material );
  26897. * scene.add( torusKnot );
  26898. * ```
  26899. *
  26900. * @augments BufferGeometry
  26901. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  26902. */
  26903. class TorusKnotGeometry extends BufferGeometry {
  26904. /**
  26905. * Constructs a new torus knot geometry.
  26906. *
  26907. * @param {number} [radius=1] - Radius of the torus knot.
  26908. * @param {number} [tube=0.4] - Radius of the tube.
  26909. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26910. * @param {number} [radialSegments=8] - The number of radial segments.
  26911. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26912. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26913. */
  26914. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26915. super();
  26916. this.type = 'TorusKnotGeometry';
  26917. /**
  26918. * Holds the constructor parameters that have been
  26919. * used to generate the geometry. Any modification
  26920. * after instantiation does not change the geometry.
  26921. *
  26922. * @type {Object}
  26923. */
  26924. this.parameters = {
  26925. radius: radius,
  26926. tube: tube,
  26927. tubularSegments: tubularSegments,
  26928. radialSegments: radialSegments,
  26929. p: p,
  26930. q: q
  26931. };
  26932. tubularSegments = Math.floor( tubularSegments );
  26933. radialSegments = Math.floor( radialSegments );
  26934. // buffers
  26935. const indices = [];
  26936. const vertices = [];
  26937. const normals = [];
  26938. const uvs = [];
  26939. // helper variables
  26940. const vertex = new Vector3();
  26941. const normal = new Vector3();
  26942. const P1 = new Vector3();
  26943. const P2 = new Vector3();
  26944. const B = new Vector3();
  26945. const T = new Vector3();
  26946. const N = new Vector3();
  26947. // generate vertices, normals and uvs
  26948. for ( let i = 0; i <= tubularSegments; ++ i ) {
  26949. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  26950. const u = i / tubularSegments * p * Math.PI * 2;
  26951. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  26952. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26953. calculatePositionOnCurve( u, p, q, radius, P1 );
  26954. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  26955. // calculate orthonormal basis
  26956. T.subVectors( P2, P1 );
  26957. N.addVectors( P2, P1 );
  26958. B.crossVectors( T, N );
  26959. N.crossVectors( B, T );
  26960. // normalize B, N. T can be ignored, we don't use it
  26961. B.normalize();
  26962. N.normalize();
  26963. for ( let j = 0; j <= radialSegments; ++ j ) {
  26964. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26965. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26966. const v = j / radialSegments * Math.PI * 2;
  26967. const cx = - tube * Math.cos( v );
  26968. const cy = tube * Math.sin( v );
  26969. // now calculate the final vertex position.
  26970. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  26971. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  26972. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  26973. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  26974. vertices.push( vertex.x, vertex.y, vertex.z );
  26975. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  26976. normal.subVectors( vertex, P1 ).normalize();
  26977. normals.push( normal.x, normal.y, normal.z );
  26978. // uv
  26979. uvs.push( i / tubularSegments );
  26980. uvs.push( j / radialSegments );
  26981. }
  26982. }
  26983. // generate indices
  26984. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26985. for ( let i = 1; i <= radialSegments; i ++ ) {
  26986. // indices
  26987. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26988. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26989. const c = ( radialSegments + 1 ) * j + i;
  26990. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26991. // faces
  26992. indices.push( a, b, d );
  26993. indices.push( b, c, d );
  26994. }
  26995. }
  26996. // build geometry
  26997. this.setIndex( indices );
  26998. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26999. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27000. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27001. // this function calculates the current position on the torus curve
  27002. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27003. const cu = Math.cos( u );
  27004. const su = Math.sin( u );
  27005. const quOverP = q / p * u;
  27006. const cs = Math.cos( quOverP );
  27007. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27008. position.y = radius * ( 2 + cs ) * su * 0.5;
  27009. position.z = radius * Math.sin( quOverP ) * 0.5;
  27010. }
  27011. }
  27012. copy( source ) {
  27013. super.copy( source );
  27014. this.parameters = Object.assign( {}, source.parameters );
  27015. return this;
  27016. }
  27017. /**
  27018. * Factory method for creating an instance of this class from the given
  27019. * JSON object.
  27020. *
  27021. * @param {Object} data - A JSON object representing the serialized geometry.
  27022. * @return {TorusKnotGeometry} A new instance.
  27023. */
  27024. static fromJSON( data ) {
  27025. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27026. }
  27027. }
  27028. /**
  27029. * Creates a tube that extrudes along a 3D curve.
  27030. *
  27031. * ```js
  27032. * class CustomSinCurve extends THREE.Curve {
  27033. *
  27034. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27035. *
  27036. * const tx = t * 3 - 1.5;
  27037. * const ty = Math.sin( 2 * Math.PI * t );
  27038. * const tz = 0;
  27039. *
  27040. * return optionalTarget.set( tx, ty, tz );
  27041. * }
  27042. *
  27043. * }
  27044. *
  27045. * const path = new CustomSinCurve( 10 );
  27046. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27047. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27048. * const mesh = new THREE.Mesh( geometry, material );
  27049. * scene.add( mesh );
  27050. * ```
  27051. *
  27052. * @augments BufferGeometry
  27053. * @demo scenes/geometry-browser.html#TubeGeometry
  27054. */
  27055. class TubeGeometry extends BufferGeometry {
  27056. /**
  27057. * Constructs a new tube geometry.
  27058. *
  27059. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27060. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27061. * @param {number} [radius=1] -The radius of the tube.
  27062. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27063. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27064. */
  27065. 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 ) {
  27066. super();
  27067. this.type = 'TubeGeometry';
  27068. /**
  27069. * Holds the constructor parameters that have been
  27070. * used to generate the geometry. Any modification
  27071. * after instantiation does not change the geometry.
  27072. *
  27073. * @type {Object}
  27074. */
  27075. this.parameters = {
  27076. path: path,
  27077. tubularSegments: tubularSegments,
  27078. radius: radius,
  27079. radialSegments: radialSegments,
  27080. closed: closed
  27081. };
  27082. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27083. // expose internals
  27084. this.tangents = frames.tangents;
  27085. this.normals = frames.normals;
  27086. this.binormals = frames.binormals;
  27087. // helper variables
  27088. const vertex = new Vector3();
  27089. const normal = new Vector3();
  27090. const uv = new Vector2();
  27091. let P = new Vector3();
  27092. // buffer
  27093. const vertices = [];
  27094. const normals = [];
  27095. const uvs = [];
  27096. const indices = [];
  27097. // create buffer data
  27098. generateBufferData();
  27099. // build geometry
  27100. this.setIndex( indices );
  27101. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27102. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27103. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27104. // functions
  27105. function generateBufferData() {
  27106. for ( let i = 0; i < tubularSegments; i ++ ) {
  27107. generateSegment( i );
  27108. }
  27109. // if the geometry is not closed, generate the last row of vertices and normals
  27110. // at the regular position on the given path
  27111. //
  27112. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27113. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27114. // uvs are generated in a separate function.
  27115. // this makes it easy compute correct values for closed geometries
  27116. generateUVs();
  27117. // finally create faces
  27118. generateIndices();
  27119. }
  27120. function generateSegment( i ) {
  27121. // we use getPointAt to sample evenly distributed points from the given path
  27122. P = path.getPointAt( i / tubularSegments, P );
  27123. // retrieve corresponding normal and binormal
  27124. const N = frames.normals[ i ];
  27125. const B = frames.binormals[ i ];
  27126. // generate normals and vertices for the current segment
  27127. for ( let j = 0; j <= radialSegments; j ++ ) {
  27128. const v = j / radialSegments * Math.PI * 2;
  27129. const sin = Math.sin( v );
  27130. const cos = - Math.cos( v );
  27131. // normal
  27132. normal.x = ( cos * N.x + sin * B.x );
  27133. normal.y = ( cos * N.y + sin * B.y );
  27134. normal.z = ( cos * N.z + sin * B.z );
  27135. normal.normalize();
  27136. normals.push( normal.x, normal.y, normal.z );
  27137. // vertex
  27138. vertex.x = P.x + radius * normal.x;
  27139. vertex.y = P.y + radius * normal.y;
  27140. vertex.z = P.z + radius * normal.z;
  27141. vertices.push( vertex.x, vertex.y, vertex.z );
  27142. }
  27143. }
  27144. function generateIndices() {
  27145. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27146. for ( let i = 1; i <= radialSegments; i ++ ) {
  27147. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27148. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27149. const c = ( radialSegments + 1 ) * j + i;
  27150. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27151. // faces
  27152. indices.push( a, b, d );
  27153. indices.push( b, c, d );
  27154. }
  27155. }
  27156. }
  27157. function generateUVs() {
  27158. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27159. for ( let j = 0; j <= radialSegments; j ++ ) {
  27160. uv.x = i / tubularSegments;
  27161. uv.y = j / radialSegments;
  27162. uvs.push( uv.x, uv.y );
  27163. }
  27164. }
  27165. }
  27166. }
  27167. copy( source ) {
  27168. super.copy( source );
  27169. this.parameters = Object.assign( {}, source.parameters );
  27170. return this;
  27171. }
  27172. toJSON() {
  27173. const data = super.toJSON();
  27174. data.path = this.parameters.path.toJSON();
  27175. return data;
  27176. }
  27177. /**
  27178. * Factory method for creating an instance of this class from the given
  27179. * JSON object.
  27180. *
  27181. * @param {Object} data - A JSON object representing the serialized geometry.
  27182. * @return {TubeGeometry} A new instance.
  27183. */
  27184. static fromJSON( data ) {
  27185. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27186. // User defined curves or instances of CurvePath will not be deserialized.
  27187. return new TubeGeometry(
  27188. new Curves[ data.path.type ]().fromJSON( data.path ),
  27189. data.tubularSegments,
  27190. data.radius,
  27191. data.radialSegments,
  27192. data.closed
  27193. );
  27194. }
  27195. }
  27196. /**
  27197. * Can be used as a helper object to visualize a geometry as a wireframe.
  27198. *
  27199. * ```js
  27200. * const geometry = new THREE.SphereGeometry();
  27201. *
  27202. * const wireframe = new THREE.WireframeGeometry( geometry );
  27203. *
  27204. * const line = new THREE.LineSegments( wireframe );
  27205. * line.material.depthWrite = false;
  27206. * line.material.opacity = 0.25;
  27207. * line.material.transparent = true;
  27208. *
  27209. * scene.add( line );
  27210. * ```
  27211. *
  27212. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27213. *
  27214. * @augments BufferGeometry
  27215. */
  27216. class WireframeGeometry extends BufferGeometry {
  27217. /**
  27218. * Constructs a new wireframe geometry.
  27219. *
  27220. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27221. */
  27222. constructor( geometry = null ) {
  27223. super();
  27224. this.type = 'WireframeGeometry';
  27225. /**
  27226. * Holds the constructor parameters that have been
  27227. * used to generate the geometry. Any modification
  27228. * after instantiation does not change the geometry.
  27229. *
  27230. * @type {Object}
  27231. */
  27232. this.parameters = {
  27233. geometry: geometry
  27234. };
  27235. if ( geometry !== null ) {
  27236. // buffer
  27237. const vertices = [];
  27238. const edges = new Set();
  27239. // helper variables
  27240. const start = new Vector3();
  27241. const end = new Vector3();
  27242. if ( geometry.index !== null ) {
  27243. // indexed BufferGeometry
  27244. const position = geometry.attributes.position;
  27245. const indices = geometry.index;
  27246. let groups = geometry.groups;
  27247. if ( groups.length === 0 ) {
  27248. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27249. }
  27250. // create a data structure that contains all edges without duplicates
  27251. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27252. const group = groups[ o ];
  27253. const groupStart = group.start;
  27254. const groupCount = group.count;
  27255. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27256. for ( let j = 0; j < 3; j ++ ) {
  27257. const index1 = indices.getX( i + j );
  27258. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27259. start.fromBufferAttribute( position, index1 );
  27260. end.fromBufferAttribute( position, index2 );
  27261. if ( isUniqueEdge( start, end, edges ) === true ) {
  27262. vertices.push( start.x, start.y, start.z );
  27263. vertices.push( end.x, end.y, end.z );
  27264. }
  27265. }
  27266. }
  27267. }
  27268. } else {
  27269. // non-indexed BufferGeometry
  27270. const position = geometry.attributes.position;
  27271. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27272. for ( let j = 0; j < 3; j ++ ) {
  27273. // three edges per triangle, an edge is represented as (index1, index2)
  27274. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27275. const index1 = 3 * i + j;
  27276. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27277. start.fromBufferAttribute( position, index1 );
  27278. end.fromBufferAttribute( position, index2 );
  27279. if ( isUniqueEdge( start, end, edges ) === true ) {
  27280. vertices.push( start.x, start.y, start.z );
  27281. vertices.push( end.x, end.y, end.z );
  27282. }
  27283. }
  27284. }
  27285. }
  27286. // build geometry
  27287. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27288. }
  27289. }
  27290. copy( source ) {
  27291. super.copy( source );
  27292. this.parameters = Object.assign( {}, source.parameters );
  27293. return this;
  27294. }
  27295. }
  27296. function isUniqueEdge( start, end, edges ) {
  27297. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27298. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27299. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27300. return false;
  27301. } else {
  27302. edges.add( hash1 );
  27303. edges.add( hash2 );
  27304. return true;
  27305. }
  27306. }
  27307. var Geometries = /*#__PURE__*/Object.freeze({
  27308. __proto__: null,
  27309. BoxGeometry: BoxGeometry,
  27310. CapsuleGeometry: CapsuleGeometry,
  27311. CircleGeometry: CircleGeometry,
  27312. ConeGeometry: ConeGeometry,
  27313. CylinderGeometry: CylinderGeometry,
  27314. DodecahedronGeometry: DodecahedronGeometry,
  27315. EdgesGeometry: EdgesGeometry,
  27316. ExtrudeGeometry: ExtrudeGeometry,
  27317. IcosahedronGeometry: IcosahedronGeometry,
  27318. LatheGeometry: LatheGeometry,
  27319. OctahedronGeometry: OctahedronGeometry,
  27320. PlaneGeometry: PlaneGeometry,
  27321. PolyhedronGeometry: PolyhedronGeometry,
  27322. RingGeometry: RingGeometry,
  27323. ShapeGeometry: ShapeGeometry,
  27324. SphereGeometry: SphereGeometry,
  27325. TetrahedronGeometry: TetrahedronGeometry,
  27326. TorusGeometry: TorusGeometry,
  27327. TorusKnotGeometry: TorusKnotGeometry,
  27328. TubeGeometry: TubeGeometry,
  27329. WireframeGeometry: WireframeGeometry
  27330. });
  27331. /**
  27332. * This material can receive shadows, but otherwise is completely transparent.
  27333. *
  27334. * ```js
  27335. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27336. * geometry.rotateX( - Math.PI / 2 );
  27337. *
  27338. * const material = new THREE.ShadowMaterial();
  27339. * material.opacity = 0.2;
  27340. *
  27341. * const plane = new THREE.Mesh( geometry, material );
  27342. * plane.position.y = -200;
  27343. * plane.receiveShadow = true;
  27344. * scene.add( plane );
  27345. * ```
  27346. *
  27347. * @augments Material
  27348. */
  27349. class ShadowMaterial extends Material {
  27350. /**
  27351. * Constructs a new shadow material.
  27352. *
  27353. * @param {Object} [parameters] - An object with one or more properties
  27354. * defining the material's appearance. Any property of the material
  27355. * (including any property from inherited materials) can be passed
  27356. * in here. Color values can be passed any type of value accepted
  27357. * by {@link Color#set}.
  27358. */
  27359. constructor( parameters ) {
  27360. super();
  27361. /**
  27362. * This flag can be used for type testing.
  27363. *
  27364. * @type {boolean}
  27365. * @readonly
  27366. * @default true
  27367. */
  27368. this.isShadowMaterial = true;
  27369. this.type = 'ShadowMaterial';
  27370. /**
  27371. * Color of the material.
  27372. *
  27373. * @type {Color}
  27374. * @default (0,0,0)
  27375. */
  27376. this.color = new Color( 0x000000 );
  27377. /**
  27378. * Overwritten since shadow materials are transparent
  27379. * by default.
  27380. *
  27381. * @type {boolean}
  27382. * @default true
  27383. */
  27384. this.transparent = true;
  27385. /**
  27386. * Whether the material is affected by fog or not.
  27387. *
  27388. * @type {boolean}
  27389. * @default true
  27390. */
  27391. this.fog = true;
  27392. this.setValues( parameters );
  27393. }
  27394. copy( source ) {
  27395. super.copy( source );
  27396. this.color.copy( source.color );
  27397. this.fog = source.fog;
  27398. return this;
  27399. }
  27400. }
  27401. /**
  27402. * Provides utility functions for managing uniforms.
  27403. *
  27404. * @module UniformsUtils
  27405. */
  27406. /**
  27407. * Clones the given uniform definitions by performing a deep-copy. That means
  27408. * if the value of a uniform refers to an object like a Vector3 or Texture,
  27409. * the cloned uniform will refer to a new object reference.
  27410. *
  27411. * @param {Object} src - An object representing uniform definitions.
  27412. * @return {Object} The cloned uniforms.
  27413. */
  27414. function cloneUniforms( src ) {
  27415. const dst = {};
  27416. for ( const u in src ) {
  27417. dst[ u ] = {};
  27418. for ( const p in src[ u ] ) {
  27419. const property = src[ u ][ p ];
  27420. if ( isThreeObject( property ) ) {
  27421. if ( property.isRenderTargetTexture ) {
  27422. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  27423. dst[ u ][ p ] = null;
  27424. } else {
  27425. dst[ u ][ p ] = property.clone();
  27426. }
  27427. } else if ( Array.isArray( property ) ) {
  27428. if ( isThreeObject( property[ 0 ] ) ) {
  27429. const clonedProperty = [];
  27430. for ( let i = 0, l = property.length; i < l; i ++ ) {
  27431. clonedProperty[ i ] = property[ i ].clone();
  27432. }
  27433. dst[ u ][ p ] = clonedProperty;
  27434. } else {
  27435. dst[ u ][ p ] = property.slice();
  27436. }
  27437. } else {
  27438. dst[ u ][ p ] = property;
  27439. }
  27440. }
  27441. }
  27442. return dst;
  27443. }
  27444. /**
  27445. * Merges the given uniform definitions into a single object. Since the
  27446. * method internally uses cloneUniforms(), it performs a deep-copy when
  27447. * producing the merged uniform definitions.
  27448. *
  27449. * @param {Array} uniforms - An array of objects containing uniform definitions.
  27450. * @return {Object} The merged uniforms.
  27451. */
  27452. function mergeUniforms( uniforms ) {
  27453. const merged = {};
  27454. for ( let u = 0; u < uniforms.length; u ++ ) {
  27455. const tmp = cloneUniforms( uniforms[ u ] );
  27456. for ( const p in tmp ) {
  27457. merged[ p ] = tmp[ p ];
  27458. }
  27459. }
  27460. return merged;
  27461. }
  27462. function isThreeObject( property ) {
  27463. return ( property && ( property.isColor ||
  27464. property.isMatrix3 || property.isMatrix4 ||
  27465. property.isVector2 || property.isVector3 || property.isVector4 ||
  27466. property.isTexture || property.isQuaternion ) );
  27467. }
  27468. function cloneUniformsGroups( src ) {
  27469. const dst = [];
  27470. for ( let u = 0; u < src.length; u ++ ) {
  27471. dst.push( src[ u ].clone() );
  27472. }
  27473. return dst;
  27474. }
  27475. function getUnlitUniformColorSpace( renderer ) {
  27476. const currentRenderTarget = renderer.getRenderTarget();
  27477. if ( currentRenderTarget === null ) {
  27478. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  27479. return renderer.outputColorSpace;
  27480. }
  27481. // https://github.com/mrdoob/three.js/issues/27868
  27482. if ( currentRenderTarget.isXRRenderTarget === true ) {
  27483. return currentRenderTarget.texture.colorSpace;
  27484. }
  27485. return ColorManagement.workingColorSpace;
  27486. }
  27487. // Legacy
  27488. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  27489. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  27490. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  27491. /**
  27492. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  27493. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  27494. * effect not included with any of the built-in materials.
  27495. *
  27496. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  27497. *
  27498. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  27499. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  27500. * you don't want that, use {@link RawShaderMaterial} instead.
  27501. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  27502. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  27503. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  27504. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  27505. * - The loop variable has to be *i*.
  27506. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  27507. * value of *i* for the given iteration and can be used in preprocessor
  27508. * statements.
  27509. *
  27510. * ```js
  27511. * const material = new THREE.ShaderMaterial( {
  27512. * uniforms: {
  27513. * time: { value: 1.0 },
  27514. * resolution: { value: new THREE.Vector2() }
  27515. * },
  27516. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  27517. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  27518. * } );
  27519. * ```
  27520. *
  27521. * @augments Material
  27522. */
  27523. class ShaderMaterial extends Material {
  27524. /**
  27525. * Constructs a new shader material.
  27526. *
  27527. * @param {Object} [parameters] - An object with one or more properties
  27528. * defining the material's appearance. Any property of the material
  27529. * (including any property from inherited materials) can be passed
  27530. * in here. Color values can be passed any type of value accepted
  27531. * by {@link Color#set}.
  27532. */
  27533. constructor( parameters ) {
  27534. super();
  27535. /**
  27536. * This flag can be used for type testing.
  27537. *
  27538. * @type {boolean}
  27539. * @readonly
  27540. * @default true
  27541. */
  27542. this.isShaderMaterial = true;
  27543. this.type = 'ShaderMaterial';
  27544. /**
  27545. * Defines custom constants using `#define` directives within the GLSL code
  27546. * for both the vertex shader and the fragment shader; each key/value pair
  27547. * yields another directive.
  27548. * ```js
  27549. * defines: {
  27550. * FOO: 15,
  27551. * BAR: true
  27552. * }
  27553. * ```
  27554. * Yields the lines:
  27555. * ```
  27556. * #define FOO 15
  27557. * #define BAR true
  27558. * ```
  27559. *
  27560. * @type {Object}
  27561. */
  27562. this.defines = {};
  27563. /**
  27564. * An object of the form:
  27565. * ```js
  27566. * {
  27567. * "uniform1": { value: 1.0 },
  27568. * "uniform2": { value: 2 }
  27569. * }
  27570. * ```
  27571. * specifying the uniforms to be passed to the shader code; keys are uniform
  27572. * names, values are definitions of the form
  27573. * ```
  27574. * {
  27575. * value: 1.0
  27576. * }
  27577. * ```
  27578. * where `value` is the value of the uniform. Names must match the name of
  27579. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  27580. * on every frame, so updating the value of the uniform will immediately
  27581. * update the value available to the GLSL code.
  27582. *
  27583. * @type {Object}
  27584. */
  27585. this.uniforms = {};
  27586. /**
  27587. * An array holding uniforms groups for configuring UBOs.
  27588. *
  27589. * @type {Array<UniformsGroup>}
  27590. */
  27591. this.uniformsGroups = [];
  27592. /**
  27593. * Vertex shader GLSL code. This is the actual code for the shader.
  27594. *
  27595. * @type {string}
  27596. */
  27597. this.vertexShader = default_vertex;
  27598. /**
  27599. * Fragment shader GLSL code. This is the actual code for the shader.
  27600. *
  27601. * @type {string}
  27602. */
  27603. this.fragmentShader = default_fragment;
  27604. /**
  27605. * Controls line thickness or lines.
  27606. *
  27607. * WebGL and WebGPU ignore this setting and always render line primitives with a
  27608. * width of one pixel.
  27609. *
  27610. * @type {number}
  27611. * @default 1
  27612. */
  27613. this.linewidth = 1;
  27614. /**
  27615. * Renders the geometry as a wireframe.
  27616. *
  27617. * @type {boolean}
  27618. * @default false
  27619. */
  27620. this.wireframe = false;
  27621. /**
  27622. * Controls the thickness of the wireframe.
  27623. *
  27624. * WebGL and WebGPU ignore this property and always render
  27625. * 1 pixel wide lines.
  27626. *
  27627. * @type {number}
  27628. * @default 1
  27629. */
  27630. this.wireframeLinewidth = 1;
  27631. /**
  27632. * Defines whether the material color is affected by global fog settings; `true`
  27633. * to pass fog uniforms to the shader.
  27634. *
  27635. * Setting this property to `true` requires the definition of fog uniforms. It is
  27636. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  27637. * with predefined fog uniforms.
  27638. *
  27639. * ```js
  27640. * const material = new ShaderMaterial( {
  27641. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  27642. * vertexShader: vertexShader,
  27643. * fragmentShader: fragmentShader,
  27644. * fog: true
  27645. * } );
  27646. * ```
  27647. *
  27648. * @type {boolean}
  27649. * @default false
  27650. */
  27651. this.fog = false;
  27652. /**
  27653. * Defines whether this material uses lighting; `true` to pass uniform data
  27654. * related to lighting to this shader.
  27655. *
  27656. * @type {boolean}
  27657. * @default false
  27658. */
  27659. this.lights = false;
  27660. /**
  27661. * Defines whether this material supports clipping; `true` to let the renderer
  27662. * pass the clippingPlanes uniform.
  27663. *
  27664. * @type {boolean}
  27665. * @default false
  27666. */
  27667. this.clipping = false;
  27668. /**
  27669. * Overwritten and set to `true` by default.
  27670. *
  27671. * @type {boolean}
  27672. * @default true
  27673. */
  27674. this.forceSinglePass = true;
  27675. /**
  27676. * This object allows to enable certain WebGL 2 extensions.
  27677. *
  27678. * - clipCullDistance: set to `true` to use vertex shader clipping
  27679. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  27680. *
  27681. * @type {{clipCullDistance:false,multiDraw:false}}
  27682. */
  27683. this.extensions = {
  27684. clipCullDistance: false, // set to use vertex shader clipping
  27685. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  27686. };
  27687. /**
  27688. * When the rendered geometry doesn't include these attributes but the
  27689. * material does, these default values will be passed to the shaders. This
  27690. * avoids errors when buffer data is missing.
  27691. *
  27692. * - color: [ 1, 1, 1 ]
  27693. * - uv: [ 0, 0 ]
  27694. * - uv1: [ 0, 0 ]
  27695. *
  27696. * @type {Object}
  27697. */
  27698. this.defaultAttributeValues = {
  27699. 'color': [ 1, 1, 1 ],
  27700. 'uv': [ 0, 0 ],
  27701. 'uv1': [ 0, 0 ]
  27702. };
  27703. /**
  27704. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  27705. * to bind a generic vertex index to an attribute variable.
  27706. *
  27707. * @type {string|undefined}
  27708. * @default undefined
  27709. */
  27710. this.index0AttributeName = undefined;
  27711. /**
  27712. * Can be used to force a uniform update while changing uniforms in
  27713. * {@link Object3D#onBeforeRender}.
  27714. *
  27715. * @type {boolean}
  27716. * @default false
  27717. */
  27718. this.uniformsNeedUpdate = false;
  27719. /**
  27720. * Defines the GLSL version of custom shader code.
  27721. *
  27722. * @type {?(GLSL1|GLSL3)}
  27723. * @default null
  27724. */
  27725. this.glslVersion = null;
  27726. if ( parameters !== undefined ) {
  27727. this.setValues( parameters );
  27728. }
  27729. }
  27730. copy( source ) {
  27731. super.copy( source );
  27732. this.fragmentShader = source.fragmentShader;
  27733. this.vertexShader = source.vertexShader;
  27734. this.uniforms = cloneUniforms( source.uniforms );
  27735. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  27736. this.defines = Object.assign( {}, source.defines );
  27737. this.wireframe = source.wireframe;
  27738. this.wireframeLinewidth = source.wireframeLinewidth;
  27739. this.fog = source.fog;
  27740. this.lights = source.lights;
  27741. this.clipping = source.clipping;
  27742. this.extensions = Object.assign( {}, source.extensions );
  27743. this.glslVersion = source.glslVersion;
  27744. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  27745. this.index0AttributeName = source.index0AttributeName;
  27746. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  27747. return this;
  27748. }
  27749. toJSON( meta ) {
  27750. const data = super.toJSON( meta );
  27751. data.glslVersion = this.glslVersion;
  27752. data.uniforms = {};
  27753. for ( const name in this.uniforms ) {
  27754. const uniform = this.uniforms[ name ];
  27755. const value = uniform.value;
  27756. if ( value && value.isTexture ) {
  27757. data.uniforms[ name ] = {
  27758. type: 't',
  27759. value: value.toJSON( meta ).uuid
  27760. };
  27761. } else if ( value && value.isColor ) {
  27762. data.uniforms[ name ] = {
  27763. type: 'c',
  27764. value: value.getHex()
  27765. };
  27766. } else if ( value && value.isVector2 ) {
  27767. data.uniforms[ name ] = {
  27768. type: 'v2',
  27769. value: value.toArray()
  27770. };
  27771. } else if ( value && value.isVector3 ) {
  27772. data.uniforms[ name ] = {
  27773. type: 'v3',
  27774. value: value.toArray()
  27775. };
  27776. } else if ( value && value.isVector4 ) {
  27777. data.uniforms[ name ] = {
  27778. type: 'v4',
  27779. value: value.toArray()
  27780. };
  27781. } else if ( value && value.isMatrix3 ) {
  27782. data.uniforms[ name ] = {
  27783. type: 'm3',
  27784. value: value.toArray()
  27785. };
  27786. } else if ( value && value.isMatrix4 ) {
  27787. data.uniforms[ name ] = {
  27788. type: 'm4',
  27789. value: value.toArray()
  27790. };
  27791. } else {
  27792. data.uniforms[ name ] = {
  27793. value: value
  27794. };
  27795. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  27796. }
  27797. }
  27798. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  27799. data.vertexShader = this.vertexShader;
  27800. data.fragmentShader = this.fragmentShader;
  27801. data.lights = this.lights;
  27802. data.clipping = this.clipping;
  27803. const extensions = {};
  27804. for ( const key in this.extensions ) {
  27805. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  27806. }
  27807. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  27808. return data;
  27809. }
  27810. /**
  27811. * Deserializes the material from the given JSON.
  27812. *
  27813. * @param {Object} json - The JSON holding the serialized material.
  27814. * @param {Object<string,Texture>} textures - A dictionary holding textures referenced by the material.
  27815. * @return {ShaderMaterial} A reference to this material.
  27816. */
  27817. fromJSON( json, textures ) {
  27818. super.fromJSON( json, textures );
  27819. if ( json.uniforms !== undefined ) {
  27820. for ( const name in json.uniforms ) {
  27821. const uniform = json.uniforms[ name ];
  27822. this.uniforms[ name ] = {};
  27823. switch ( uniform.type ) {
  27824. case 't':
  27825. this.uniforms[ name ].value = textures[ uniform.value ] || null;
  27826. break;
  27827. case 'c':
  27828. this.uniforms[ name ].value = new Color().setHex( uniform.value );
  27829. break;
  27830. case 'v2':
  27831. this.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  27832. break;
  27833. case 'v3':
  27834. this.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  27835. break;
  27836. case 'v4':
  27837. this.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  27838. break;
  27839. case 'm3':
  27840. this.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  27841. break;
  27842. case 'm4':
  27843. this.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  27844. break;
  27845. default:
  27846. this.uniforms[ name ].value = uniform.value;
  27847. }
  27848. }
  27849. }
  27850. if ( json.defines !== undefined ) this.defines = json.defines;
  27851. if ( json.vertexShader !== undefined ) this.vertexShader = json.vertexShader;
  27852. if ( json.fragmentShader !== undefined ) this.fragmentShader = json.fragmentShader;
  27853. if ( json.glslVersion !== undefined ) this.glslVersion = json.glslVersion;
  27854. if ( json.extensions !== undefined ) {
  27855. for ( const key in json.extensions ) {
  27856. this.extensions[ key ] = json.extensions[ key ];
  27857. }
  27858. }
  27859. if ( json.lights !== undefined ) this.lights = json.lights;
  27860. if ( json.clipping !== undefined ) this.clipping = json.clipping;
  27861. return this;
  27862. }
  27863. }
  27864. /**
  27865. * This class works just like {@link ShaderMaterial}, except that definitions
  27866. * of built-in uniforms and attributes are not automatically prepended to the
  27867. * GLSL shader code.
  27868. *
  27869. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27870. *
  27871. * @augments ShaderMaterial
  27872. */
  27873. class RawShaderMaterial extends ShaderMaterial {
  27874. /**
  27875. * Constructs a new raw shader material.
  27876. *
  27877. * @param {Object} [parameters] - An object with one or more properties
  27878. * defining the material's appearance. Any property of the material
  27879. * (including any property from inherited materials) can be passed
  27880. * in here. Color values can be passed any type of value accepted
  27881. * by {@link Color#set}.
  27882. */
  27883. constructor( parameters ) {
  27884. super( parameters );
  27885. /**
  27886. * This flag can be used for type testing.
  27887. *
  27888. * @type {boolean}
  27889. * @readonly
  27890. * @default true
  27891. */
  27892. this.isRawShaderMaterial = true;
  27893. this.type = 'RawShaderMaterial';
  27894. }
  27895. }
  27896. /**
  27897. * A standard physically based material, using Metallic-Roughness workflow.
  27898. *
  27899. * Physically based rendering (PBR) has recently become the standard in many
  27900. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27901. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27902. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27903. *
  27904. * This approach differs from older approaches in that instead of using
  27905. * approximations for the way in which light interacts with a surface, a
  27906. * physically correct model is used. The idea is that, instead of tweaking
  27907. * materials to look good under specific lighting, a material can be created
  27908. * that will react 'correctly' under all lighting scenarios.
  27909. *
  27910. * In practice this gives a more accurate and realistic looking result than
  27911. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27912. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27913. * shading.
  27914. *
  27915. * Note that for best results you should always specify an environment map when using this material.
  27916. *
  27917. * For a non-technical introduction to the concept of PBR and how to set up a
  27918. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27919. *
  27920. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27921. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27922. *
  27923. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27924. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27925. * (pdf), by Brent Burley.
  27926. *
  27927. * @augments Material
  27928. * @demo scenes/material-browser.html#MeshStandardMaterial
  27929. */
  27930. class MeshStandardMaterial extends Material {
  27931. /**
  27932. * Constructs a new mesh standard material.
  27933. *
  27934. * @param {Object} [parameters] - An object with one or more properties
  27935. * defining the material's appearance. Any property of the material
  27936. * (including any property from inherited materials) can be passed
  27937. * in here. Color values can be passed any type of value accepted
  27938. * by {@link Color#set}.
  27939. */
  27940. constructor( parameters ) {
  27941. super();
  27942. /**
  27943. * This flag can be used for type testing.
  27944. *
  27945. * @type {boolean}
  27946. * @readonly
  27947. * @default true
  27948. */
  27949. this.isMeshStandardMaterial = true;
  27950. this.type = 'MeshStandardMaterial';
  27951. this.defines = { 'STANDARD': '' };
  27952. /**
  27953. * Color of the material.
  27954. *
  27955. * @type {Color}
  27956. * @default (1,1,1)
  27957. */
  27958. this.color = new Color( 0xffffff ); // diffuse
  27959. /**
  27960. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27961. * means fully diffuse. If `roughnessMap` is also provided,
  27962. * both values are multiplied.
  27963. *
  27964. * @type {number}
  27965. * @default 1
  27966. */
  27967. this.roughness = 1.0;
  27968. /**
  27969. * How much the material is like a metal. Non-metallic materials such as wood
  27970. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27971. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27972. * If `metalnessMap` is also provided, both values are multiplied.
  27973. *
  27974. * @type {number}
  27975. * @default 0
  27976. */
  27977. this.metalness = 0.0;
  27978. /**
  27979. * The color map. May optionally include an alpha channel, typically combined
  27980. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27981. * color is modulated by the diffuse `color`.
  27982. *
  27983. * `map` represents color data, and the texture must be assigned a
  27984. * {@link Texture#colorSpace}. Most `map` textures set
  27985. * `texture.colorSpace = SRGBColorSpace`.
  27986. *
  27987. * @type {?Texture}
  27988. * @default null
  27989. */
  27990. this.map = null;
  27991. /**
  27992. * The light map. Requires a second set of UVs.
  27993. *
  27994. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  27995. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  27996. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  27997. * such as `.exr` or `.hdr`.
  27998. *
  27999. * @type {?Texture}
  28000. * @default null
  28001. */
  28002. this.lightMap = null;
  28003. /**
  28004. * Intensity of the baked light.
  28005. *
  28006. * @type {number}
  28007. * @default 1
  28008. */
  28009. this.lightMapIntensity = 1.0;
  28010. /**
  28011. * The red channel of this texture is used as the ambient occlusion map.
  28012. * Requires a second set of UVs.
  28013. *
  28014. * `aoMap` represents non-color data. Any texture assigned must have
  28015. * `texture.colorSpace = NoColorSpace` (default).
  28016. *
  28017. * @type {?Texture}
  28018. * @default null
  28019. */
  28020. this.aoMap = null;
  28021. /**
  28022. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28023. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28024. * red channel is also `1`, ambient light is fully occluded on a surface.
  28025. *
  28026. * @type {number}
  28027. * @default 1
  28028. */
  28029. this.aoMapIntensity = 1.0;
  28030. /**
  28031. * Emissive (light) color of the material, essentially a solid color
  28032. * unaffected by other lighting.
  28033. *
  28034. * @type {Color}
  28035. * @default (0,0,0)
  28036. */
  28037. this.emissive = new Color( 0x000000 );
  28038. /**
  28039. * Intensity of the emissive light. Modulates the emissive color.
  28040. *
  28041. * @type {number}
  28042. * @default 1
  28043. */
  28044. this.emissiveIntensity = 1.0;
  28045. /**
  28046. * Set emissive (glow) map. The emissive map color is modulated by the
  28047. * emissive color and the emissive intensity. If you have an emissive map,
  28048. * be sure to set the emissive color to something other than black.
  28049. *
  28050. * `emissiveMap` represents color data, and the texture must be assigned a
  28051. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  28052. * `texture.colorSpace = SRGBColorSpace`.
  28053. *
  28054. * @type {?Texture}
  28055. * @default null
  28056. */
  28057. this.emissiveMap = null;
  28058. /**
  28059. * The texture to create a bump map. The black and white values map to the
  28060. * perceived depth in relation to the lights. Bump doesn't actually affect
  28061. * the geometry of the object, only the lighting. If a normal map is defined
  28062. * this will be ignored.
  28063. *
  28064. * `bumpMap` represents non-color data. Any texture assigned must have
  28065. * `texture.colorSpace = NoColorSpace` (default).
  28066. *
  28067. * @type {?Texture}
  28068. * @default null
  28069. */
  28070. this.bumpMap = null;
  28071. /**
  28072. * How much the bump map affects the material. Typical range is `[0,1]`.
  28073. *
  28074. * @type {number}
  28075. * @default 1
  28076. */
  28077. this.bumpScale = 1;
  28078. /**
  28079. * The texture to create a normal map. The RGB values affect the surface
  28080. * normal for each pixel fragment and change the way the color is lit. Normal
  28081. * maps do not change the actual shape of the surface, only the lighting. In
  28082. * case the material has a normal map authored using the left handed
  28083. * convention, the `y` component of `normalScale` should be negated to compensate
  28084. * for the different handedness.
  28085. *
  28086. * `normalMap` represents non-color data. Any texture assigned must have
  28087. * `texture.colorSpace = NoColorSpace` (default).
  28088. *
  28089. * @type {?Texture}
  28090. * @default null
  28091. */
  28092. this.normalMap = null;
  28093. /**
  28094. * The type of normal map.
  28095. *
  28096. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28097. * @default TangentSpaceNormalMap
  28098. */
  28099. this.normalMapType = TangentSpaceNormalMap;
  28100. /**
  28101. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28102. *
  28103. * @type {Vector2}
  28104. * @default (1,1)
  28105. */
  28106. this.normalScale = new Vector2( 1, 1 );
  28107. /**
  28108. * The displacement map affects the position of the mesh's vertices. Unlike
  28109. * other maps which only affect the light and shade of the material the
  28110. * displaced vertices can cast shadows, block other objects, and otherwise
  28111. * act as real geometry. The displacement texture is an image where the value
  28112. * of each pixel (white being the highest) is mapped against, and
  28113. * repositions, the vertices of the mesh. For best results, pair a
  28114. * displacement map with a matching normal map, since the renderer can
  28115. * not recompute surface normals from the displaced vertices.
  28116. *
  28117. * `displacementMap` represents non-color data. Any texture assigned must have
  28118. * `texture.colorSpace = NoColorSpace` (default).
  28119. *
  28120. * @type {?Texture}
  28121. * @default null
  28122. */
  28123. this.displacementMap = null;
  28124. /**
  28125. * How much the displacement map affects the mesh (where black is no
  28126. * displacement, and white is maximum displacement). Without a displacement
  28127. * map set, this value is not applied.
  28128. *
  28129. * @type {number}
  28130. * @default 0
  28131. */
  28132. this.displacementScale = 1;
  28133. /**
  28134. * The offset of the displacement map's values on the mesh's vertices.
  28135. * The bias is added to the scaled sample of the displacement map.
  28136. * Without a displacement map set, this value is not applied.
  28137. *
  28138. * @type {number}
  28139. * @default 0
  28140. */
  28141. this.displacementBias = 0;
  28142. /**
  28143. * The green channel of this texture is used to alter the roughness of the
  28144. * material.
  28145. *
  28146. * `roughnessMap` represents non-color data. Any texture assigned must have
  28147. * `texture.colorSpace = NoColorSpace` (default).
  28148. *
  28149. * @type {?Texture}
  28150. * @default null
  28151. */
  28152. this.roughnessMap = null;
  28153. /**
  28154. * The blue channel of this texture is used to alter the metalness of the
  28155. * material.
  28156. *
  28157. * `metalnessMap` represents non-color data. Any texture assigned must have
  28158. * `texture.colorSpace = NoColorSpace` (default).
  28159. *
  28160. * @type {?Texture}
  28161. * @default null
  28162. */
  28163. this.metalnessMap = null;
  28164. /**
  28165. * The alpha map is a grayscale texture that controls the opacity across the
  28166. * surface (black: fully transparent; white: fully opaque).
  28167. *
  28168. * Only the color of the texture is used, ignoring the alpha channel if one
  28169. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28170. * when sampling this texture due to the extra bit of precision provided for
  28171. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28172. * luminance/alpha textures will also still work as expected.
  28173. *
  28174. * `alphaMap` represents non-color data. Any texture assigned must have
  28175. * `texture.colorSpace = NoColorSpace` (default).
  28176. *
  28177. * @type {?Texture}
  28178. * @default null
  28179. */
  28180. this.alphaMap = null;
  28181. /**
  28182. * The environment map. To ensure a physically correct rendering, environment maps
  28183. * are internally pre-processed with {@link PMREMGenerator}.
  28184. *
  28185. * `envMap` represents luminance data, and the texture must be assigned
  28186. * a {@link Texture#colorSpace}. Most `envMap` textures set
  28187. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  28188. * such as `.exr` or `.hdr`.
  28189. *
  28190. * @type {?Texture}
  28191. * @default null
  28192. */
  28193. this.envMap = null;
  28194. /**
  28195. * The rotation of the environment map in radians.
  28196. *
  28197. * @type {Euler}
  28198. * @default (0,0,0)
  28199. */
  28200. this.envMapRotation = new Euler();
  28201. /**
  28202. * Scales the effect of the environment map by multiplying its color.
  28203. *
  28204. * @type {number}
  28205. * @default 1
  28206. */
  28207. this.envMapIntensity = 1.0;
  28208. /**
  28209. * Renders the geometry as a wireframe.
  28210. *
  28211. * @type {boolean}
  28212. * @default false
  28213. */
  28214. this.wireframe = false;
  28215. /**
  28216. * Controls the thickness of the wireframe.
  28217. *
  28218. * Can only be used with {@link SVGRenderer}.
  28219. *
  28220. * @type {number}
  28221. * @default 1
  28222. */
  28223. this.wireframeLinewidth = 1;
  28224. /**
  28225. * Defines appearance of wireframe ends.
  28226. *
  28227. * Can only be used with {@link SVGRenderer}.
  28228. *
  28229. * @type {('round'|'bevel'|'miter')}
  28230. * @default 'round'
  28231. */
  28232. this.wireframeLinecap = 'round';
  28233. /**
  28234. * Defines appearance of wireframe joints.
  28235. *
  28236. * Can only be used with {@link SVGRenderer}.
  28237. *
  28238. * @type {('round'|'bevel'|'miter')}
  28239. * @default 'round'
  28240. */
  28241. this.wireframeLinejoin = 'round';
  28242. /**
  28243. * Whether the material is rendered with flat shading or not.
  28244. *
  28245. * @type {boolean}
  28246. * @default false
  28247. */
  28248. this.flatShading = false;
  28249. /**
  28250. * Whether the material is affected by fog or not.
  28251. *
  28252. * @type {boolean}
  28253. * @default true
  28254. */
  28255. this.fog = true;
  28256. this.setValues( parameters );
  28257. }
  28258. copy( source ) {
  28259. super.copy( source );
  28260. this.defines = { 'STANDARD': '' };
  28261. this.color.copy( source.color );
  28262. this.roughness = source.roughness;
  28263. this.metalness = source.metalness;
  28264. this.map = source.map;
  28265. this.lightMap = source.lightMap;
  28266. this.lightMapIntensity = source.lightMapIntensity;
  28267. this.aoMap = source.aoMap;
  28268. this.aoMapIntensity = source.aoMapIntensity;
  28269. this.emissive.copy( source.emissive );
  28270. this.emissiveMap = source.emissiveMap;
  28271. this.emissiveIntensity = source.emissiveIntensity;
  28272. this.bumpMap = source.bumpMap;
  28273. this.bumpScale = source.bumpScale;
  28274. this.normalMap = source.normalMap;
  28275. this.normalMapType = source.normalMapType;
  28276. this.normalScale.copy( source.normalScale );
  28277. this.displacementMap = source.displacementMap;
  28278. this.displacementScale = source.displacementScale;
  28279. this.displacementBias = source.displacementBias;
  28280. this.roughnessMap = source.roughnessMap;
  28281. this.metalnessMap = source.metalnessMap;
  28282. this.alphaMap = source.alphaMap;
  28283. this.envMap = source.envMap;
  28284. this.envMapRotation.copy( source.envMapRotation );
  28285. this.envMapIntensity = source.envMapIntensity;
  28286. this.wireframe = source.wireframe;
  28287. this.wireframeLinewidth = source.wireframeLinewidth;
  28288. this.wireframeLinecap = source.wireframeLinecap;
  28289. this.wireframeLinejoin = source.wireframeLinejoin;
  28290. this.flatShading = source.flatShading;
  28291. this.fog = source.fog;
  28292. return this;
  28293. }
  28294. }
  28295. /**
  28296. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28297. * physically-based rendering properties:
  28298. *
  28299. * - Anisotropy: Ability to represent the anisotropic property of materials
  28300. * as observable with brushed metals.
  28301. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28302. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28303. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28304. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28305. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28306. * wings of many insects.
  28307. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28308. * transparent materials are less reflective. Physically-based transmission provides a more
  28309. * realistic option for thin, transparent surfaces like glass.
  28310. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28311. * - Sheen: Can be used for representing cloth and fabric materials.
  28312. *
  28313. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28314. * higher performance cost, per pixel, than other three.js materials. Most
  28315. * effects are disabled by default, and add cost as they are enabled. For
  28316. * best results, always specify an environment map when using this material.
  28317. *
  28318. * @augments MeshStandardMaterial
  28319. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28320. */
  28321. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28322. /**
  28323. * Constructs a new mesh physical material.
  28324. *
  28325. * @param {Object} [parameters] - An object with one or more properties
  28326. * defining the material's appearance. Any property of the material
  28327. * (including any property from inherited materials) can be passed
  28328. * in here. Color values can be passed any type of value accepted
  28329. * by {@link Color#set}.
  28330. */
  28331. constructor( parameters ) {
  28332. super();
  28333. /**
  28334. * This flag can be used for type testing.
  28335. *
  28336. * @type {boolean}
  28337. * @readonly
  28338. * @default true
  28339. */
  28340. this.isMeshPhysicalMaterial = true;
  28341. this.defines = {
  28342. 'STANDARD': '',
  28343. 'PHYSICAL': ''
  28344. };
  28345. this.type = 'MeshPhysicalMaterial';
  28346. /**
  28347. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28348. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28349. * property provides additional rotation to the vectors in the texture.
  28350. *
  28351. * @type {number}
  28352. * @default 1
  28353. */
  28354. this.anisotropyRotation = 0;
  28355. /**
  28356. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28357. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28358. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28359. *
  28360. * `anisotropyMap` represents non-color data. Any texture assigned must have
  28361. * `texture.colorSpace = NoColorSpace` (default).
  28362. *
  28363. * @type {?Texture}
  28364. * @default null
  28365. */
  28366. this.anisotropyMap = null;
  28367. /**
  28368. * The red channel of this texture is multiplied against `clearcoat`,
  28369. * for per-pixel control over a coating's intensity.
  28370. *
  28371. * `clearcoatMap` represents non-color data. Any texture assigned must have
  28372. * `texture.colorSpace = NoColorSpace` (default).
  28373. *
  28374. * @type {?Texture}
  28375. * @default null
  28376. */
  28377. this.clearcoatMap = null;
  28378. /**
  28379. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28380. *
  28381. * @type {number}
  28382. * @default 0
  28383. */
  28384. this.clearcoatRoughness = 0.0;
  28385. /**
  28386. * The green channel of this texture is multiplied against
  28387. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28388. *
  28389. * `clearcoatRoughnessMap` represents non-color data. Any texture assigned must have
  28390. * `texture.colorSpace = NoColorSpace` (default).
  28391. *
  28392. * @type {?Texture}
  28393. * @default null
  28394. */
  28395. this.clearcoatRoughnessMap = null;
  28396. /**
  28397. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28398. * `(0,0)` to `(1,1)`.
  28399. *
  28400. * @type {Vector2}
  28401. * @default (1,1)
  28402. */
  28403. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28404. /**
  28405. * Can be used to enable independent normals for the clear coat layer.
  28406. *
  28407. * `clearcoatNormalMap` represents non-color data. Any texture assigned must have
  28408. * `texture.colorSpace = NoColorSpace` (default).
  28409. *
  28410. * @type {?Texture}
  28411. * @default null
  28412. */
  28413. this.clearcoatNormalMap = null;
  28414. /**
  28415. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28416. *
  28417. * @type {number}
  28418. * @default 1.5
  28419. */
  28420. this.ior = 1.5;
  28421. /**
  28422. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28423. * corresponds to an index-of-refraction of `1.5`.
  28424. *
  28425. * This models the reflectivity of non-metallic materials. It has no effect
  28426. * when `metalness` is `1.0`
  28427. *
  28428. * @name MeshPhysicalMaterial#reflectivity
  28429. * @type {number}
  28430. * @default 0.5
  28431. */
  28432. Object.defineProperty( this, 'reflectivity', {
  28433. get: function () {
  28434. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28435. },
  28436. set: function ( reflectivity ) {
  28437. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28438. }
  28439. } );
  28440. /**
  28441. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28442. * control over iridescence.
  28443. *
  28444. * `iridescenceMap` represents non-color data. Any texture assigned must have
  28445. * `texture.colorSpace = NoColorSpace` (default).
  28446. *
  28447. * @type {?Texture}
  28448. * @default null
  28449. */
  28450. this.iridescenceMap = null;
  28451. /**
  28452. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28453. * Between `1.0` to `2.333`.
  28454. *
  28455. * @type {number}
  28456. * @default 1.3
  28457. */
  28458. this.iridescenceIOR = 1.3;
  28459. /**
  28460. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28461. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28462. *
  28463. * @type {Array<number,number>}
  28464. * @default [100,400]
  28465. */
  28466. this.iridescenceThicknessRange = [ 100, 400 ];
  28467. /**
  28468. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28469. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28470. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28471. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28472. * - Values in-between will linearly interpolate between the elements of the array.
  28473. *
  28474. * `iridescenceThicknessMap` represents non-color data. Any texture assigned must have
  28475. * `texture.colorSpace = NoColorSpace` (default).
  28476. *
  28477. * @type {?Texture}
  28478. * @default null
  28479. */
  28480. this.iridescenceThicknessMap = null;
  28481. /**
  28482. * The sheen tint.
  28483. *
  28484. * @type {Color}
  28485. * @default (0,0,0)
  28486. */
  28487. this.sheenColor = new Color( 0x000000 );
  28488. /**
  28489. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28490. * over sheen tint.
  28491. *
  28492. * `sheenColorMap` represents color data, and the texture must be assigned a
  28493. * {@link Texture#colorSpace}. Most `sheenColorMap` textures set
  28494. * `texture.colorSpace = SRGBColorSpace`.
  28495. *
  28496. * @type {?Texture}
  28497. * @default null
  28498. */
  28499. this.sheenColorMap = null;
  28500. /**
  28501. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28502. *
  28503. * @type {number}
  28504. * @default 1
  28505. */
  28506. this.sheenRoughness = 1.0;
  28507. /**
  28508. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28509. * over sheen roughness.
  28510. *
  28511. * `sheenRoughnessMap` represents non-color data. Any texture assigned must have
  28512. * `texture.colorSpace = NoColorSpace` (default).
  28513. *
  28514. * @type {?Texture}
  28515. * @default null
  28516. */
  28517. this.sheenRoughnessMap = null;
  28518. /**
  28519. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28520. * optical transparency.
  28521. *
  28522. * `transmissionMap` represents non-color data. Any texture assigned must have
  28523. * `texture.colorSpace = NoColorSpace` (default).
  28524. *
  28525. * @type {?Texture}
  28526. * @default null
  28527. */
  28528. this.transmissionMap = null;
  28529. /**
  28530. * The thickness of the volume beneath the surface. The value is given in the
  28531. * coordinate space of the mesh. If the value is `0` the material is
  28532. * thin-walled. Otherwise the material is a volume boundary.
  28533. *
  28534. * @type {number}
  28535. * @default 0
  28536. */
  28537. this.thickness = 0;
  28538. /**
  28539. * A texture that defines the thickness, stored in the green channel. This will
  28540. * be multiplied by `thickness`.
  28541. *
  28542. * `thicknessMap` represents non-color data. Any texture assigned must have
  28543. * `texture.colorSpace = NoColorSpace` (default).
  28544. *
  28545. * @type {?Texture}
  28546. * @default null
  28547. */
  28548. this.thicknessMap = null;
  28549. /**
  28550. * Density of the medium given as the average distance that light travels in
  28551. * the medium before interacting with a particle. The value is given in world
  28552. * space units, and must be greater than zero.
  28553. *
  28554. * @type {number}
  28555. * @default Infinity
  28556. */
  28557. this.attenuationDistance = Infinity;
  28558. /**
  28559. * The color that white light turns into due to absorption when reaching the
  28560. * attenuation distance.
  28561. *
  28562. * @type {Color}
  28563. * @default (1,1,1)
  28564. */
  28565. this.attenuationColor = new Color( 1, 1, 1 );
  28566. /**
  28567. * A float that scales the amount of specular reflection for non-metals only.
  28568. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28569. *
  28570. * @type {number}
  28571. * @default 1
  28572. */
  28573. this.specularIntensity = 1.0;
  28574. /**
  28575. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28576. * for per-pixel control over specular intensity.
  28577. *
  28578. * `specularIntensityMap` represents non-color data. Any texture assigned must have
  28579. * `texture.colorSpace = NoColorSpace` (default).
  28580. *
  28581. * @type {?Texture}
  28582. * @default null
  28583. */
  28584. this.specularIntensityMap = null;
  28585. /**
  28586. * Tints the specular reflection at normal incidence for non-metals only.
  28587. *
  28588. * @type {Color}
  28589. * @default (1,1,1)
  28590. */
  28591. this.specularColor = new Color( 1, 1, 1 );
  28592. /**
  28593. * The RGB channels of this texture are multiplied against `specularColor`,
  28594. * for per-pixel control over specular color.
  28595. *
  28596. * `specularColorMap` represents color data, and the texture must be assigned a
  28597. * {@link Texture#colorSpace}. Most `specularColorMap` textures set
  28598. * `texture.colorSpace = SRGBColorSpace`.
  28599. *
  28600. * @type {?Texture}
  28601. * @default null
  28602. */
  28603. this.specularColorMap = null;
  28604. this._anisotropy = 0;
  28605. this._clearcoat = 0;
  28606. this._dispersion = 0;
  28607. this._iridescence = 0;
  28608. this._sheen = 0.0;
  28609. this._transmission = 0;
  28610. this.setValues( parameters );
  28611. }
  28612. /**
  28613. * The anisotropy strength, from `0.0` to `1.0`.
  28614. *
  28615. * @type {number}
  28616. * @default 0
  28617. */
  28618. get anisotropy() {
  28619. return this._anisotropy;
  28620. }
  28621. set anisotropy( value ) {
  28622. if ( this._anisotropy > 0 !== value > 0 ) {
  28623. this.version ++;
  28624. }
  28625. this._anisotropy = value;
  28626. }
  28627. /**
  28628. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28629. * clear coat related properties to enable multilayer materials that have a
  28630. * thin translucent layer over the base layer.
  28631. *
  28632. * @type {number}
  28633. * @default 0
  28634. */
  28635. get clearcoat() {
  28636. return this._clearcoat;
  28637. }
  28638. set clearcoat( value ) {
  28639. if ( this._clearcoat > 0 !== value > 0 ) {
  28640. this.version ++;
  28641. }
  28642. this._clearcoat = value;
  28643. }
  28644. /**
  28645. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28646. * the surface and the viewer, from `0.0` to `1.0`.
  28647. *
  28648. * @type {number}
  28649. * @default 0
  28650. */
  28651. get iridescence() {
  28652. return this._iridescence;
  28653. }
  28654. set iridescence( value ) {
  28655. if ( this._iridescence > 0 !== value > 0 ) {
  28656. this.version ++;
  28657. }
  28658. this._iridescence = value;
  28659. }
  28660. /**
  28661. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28662. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28663. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28664. *
  28665. * @type {number}
  28666. * @default 0
  28667. */
  28668. get dispersion() {
  28669. return this._dispersion;
  28670. }
  28671. set dispersion( value ) {
  28672. if ( this._dispersion > 0 !== value > 0 ) {
  28673. this.version ++;
  28674. }
  28675. this._dispersion = value;
  28676. }
  28677. /**
  28678. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28679. *
  28680. * @type {number}
  28681. * @default 0
  28682. */
  28683. get sheen() {
  28684. return this._sheen;
  28685. }
  28686. set sheen( value ) {
  28687. if ( this._sheen > 0 !== value > 0 ) {
  28688. this.version ++;
  28689. }
  28690. this._sheen = value;
  28691. }
  28692. /**
  28693. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28694. *
  28695. * Thin, transparent or semitransparent, plastic or glass materials remain
  28696. * largely reflective even if they are fully transmissive. The transmission
  28697. * property can be used to model these materials.
  28698. *
  28699. * When transmission is non-zero, `opacity` should be set to `1`.
  28700. *
  28701. * @type {number}
  28702. * @default 0
  28703. */
  28704. get transmission() {
  28705. return this._transmission;
  28706. }
  28707. set transmission( value ) {
  28708. if ( this._transmission > 0 !== value > 0 ) {
  28709. this.version ++;
  28710. }
  28711. this._transmission = value;
  28712. }
  28713. copy( source ) {
  28714. super.copy( source );
  28715. this.defines = {
  28716. 'STANDARD': '',
  28717. 'PHYSICAL': ''
  28718. };
  28719. this.anisotropy = source.anisotropy;
  28720. this.anisotropyRotation = source.anisotropyRotation;
  28721. this.anisotropyMap = source.anisotropyMap;
  28722. this.clearcoat = source.clearcoat;
  28723. this.clearcoatMap = source.clearcoatMap;
  28724. this.clearcoatRoughness = source.clearcoatRoughness;
  28725. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28726. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28727. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28728. this.dispersion = source.dispersion;
  28729. this.ior = source.ior;
  28730. this.iridescence = source.iridescence;
  28731. this.iridescenceMap = source.iridescenceMap;
  28732. this.iridescenceIOR = source.iridescenceIOR;
  28733. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28734. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28735. this.sheen = source.sheen;
  28736. this.sheenColor.copy( source.sheenColor );
  28737. this.sheenColorMap = source.sheenColorMap;
  28738. this.sheenRoughness = source.sheenRoughness;
  28739. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28740. this.transmission = source.transmission;
  28741. this.transmissionMap = source.transmissionMap;
  28742. this.thickness = source.thickness;
  28743. this.thicknessMap = source.thicknessMap;
  28744. this.attenuationDistance = source.attenuationDistance;
  28745. this.attenuationColor.copy( source.attenuationColor );
  28746. this.specularIntensity = source.specularIntensity;
  28747. this.specularIntensityMap = source.specularIntensityMap;
  28748. this.specularColor.copy( source.specularColor );
  28749. this.specularColorMap = source.specularColorMap;
  28750. return this;
  28751. }
  28752. }
  28753. /**
  28754. * A material for shiny surfaces with specular highlights.
  28755. *
  28756. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28757. * model for calculating reflectance. Unlike the Lambertian model used in the
  28758. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28759. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28760. *
  28761. * Performance will generally be greater when using this material over the
  28762. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28763. * some graphical accuracy.
  28764. *
  28765. * @augments Material
  28766. * @demo scenes/material-browser.html#MeshPhongMaterial
  28767. */
  28768. class MeshPhongMaterial extends Material {
  28769. /**
  28770. * Constructs a new mesh phong material.
  28771. *
  28772. * @param {Object} [parameters] - An object with one or more properties
  28773. * defining the material's appearance. Any property of the material
  28774. * (including any property from inherited materials) can be passed
  28775. * in here. Color values can be passed any type of value accepted
  28776. * by {@link Color#set}.
  28777. */
  28778. constructor( parameters ) {
  28779. super();
  28780. /**
  28781. * This flag can be used for type testing.
  28782. *
  28783. * @type {boolean}
  28784. * @readonly
  28785. * @default true
  28786. */
  28787. this.isMeshPhongMaterial = true;
  28788. this.type = 'MeshPhongMaterial';
  28789. /**
  28790. * Color of the material.
  28791. *
  28792. * @type {Color}
  28793. * @default (1,1,1)
  28794. */
  28795. this.color = new Color( 0xffffff ); // diffuse
  28796. /**
  28797. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28798. *
  28799. * This defines how shiny the material is and the color of its shine.
  28800. *
  28801. * @type {Color}
  28802. */
  28803. this.specular = new Color( 0x111111 );
  28804. /**
  28805. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28806. *
  28807. * @type {number}
  28808. * @default 30
  28809. */
  28810. this.shininess = 30;
  28811. /**
  28812. * The color map. May optionally include an alpha channel, typically combined
  28813. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28814. * color is modulated by the diffuse `color`.
  28815. *
  28816. * `map` represents color data, and the texture must be assigned a
  28817. * {@link Texture#colorSpace}. Most `map` textures set
  28818. * `texture.colorSpace = SRGBColorSpace`.
  28819. *
  28820. * @type {?Texture}
  28821. * @default null
  28822. */
  28823. this.map = null;
  28824. /**
  28825. * The light map. Requires a second set of UVs.
  28826. *
  28827. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  28828. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  28829. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  28830. * such as `.exr` or `.hdr`.
  28831. *
  28832. * @type {?Texture}
  28833. * @default null
  28834. */
  28835. this.lightMap = null;
  28836. /**
  28837. * Intensity of the baked light.
  28838. *
  28839. * @type {number}
  28840. * @default 1
  28841. */
  28842. this.lightMapIntensity = 1.0;
  28843. /**
  28844. * The red channel of this texture is used as the ambient occlusion map.
  28845. * Requires a second set of UVs.
  28846. *
  28847. * `aoMap` represents non-color data. Any texture assigned must have
  28848. * `texture.colorSpace = NoColorSpace` (default).
  28849. *
  28850. * @type {?Texture}
  28851. * @default null
  28852. */
  28853. this.aoMap = null;
  28854. /**
  28855. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28856. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28857. * red channel is also `1`, ambient light is fully occluded on a surface.
  28858. *
  28859. * @type {number}
  28860. * @default 1
  28861. */
  28862. this.aoMapIntensity = 1.0;
  28863. /**
  28864. * Emissive (light) color of the material, essentially a solid color
  28865. * unaffected by other lighting.
  28866. *
  28867. * @type {Color}
  28868. * @default (0,0,0)
  28869. */
  28870. this.emissive = new Color( 0x000000 );
  28871. /**
  28872. * Intensity of the emissive light. Modulates the emissive color.
  28873. *
  28874. * @type {number}
  28875. * @default 1
  28876. */
  28877. this.emissiveIntensity = 1.0;
  28878. /**
  28879. * Set emissive (glow) map. The emissive map color is modulated by the
  28880. * emissive color and the emissive intensity. If you have an emissive map,
  28881. * be sure to set the emissive color to something other than black.
  28882. *
  28883. * `emissiveMap` represents color data, and the texture must be assigned a
  28884. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  28885. * `texture.colorSpace = SRGBColorSpace`.
  28886. *
  28887. * @type {?Texture}
  28888. * @default null
  28889. */
  28890. this.emissiveMap = null;
  28891. /**
  28892. * The texture to create a bump map. The black and white values map to the
  28893. * perceived depth in relation to the lights. Bump doesn't actually affect
  28894. * the geometry of the object, only the lighting. If a normal map is defined
  28895. * this will be ignored.
  28896. *
  28897. * `bumpMap` represents non-color data. Any texture assigned must have
  28898. * `texture.colorSpace = NoColorSpace` (default).
  28899. *
  28900. * @type {?Texture}
  28901. * @default null
  28902. */
  28903. this.bumpMap = null;
  28904. /**
  28905. * How much the bump map affects the material. Typical range is `[0,1]`.
  28906. *
  28907. * @type {number}
  28908. * @default 1
  28909. */
  28910. this.bumpScale = 1;
  28911. /**
  28912. * The texture to create a normal map. The RGB values affect the surface
  28913. * normal for each pixel fragment and change the way the color is lit. Normal
  28914. * maps do not change the actual shape of the surface, only the lighting. In
  28915. * case the material has a normal map authored using the left handed
  28916. * convention, the `y` component of `normalScale` should be negated to compensate
  28917. * for the different handedness.
  28918. *
  28919. * `normalMap` represents non-color data. Any texture assigned must have
  28920. * `texture.colorSpace = NoColorSpace` (default).
  28921. *
  28922. * @type {?Texture}
  28923. * @default null
  28924. */
  28925. this.normalMap = null;
  28926. /**
  28927. * The type of normal map.
  28928. *
  28929. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28930. * @default TangentSpaceNormalMap
  28931. */
  28932. this.normalMapType = TangentSpaceNormalMap;
  28933. /**
  28934. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28935. *
  28936. * @type {Vector2}
  28937. * @default (1,1)
  28938. */
  28939. this.normalScale = new Vector2( 1, 1 );
  28940. /**
  28941. * The displacement map affects the position of the mesh's vertices. Unlike
  28942. * other maps which only affect the light and shade of the material the
  28943. * displaced vertices can cast shadows, block other objects, and otherwise
  28944. * act as real geometry. The displacement texture is an image where the value
  28945. * of each pixel (white being the highest) is mapped against, and
  28946. * repositions, the vertices of the mesh. For best results, pair a
  28947. * displacement map with a matching normal map, since the renderer can
  28948. * not recompute surface normals from the displaced vertices.
  28949. *
  28950. * `displacementMap` represents non-color data. Any texture assigned must have
  28951. * `texture.colorSpace = NoColorSpace` (default).
  28952. *
  28953. * @type {?Texture}
  28954. * @default null
  28955. */
  28956. this.displacementMap = null;
  28957. /**
  28958. * How much the displacement map affects the mesh (where black is no
  28959. * displacement, and white is maximum displacement). Without a displacement
  28960. * map set, this value is not applied.
  28961. *
  28962. * @type {number}
  28963. * @default 0
  28964. */
  28965. this.displacementScale = 1;
  28966. /**
  28967. * The offset of the displacement map's values on the mesh's vertices.
  28968. * The bias is added to the scaled sample of the displacement map.
  28969. * Without a displacement map set, this value is not applied.
  28970. *
  28971. * @type {number}
  28972. * @default 0
  28973. */
  28974. this.displacementBias = 0;
  28975. /**
  28976. * The specular map value affects both how much the specular surface
  28977. * highlight contributes and how much of the environment map affects the
  28978. * surface.
  28979. *
  28980. * `specularMap` represents color data, and the texture must be assigned a
  28981. * {@link Texture#colorSpace}. Most `specularMap` textures set
  28982. * `texture.colorSpace = SRGBColorSpace`.
  28983. *
  28984. * @type {?Texture}
  28985. * @default null
  28986. */
  28987. this.specularMap = null;
  28988. /**
  28989. * The alpha map is a grayscale texture that controls the opacity across the
  28990. * surface (black: fully transparent; white: fully opaque).
  28991. *
  28992. * Only the color of the texture is used, ignoring the alpha channel if one
  28993. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28994. * when sampling this texture due to the extra bit of precision provided for
  28995. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28996. * luminance/alpha textures will also still work as expected.
  28997. *
  28998. * `alphaMap` represents non-color data. Any texture assigned must have
  28999. * `texture.colorSpace = NoColorSpace` (default).
  29000. *
  29001. * @type {?Texture}
  29002. * @default null
  29003. */
  29004. this.alphaMap = null;
  29005. /**
  29006. * The environment map.
  29007. *
  29008. * `envMap` represents luminance data, and the texture must be assigned
  29009. * a {@link Texture#colorSpace}. Most `envMap` textures set
  29010. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29011. * such as `.exr` or `.hdr`.
  29012. *
  29013. * @type {?Texture}
  29014. * @default null
  29015. */
  29016. this.envMap = null;
  29017. /**
  29018. * The rotation of the environment map in radians.
  29019. *
  29020. * @type {Euler}
  29021. * @default (0,0,0)
  29022. */
  29023. this.envMapRotation = new Euler();
  29024. /**
  29025. * How to combine the result of the surface's color with the environment map, if any.
  29026. *
  29027. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29028. * blend between the two colors.
  29029. *
  29030. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29031. * @default MultiplyOperation
  29032. */
  29033. this.combine = MultiplyOperation;
  29034. /**
  29035. * How much the environment map affects the surface.
  29036. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29037. *
  29038. * @type {number}
  29039. * @default 1
  29040. */
  29041. this.reflectivity = 1;
  29042. /**
  29043. * Scales the effect of the environment map by multiplying its color.
  29044. *
  29045. * @type {number}
  29046. * @default 1
  29047. */
  29048. this.envMapIntensity = 1.0;
  29049. /**
  29050. * The index of refraction (IOR) of air (approximately 1) divided by the
  29051. * index of refraction of the material. It is used with environment mapping
  29052. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29053. * The refraction ratio should not exceed `1`.
  29054. *
  29055. * @type {number}
  29056. * @default 0.98
  29057. */
  29058. this.refractionRatio = 0.98;
  29059. /**
  29060. * Renders the geometry as a wireframe.
  29061. *
  29062. * @type {boolean}
  29063. * @default false
  29064. */
  29065. this.wireframe = false;
  29066. /**
  29067. * Controls the thickness of the wireframe.
  29068. *
  29069. * Can only be used with {@link SVGRenderer}.
  29070. *
  29071. * @type {number}
  29072. * @default 1
  29073. */
  29074. this.wireframeLinewidth = 1;
  29075. /**
  29076. * Defines appearance of wireframe ends.
  29077. *
  29078. * Can only be used with {@link SVGRenderer}.
  29079. *
  29080. * @type {('round'|'bevel'|'miter')}
  29081. * @default 'round'
  29082. */
  29083. this.wireframeLinecap = 'round';
  29084. /**
  29085. * Defines appearance of wireframe joints.
  29086. *
  29087. * Can only be used with {@link SVGRenderer}.
  29088. *
  29089. * @type {('round'|'bevel'|'miter')}
  29090. * @default 'round'
  29091. */
  29092. this.wireframeLinejoin = 'round';
  29093. /**
  29094. * Whether the material is rendered with flat shading or not.
  29095. *
  29096. * @type {boolean}
  29097. * @default false
  29098. */
  29099. this.flatShading = false;
  29100. /**
  29101. * Whether the material is affected by fog or not.
  29102. *
  29103. * @type {boolean}
  29104. * @default true
  29105. */
  29106. this.fog = true;
  29107. this.setValues( parameters );
  29108. }
  29109. copy( source ) {
  29110. super.copy( source );
  29111. this.color.copy( source.color );
  29112. this.specular.copy( source.specular );
  29113. this.shininess = source.shininess;
  29114. this.map = source.map;
  29115. this.lightMap = source.lightMap;
  29116. this.lightMapIntensity = source.lightMapIntensity;
  29117. this.aoMap = source.aoMap;
  29118. this.aoMapIntensity = source.aoMapIntensity;
  29119. this.emissive.copy( source.emissive );
  29120. this.emissiveMap = source.emissiveMap;
  29121. this.emissiveIntensity = source.emissiveIntensity;
  29122. this.bumpMap = source.bumpMap;
  29123. this.bumpScale = source.bumpScale;
  29124. this.normalMap = source.normalMap;
  29125. this.normalMapType = source.normalMapType;
  29126. this.normalScale.copy( source.normalScale );
  29127. this.displacementMap = source.displacementMap;
  29128. this.displacementScale = source.displacementScale;
  29129. this.displacementBias = source.displacementBias;
  29130. this.specularMap = source.specularMap;
  29131. this.alphaMap = source.alphaMap;
  29132. this.envMap = source.envMap;
  29133. this.envMapRotation.copy( source.envMapRotation );
  29134. this.combine = source.combine;
  29135. this.reflectivity = source.reflectivity;
  29136. this.envMapIntensity = source.envMapIntensity;
  29137. this.refractionRatio = source.refractionRatio;
  29138. this.wireframe = source.wireframe;
  29139. this.wireframeLinewidth = source.wireframeLinewidth;
  29140. this.wireframeLinecap = source.wireframeLinecap;
  29141. this.wireframeLinejoin = source.wireframeLinejoin;
  29142. this.flatShading = source.flatShading;
  29143. this.fog = source.fog;
  29144. return this;
  29145. }
  29146. }
  29147. /**
  29148. * A material implementing toon shading.
  29149. *
  29150. * @augments Material
  29151. * @demo scenes/material-browser.html#MeshToonMaterial
  29152. */
  29153. class MeshToonMaterial extends Material {
  29154. /**
  29155. * Constructs a new mesh toon material.
  29156. *
  29157. * @param {Object} [parameters] - An object with one or more properties
  29158. * defining the material's appearance. Any property of the material
  29159. * (including any property from inherited materials) can be passed
  29160. * in here. Color values can be passed any type of value accepted
  29161. * by {@link Color#set}.
  29162. */
  29163. constructor( parameters ) {
  29164. super();
  29165. /**
  29166. * This flag can be used for type testing.
  29167. *
  29168. * @type {boolean}
  29169. * @readonly
  29170. * @default true
  29171. */
  29172. this.isMeshToonMaterial = true;
  29173. this.defines = { 'TOON': '' };
  29174. this.type = 'MeshToonMaterial';
  29175. /**
  29176. * Color of the material.
  29177. *
  29178. * @type {Color}
  29179. * @default (1,1,1)
  29180. */
  29181. this.color = new Color( 0xffffff );
  29182. /**
  29183. * The color map. May optionally include an alpha channel, typically combined
  29184. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29185. * color is modulated by the diffuse `color`.
  29186. *
  29187. * `map` represents color data, and the texture must be assigned a
  29188. * {@link Texture#colorSpace}. Most `map` textures set
  29189. * `texture.colorSpace = SRGBColorSpace`.
  29190. *
  29191. * @type {?Texture}
  29192. * @default null
  29193. */
  29194. this.map = null;
  29195. /**
  29196. * Gradient map for toon shading. It's required to set
  29197. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@link NearestFilter}
  29198. * when using this type of texture.
  29199. *
  29200. * `gradientMap` represents non-color data. Any texture assigned must have
  29201. * `texture.colorSpace = NoColorSpace` (default).
  29202. *
  29203. * @type {?Texture}
  29204. * @default null
  29205. */
  29206. this.gradientMap = null;
  29207. /**
  29208. * The light map. Requires a second set of UVs.
  29209. *
  29210. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  29211. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  29212. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29213. * such as `.exr` or `.hdr`.
  29214. *
  29215. * @type {?Texture}
  29216. * @default null
  29217. */
  29218. this.lightMap = null;
  29219. /**
  29220. * Intensity of the baked light.
  29221. *
  29222. * @type {number}
  29223. * @default 1
  29224. */
  29225. this.lightMapIntensity = 1.0;
  29226. /**
  29227. * The red channel of this texture is used as the ambient occlusion map.
  29228. * Requires a second set of UVs.
  29229. *
  29230. * `aoMap` represents non-color data. Any texture assigned must have
  29231. * `texture.colorSpace = NoColorSpace` (default).
  29232. *
  29233. * @type {?Texture}
  29234. * @default null
  29235. */
  29236. this.aoMap = null;
  29237. /**
  29238. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29239. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29240. * red channel is also `1`, ambient light is fully occluded on a surface.
  29241. *
  29242. * @type {number}
  29243. * @default 1
  29244. */
  29245. this.aoMapIntensity = 1.0;
  29246. /**
  29247. * Emissive (light) color of the material, essentially a solid color
  29248. * unaffected by other lighting.
  29249. *
  29250. * @type {Color}
  29251. * @default (0,0,0)
  29252. */
  29253. this.emissive = new Color( 0x000000 );
  29254. /**
  29255. * Intensity of the emissive light. Modulates the emissive color.
  29256. *
  29257. * @type {number}
  29258. * @default 1
  29259. */
  29260. this.emissiveIntensity = 1.0;
  29261. /**
  29262. * Set emissive (glow) map. The emissive map color is modulated by the
  29263. * emissive color and the emissive intensity. If you have an emissive map,
  29264. * be sure to set the emissive color to something other than black.
  29265. *
  29266. * `emissiveMap` represents color data, and the texture must be assigned a
  29267. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  29268. * `texture.colorSpace = SRGBColorSpace`.
  29269. *
  29270. * @type {?Texture}
  29271. * @default null
  29272. */
  29273. this.emissiveMap = null;
  29274. /**
  29275. * The texture to create a bump map. The black and white values map to the
  29276. * perceived depth in relation to the lights. Bump doesn't actually affect
  29277. * the geometry of the object, only the lighting. If a normal map is defined
  29278. * this will be ignored.
  29279. *
  29280. * `bumpMap` represents non-color data. Any texture assigned must have
  29281. * `texture.colorSpace = NoColorSpace` (default).
  29282. *
  29283. * @type {?Texture}
  29284. * @default null
  29285. */
  29286. this.bumpMap = null;
  29287. /**
  29288. * How much the bump map affects the material. Typical range is `[0,1]`.
  29289. *
  29290. * @type {number}
  29291. * @default 1
  29292. */
  29293. this.bumpScale = 1;
  29294. /**
  29295. * The texture to create a normal map. The RGB values affect the surface
  29296. * normal for each pixel fragment and change the way the color is lit. Normal
  29297. * maps do not change the actual shape of the surface, only the lighting. In
  29298. * case the material has a normal map authored using the left handed
  29299. * convention, the `y` component of `normalScale` should be negated to compensate
  29300. * for the different handedness.
  29301. *
  29302. * `normalMap` represents non-color data. Any texture assigned must have
  29303. * `texture.colorSpace = NoColorSpace` (default).
  29304. *
  29305. * @type {?Texture}
  29306. * @default null
  29307. */
  29308. this.normalMap = null;
  29309. /**
  29310. * The type of normal map.
  29311. *
  29312. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29313. * @default TangentSpaceNormalMap
  29314. */
  29315. this.normalMapType = TangentSpaceNormalMap;
  29316. /**
  29317. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29318. *
  29319. * @type {Vector2}
  29320. * @default (1,1)
  29321. */
  29322. this.normalScale = new Vector2( 1, 1 );
  29323. /**
  29324. * The displacement map affects the position of the mesh's vertices. Unlike
  29325. * other maps which only affect the light and shade of the material the
  29326. * displaced vertices can cast shadows, block other objects, and otherwise
  29327. * act as real geometry. The displacement texture is an image where the value
  29328. * of each pixel (white being the highest) is mapped against, and
  29329. * repositions, the vertices of the mesh. For best results, pair a
  29330. * displacement map with a matching normal map, since the renderer can
  29331. * not recompute surface normals from the displaced vertices.
  29332. *
  29333. * `displacementMap` represents non-color data. Any texture assigned must have
  29334. * `texture.colorSpace = NoColorSpace` (default).
  29335. *
  29336. * @type {?Texture}
  29337. * @default null
  29338. */
  29339. this.displacementMap = null;
  29340. /**
  29341. * How much the displacement map affects the mesh (where black is no
  29342. * displacement, and white is maximum displacement). Without a displacement
  29343. * map set, this value is not applied.
  29344. *
  29345. * @type {number}
  29346. * @default 0
  29347. */
  29348. this.displacementScale = 1;
  29349. /**
  29350. * The offset of the displacement map's values on the mesh's vertices.
  29351. * The bias is added to the scaled sample of the displacement map.
  29352. * Without a displacement map set, this value is not applied.
  29353. *
  29354. * @type {number}
  29355. * @default 0
  29356. */
  29357. this.displacementBias = 0;
  29358. /**
  29359. * The alpha map is a grayscale texture that controls the opacity across the
  29360. * surface (black: fully transparent; white: fully opaque).
  29361. *
  29362. * Only the color of the texture is used, ignoring the alpha channel if one
  29363. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29364. * when sampling this texture due to the extra bit of precision provided for
  29365. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29366. * luminance/alpha textures will also still work as expected.
  29367. *
  29368. * `alphaMap` represents non-color data. Any texture assigned must have
  29369. * `texture.colorSpace = NoColorSpace` (default).
  29370. *
  29371. * @type {?Texture}
  29372. * @default null
  29373. */
  29374. this.alphaMap = null;
  29375. /**
  29376. * Renders the geometry as a wireframe.
  29377. *
  29378. * @type {boolean}
  29379. * @default false
  29380. */
  29381. this.wireframe = false;
  29382. /**
  29383. * Controls the thickness of the wireframe.
  29384. *
  29385. * Can only be used with {@link SVGRenderer}.
  29386. *
  29387. * @type {number}
  29388. * @default 1
  29389. */
  29390. this.wireframeLinewidth = 1;
  29391. /**
  29392. * Defines appearance of wireframe ends.
  29393. *
  29394. * Can only be used with {@link SVGRenderer}.
  29395. *
  29396. * @type {('round'|'bevel'|'miter')}
  29397. * @default 'round'
  29398. */
  29399. this.wireframeLinecap = 'round';
  29400. /**
  29401. * Defines appearance of wireframe joints.
  29402. *
  29403. * Can only be used with {@link SVGRenderer}.
  29404. *
  29405. * @type {('round'|'bevel'|'miter')}
  29406. * @default 'round'
  29407. */
  29408. this.wireframeLinejoin = 'round';
  29409. /**
  29410. * Whether the material is affected by fog or not.
  29411. *
  29412. * @type {boolean}
  29413. * @default true
  29414. */
  29415. this.fog = true;
  29416. this.setValues( parameters );
  29417. }
  29418. copy( source ) {
  29419. super.copy( source );
  29420. this.color.copy( source.color );
  29421. this.map = source.map;
  29422. this.gradientMap = source.gradientMap;
  29423. this.lightMap = source.lightMap;
  29424. this.lightMapIntensity = source.lightMapIntensity;
  29425. this.aoMap = source.aoMap;
  29426. this.aoMapIntensity = source.aoMapIntensity;
  29427. this.emissive.copy( source.emissive );
  29428. this.emissiveMap = source.emissiveMap;
  29429. this.emissiveIntensity = source.emissiveIntensity;
  29430. this.bumpMap = source.bumpMap;
  29431. this.bumpScale = source.bumpScale;
  29432. this.normalMap = source.normalMap;
  29433. this.normalMapType = source.normalMapType;
  29434. this.normalScale.copy( source.normalScale );
  29435. this.displacementMap = source.displacementMap;
  29436. this.displacementScale = source.displacementScale;
  29437. this.displacementBias = source.displacementBias;
  29438. this.alphaMap = source.alphaMap;
  29439. this.wireframe = source.wireframe;
  29440. this.wireframeLinewidth = source.wireframeLinewidth;
  29441. this.wireframeLinecap = source.wireframeLinecap;
  29442. this.wireframeLinejoin = source.wireframeLinejoin;
  29443. this.fog = source.fog;
  29444. return this;
  29445. }
  29446. }
  29447. /**
  29448. * A material that maps the normal vectors to RGB colors.
  29449. *
  29450. * @augments Material
  29451. * @demo scenes/material-browser.html#MeshNormalMaterial
  29452. */
  29453. class MeshNormalMaterial extends Material {
  29454. /**
  29455. * Constructs a new mesh normal material.
  29456. *
  29457. * @param {Object} [parameters] - An object with one or more properties
  29458. * defining the material's appearance. Any property of the material
  29459. * (including any property from inherited materials) can be passed
  29460. * in here. Color values can be passed any type of value accepted
  29461. * by {@link Color#set}.
  29462. */
  29463. constructor( parameters ) {
  29464. super();
  29465. /**
  29466. * This flag can be used for type testing.
  29467. *
  29468. * @type {boolean}
  29469. * @readonly
  29470. * @default true
  29471. */
  29472. this.isMeshNormalMaterial = true;
  29473. this.type = 'MeshNormalMaterial';
  29474. /**
  29475. * The texture to create a bump map. The black and white values map to the
  29476. * perceived depth in relation to the lights. Bump doesn't actually affect
  29477. * the geometry of the object, only the lighting. If a normal map is defined
  29478. * this will be ignored.
  29479. *
  29480. * `bumpMap` represents non-color data. Any texture assigned must have
  29481. * `texture.colorSpace = NoColorSpace` (default).
  29482. *
  29483. * @type {?Texture}
  29484. * @default null
  29485. */
  29486. this.bumpMap = null;
  29487. /**
  29488. * How much the bump map affects the material. Typical range is `[0,1]`.
  29489. *
  29490. * @type {number}
  29491. * @default 1
  29492. */
  29493. this.bumpScale = 1;
  29494. /**
  29495. * The texture to create a normal map. The RGB values affect the surface
  29496. * normal for each pixel fragment and change the way the color is lit. Normal
  29497. * maps do not change the actual shape of the surface, only the lighting. In
  29498. * case the material has a normal map authored using the left handed
  29499. * convention, the `y` component of `normalScale` should be negated to compensate
  29500. * for the different handedness.
  29501. *
  29502. * `normalMap` represents non-color data. Any texture assigned must have
  29503. * `texture.colorSpace = NoColorSpace` (default).
  29504. *
  29505. * @type {?Texture}
  29506. * @default null
  29507. */
  29508. this.normalMap = null;
  29509. /**
  29510. * The type of normal map.
  29511. *
  29512. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29513. * @default TangentSpaceNormalMap
  29514. */
  29515. this.normalMapType = TangentSpaceNormalMap;
  29516. /**
  29517. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29518. *
  29519. * @type {Vector2}
  29520. * @default (1,1)
  29521. */
  29522. this.normalScale = new Vector2( 1, 1 );
  29523. /**
  29524. * The displacement map affects the position of the mesh's vertices. Unlike
  29525. * other maps which only affect the light and shade of the material the
  29526. * displaced vertices can cast shadows, block other objects, and otherwise
  29527. * act as real geometry. The displacement texture is an image where the value
  29528. * of each pixel (white being the highest) is mapped against, and
  29529. * repositions, the vertices of the mesh. For best results, pair a
  29530. * displacement map with a matching normal map, since the renderer can
  29531. * not recompute surface normals from the displaced vertices.
  29532. *
  29533. * @type {?Texture}
  29534. * @default null
  29535. */
  29536. this.displacementMap = null;
  29537. /**
  29538. * How much the displacement map affects the mesh (where black is no
  29539. * displacement, and white is maximum displacement). Without a displacement
  29540. * map set, this value is not applied.
  29541. *
  29542. * @type {number}
  29543. * @default 0
  29544. */
  29545. this.displacementScale = 1;
  29546. /**
  29547. * The offset of the displacement map's values on the mesh's vertices.
  29548. * The bias is added to the scaled sample of the displacement map.
  29549. * Without a displacement map set, this value is not applied.
  29550. *
  29551. * @type {number}
  29552. * @default 0
  29553. */
  29554. this.displacementBias = 0;
  29555. /**
  29556. * Renders the geometry as a wireframe.
  29557. *
  29558. * @type {boolean}
  29559. * @default false
  29560. */
  29561. this.wireframe = false;
  29562. /**
  29563. * Controls the thickness of the wireframe.
  29564. *
  29565. * WebGL and WebGPU ignore this property and always render
  29566. * 1 pixel wide lines.
  29567. *
  29568. * @type {number}
  29569. * @default 1
  29570. */
  29571. this.wireframeLinewidth = 1;
  29572. /**
  29573. * Whether the material is rendered with flat shading or not.
  29574. *
  29575. * @type {boolean}
  29576. * @default false
  29577. */
  29578. this.flatShading = false;
  29579. this.setValues( parameters );
  29580. }
  29581. copy( source ) {
  29582. super.copy( source );
  29583. this.bumpMap = source.bumpMap;
  29584. this.bumpScale = source.bumpScale;
  29585. this.normalMap = source.normalMap;
  29586. this.normalMapType = source.normalMapType;
  29587. this.normalScale.copy( source.normalScale );
  29588. this.displacementMap = source.displacementMap;
  29589. this.displacementScale = source.displacementScale;
  29590. this.displacementBias = source.displacementBias;
  29591. this.wireframe = source.wireframe;
  29592. this.wireframeLinewidth = source.wireframeLinewidth;
  29593. this.flatShading = source.flatShading;
  29594. return this;
  29595. }
  29596. }
  29597. /**
  29598. * A material for non-shiny surfaces, without specular highlights.
  29599. *
  29600. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29601. * model for calculating reflectance. This can simulate some surfaces (such
  29602. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29603. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29604. * shading.
  29605. *
  29606. * Due to the simplicity of the reflectance and illumination models,
  29607. * performance will be greater when using this material over the
  29608. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29609. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29610. *
  29611. * @augments Material
  29612. * @demo scenes/material-browser.html#MeshLambertMaterial
  29613. */
  29614. class MeshLambertMaterial extends Material {
  29615. /**
  29616. * Constructs a new mesh lambert material.
  29617. *
  29618. * @param {Object} [parameters] - An object with one or more properties
  29619. * defining the material's appearance. Any property of the material
  29620. * (including any property from inherited materials) can be passed
  29621. * in here. Color values can be passed any type of value accepted
  29622. * by {@link Color#set}.
  29623. */
  29624. constructor( parameters ) {
  29625. super();
  29626. /**
  29627. * This flag can be used for type testing.
  29628. *
  29629. * @type {boolean}
  29630. * @readonly
  29631. * @default true
  29632. */
  29633. this.isMeshLambertMaterial = true;
  29634. this.type = 'MeshLambertMaterial';
  29635. /**
  29636. * Color of the material.
  29637. *
  29638. * @type {Color}
  29639. * @default (1,1,1)
  29640. */
  29641. this.color = new Color( 0xffffff ); // diffuse
  29642. /**
  29643. * The color map. May optionally include an alpha channel, typically combined
  29644. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29645. * color is modulated by the diffuse `color`.
  29646. *
  29647. * `map` represents color data, and the texture must be assigned a
  29648. * {@link Texture#colorSpace}. Most `map` textures set
  29649. * `texture.colorSpace = SRGBColorSpace`.
  29650. *
  29651. * @type {?Texture}
  29652. * @default null
  29653. */
  29654. this.map = null;
  29655. /**
  29656. * The light map. Requires a second set of UVs.
  29657. *
  29658. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  29659. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  29660. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29661. * such as `.exr` or `.hdr`.
  29662. *
  29663. * @type {?Texture}
  29664. * @default null
  29665. */
  29666. this.lightMap = null;
  29667. /**
  29668. * Intensity of the baked light.
  29669. *
  29670. * @type {number}
  29671. * @default 1
  29672. */
  29673. this.lightMapIntensity = 1.0;
  29674. /**
  29675. * The red channel of this texture is used as the ambient occlusion map.
  29676. * Requires a second set of UVs.
  29677. *
  29678. * `aoMap` represents non-color data. Any texture assigned must have
  29679. * `texture.colorSpace = NoColorSpace` (default).
  29680. *
  29681. * @type {?Texture}
  29682. * @default null
  29683. */
  29684. this.aoMap = null;
  29685. /**
  29686. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29687. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29688. * red channel is also `1`, ambient light is fully occluded on a surface.
  29689. *
  29690. * @type {number}
  29691. * @default 1
  29692. */
  29693. this.aoMapIntensity = 1.0;
  29694. /**
  29695. * Emissive (light) color of the material, essentially a solid color
  29696. * unaffected by other lighting.
  29697. *
  29698. * @type {Color}
  29699. * @default (0,0,0)
  29700. */
  29701. this.emissive = new Color( 0x000000 );
  29702. /**
  29703. * Intensity of the emissive light. Modulates the emissive color.
  29704. *
  29705. * @type {number}
  29706. * @default 1
  29707. */
  29708. this.emissiveIntensity = 1.0;
  29709. /**
  29710. * Set emissive (glow) map. The emissive map color is modulated by the
  29711. * emissive color and the emissive intensity. If you have an emissive map,
  29712. * be sure to set the emissive color to something other than black.
  29713. *
  29714. * `emissiveMap` represents color data, and the texture must be assigned a
  29715. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  29716. * `texture.colorSpace = SRGBColorSpace`.
  29717. *
  29718. * @type {?Texture}
  29719. * @default null
  29720. */
  29721. this.emissiveMap = null;
  29722. /**
  29723. * The texture to create a bump map. The black and white values map to the
  29724. * perceived depth in relation to the lights. Bump doesn't actually affect
  29725. * the geometry of the object, only the lighting. If a normal map is defined
  29726. * this will be ignored.
  29727. *
  29728. * `bumpMap` represents non-color data. Any texture assigned must have
  29729. * `texture.colorSpace = NoColorSpace` (default).
  29730. *
  29731. * @type {?Texture}
  29732. * @default null
  29733. */
  29734. this.bumpMap = null;
  29735. /**
  29736. * How much the bump map affects the material. Typical range is `[0,1]`.
  29737. *
  29738. * @type {number}
  29739. * @default 1
  29740. */
  29741. this.bumpScale = 1;
  29742. /**
  29743. * The texture to create a normal map. The RGB values affect the surface
  29744. * normal for each pixel fragment and change the way the color is lit. Normal
  29745. * maps do not change the actual shape of the surface, only the lighting. In
  29746. * case the material has a normal map authored using the left handed
  29747. * convention, the `y` component of `normalScale` should be negated to compensate
  29748. * for the different handedness.
  29749. *
  29750. * `normalMap` represents non-color data. Any texture assigned must have
  29751. * `texture.colorSpace = NoColorSpace` (default).
  29752. *
  29753. * @type {?Texture}
  29754. * @default null
  29755. */
  29756. this.normalMap = null;
  29757. /**
  29758. * The type of normal map.
  29759. *
  29760. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29761. * @default TangentSpaceNormalMap
  29762. */
  29763. this.normalMapType = TangentSpaceNormalMap;
  29764. /**
  29765. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29766. *
  29767. * @type {Vector2}
  29768. * @default (1,1)
  29769. */
  29770. this.normalScale = new Vector2( 1, 1 );
  29771. /**
  29772. * The displacement map affects the position of the mesh's vertices. Unlike
  29773. * other maps which only affect the light and shade of the material the
  29774. * displaced vertices can cast shadows, block other objects, and otherwise
  29775. * act as real geometry. The displacement texture is an image where the value
  29776. * of each pixel (white being the highest) is mapped against, and
  29777. * repositions, the vertices of the mesh. For best results, pair a
  29778. * displacement map with a matching normal map, since the renderer can
  29779. * not recompute surface normals from the displaced vertices.
  29780. *
  29781. * `displacementMap` represents non-color data. Any texture assigned must have
  29782. * `texture.colorSpace = NoColorSpace` (default).
  29783. *
  29784. * @type {?Texture}
  29785. * @default null
  29786. */
  29787. this.displacementMap = null;
  29788. /**
  29789. * How much the displacement map affects the mesh (where black is no
  29790. * displacement, and white is maximum displacement). Without a displacement
  29791. * map set, this value is not applied.
  29792. *
  29793. * @type {number}
  29794. * @default 0
  29795. */
  29796. this.displacementScale = 1;
  29797. /**
  29798. * The offset of the displacement map's values on the mesh's vertices.
  29799. * The bias is added to the scaled sample of the displacement map.
  29800. * Without a displacement map set, this value is not applied.
  29801. *
  29802. * @type {number}
  29803. * @default 0
  29804. */
  29805. this.displacementBias = 0;
  29806. /**
  29807. * Specular map used by the material.
  29808. *
  29809. * `specularMap` represents color data, and the texture must be assigned a
  29810. * {@link Texture#colorSpace}. Most `specularMap` textures set
  29811. * `texture.colorSpace = SRGBColorSpace`.
  29812. *
  29813. * @type {?Texture}
  29814. * @default null
  29815. */
  29816. this.specularMap = null;
  29817. /**
  29818. * The alpha map is a grayscale texture that controls the opacity across the
  29819. * surface (black: fully transparent; white: fully opaque).
  29820. *
  29821. * Only the color of the texture is used, ignoring the alpha channel if one
  29822. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29823. * when sampling this texture due to the extra bit of precision provided for
  29824. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29825. * luminance/alpha textures will also still work as expected.
  29826. *
  29827. * `alphaMap` represents non-color data. Any texture assigned must have
  29828. * `texture.colorSpace = NoColorSpace` (default).
  29829. *
  29830. * @type {?Texture}
  29831. * @default null
  29832. */
  29833. this.alphaMap = null;
  29834. /**
  29835. * The environment map.
  29836. *
  29837. * `envMap` represents luminance data, and the texture must be assigned
  29838. * a {@link Texture#colorSpace}. Most `envMap` textures set
  29839. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29840. * such as `.exr` or `.hdr`.
  29841. *
  29842. * @type {?Texture}
  29843. * @default null
  29844. */
  29845. this.envMap = null;
  29846. /**
  29847. * The rotation of the environment map in radians.
  29848. *
  29849. * @type {Euler}
  29850. * @default (0,0,0)
  29851. */
  29852. this.envMapRotation = new Euler();
  29853. /**
  29854. * How to combine the result of the surface's color with the environment map, if any.
  29855. *
  29856. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29857. * blend between the two colors.
  29858. *
  29859. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29860. * @default MultiplyOperation
  29861. */
  29862. this.combine = MultiplyOperation;
  29863. /**
  29864. * How much the environment map affects the surface.
  29865. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29866. *
  29867. * @type {number}
  29868. * @default 1
  29869. */
  29870. this.reflectivity = 1;
  29871. /**
  29872. * Scales the effect of the environment map by multiplying its color.
  29873. *
  29874. * @type {number}
  29875. * @default 1
  29876. */
  29877. this.envMapIntensity = 1.0;
  29878. /**
  29879. * The index of refraction (IOR) of air (approximately 1) divided by the
  29880. * index of refraction of the material. It is used with environment mapping
  29881. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29882. * The refraction ratio should not exceed `1`.
  29883. *
  29884. * @type {number}
  29885. * @default 0.98
  29886. */
  29887. this.refractionRatio = 0.98;
  29888. /**
  29889. * Renders the geometry as a wireframe.
  29890. *
  29891. * @type {boolean}
  29892. * @default false
  29893. */
  29894. this.wireframe = false;
  29895. /**
  29896. * Controls the thickness of the wireframe.
  29897. *
  29898. * Can only be used with {@link SVGRenderer}.
  29899. *
  29900. * @type {number}
  29901. * @default 1
  29902. */
  29903. this.wireframeLinewidth = 1;
  29904. /**
  29905. * Defines appearance of wireframe ends.
  29906. *
  29907. * Can only be used with {@link SVGRenderer}.
  29908. *
  29909. * @type {('round'|'bevel'|'miter')}
  29910. * @default 'round'
  29911. */
  29912. this.wireframeLinecap = 'round';
  29913. /**
  29914. * Defines appearance of wireframe joints.
  29915. *
  29916. * Can only be used with {@link SVGRenderer}.
  29917. *
  29918. * @type {('round'|'bevel'|'miter')}
  29919. * @default 'round'
  29920. */
  29921. this.wireframeLinejoin = 'round';
  29922. /**
  29923. * Whether the material is rendered with flat shading or not.
  29924. *
  29925. * @type {boolean}
  29926. * @default false
  29927. */
  29928. this.flatShading = false;
  29929. /**
  29930. * Whether the material is affected by fog or not.
  29931. *
  29932. * @type {boolean}
  29933. * @default true
  29934. */
  29935. this.fog = true;
  29936. this.setValues( parameters );
  29937. }
  29938. copy( source ) {
  29939. super.copy( source );
  29940. this.color.copy( source.color );
  29941. this.map = source.map;
  29942. this.lightMap = source.lightMap;
  29943. this.lightMapIntensity = source.lightMapIntensity;
  29944. this.aoMap = source.aoMap;
  29945. this.aoMapIntensity = source.aoMapIntensity;
  29946. this.emissive.copy( source.emissive );
  29947. this.emissiveMap = source.emissiveMap;
  29948. this.emissiveIntensity = source.emissiveIntensity;
  29949. this.bumpMap = source.bumpMap;
  29950. this.bumpScale = source.bumpScale;
  29951. this.normalMap = source.normalMap;
  29952. this.normalMapType = source.normalMapType;
  29953. this.normalScale.copy( source.normalScale );
  29954. this.displacementMap = source.displacementMap;
  29955. this.displacementScale = source.displacementScale;
  29956. this.displacementBias = source.displacementBias;
  29957. this.specularMap = source.specularMap;
  29958. this.alphaMap = source.alphaMap;
  29959. this.envMap = source.envMap;
  29960. this.envMapRotation.copy( source.envMapRotation );
  29961. this.combine = source.combine;
  29962. this.reflectivity = source.reflectivity;
  29963. this.envMapIntensity = source.envMapIntensity;
  29964. this.refractionRatio = source.refractionRatio;
  29965. this.wireframe = source.wireframe;
  29966. this.wireframeLinewidth = source.wireframeLinewidth;
  29967. this.wireframeLinecap = source.wireframeLinecap;
  29968. this.wireframeLinejoin = source.wireframeLinejoin;
  29969. this.flatShading = source.flatShading;
  29970. this.fog = source.fog;
  29971. return this;
  29972. }
  29973. }
  29974. /**
  29975. * A material for drawing geometry by depth. Depth is based off of the camera
  29976. * near and far plane. White is nearest, black is farthest.
  29977. *
  29978. * @augments Material
  29979. * @demo scenes/material-browser.html#MeshDepthMaterial
  29980. */
  29981. class MeshDepthMaterial extends Material {
  29982. /**
  29983. * Constructs a new mesh depth material.
  29984. *
  29985. * @param {Object} [parameters] - An object with one or more properties
  29986. * defining the material's appearance. Any property of the material
  29987. * (including any property from inherited materials) can be passed
  29988. * in here. Color values can be passed any type of value accepted
  29989. * by {@link Color#set}.
  29990. */
  29991. constructor( parameters ) {
  29992. super();
  29993. /**
  29994. * This flag can be used for type testing.
  29995. *
  29996. * @type {boolean}
  29997. * @readonly
  29998. * @default true
  29999. */
  30000. this.isMeshDepthMaterial = true;
  30001. this.type = 'MeshDepthMaterial';
  30002. /**
  30003. * Type for depth packing.
  30004. *
  30005. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  30006. * @default BasicDepthPacking
  30007. */
  30008. this.depthPacking = BasicDepthPacking;
  30009. /**
  30010. * The color map. May optionally include an alpha channel, typically combined
  30011. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30012. *
  30013. * `map` represents color data, and the texture must be assigned a
  30014. * {@link Texture#colorSpace}. Most `map` textures set
  30015. * `texture.colorSpace = SRGBColorSpace`.
  30016. *
  30017. * @type {?Texture}
  30018. * @default null
  30019. */
  30020. this.map = null;
  30021. /**
  30022. * The alpha map is a grayscale texture that controls the opacity across the
  30023. * surface (black: fully transparent; white: fully opaque).
  30024. *
  30025. * Only the color of the texture is used, ignoring the alpha channel if one
  30026. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30027. * when sampling this texture due to the extra bit of precision provided for
  30028. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30029. * luminance/alpha textures will also still work as expected.
  30030. *
  30031. * `alphaMap` represents non-color data. Any texture assigned must have
  30032. * `texture.colorSpace = NoColorSpace` (default).
  30033. *
  30034. * @type {?Texture}
  30035. * @default null
  30036. */
  30037. this.alphaMap = null;
  30038. /**
  30039. * The displacement map affects the position of the mesh's vertices. Unlike
  30040. * other maps which only affect the light and shade of the material the
  30041. * displaced vertices can cast shadows, block other objects, and otherwise
  30042. * act as real geometry. The displacement texture is an image where the value
  30043. * of each pixel (white being the highest) is mapped against, and
  30044. * repositions, the vertices of the mesh.
  30045. *
  30046. * `displacementMap` represents non-color data. Any texture assigned must have
  30047. * `texture.colorSpace = NoColorSpace` (default).
  30048. *
  30049. * @type {?Texture}
  30050. * @default null
  30051. */
  30052. this.displacementMap = null;
  30053. /**
  30054. * How much the displacement map affects the mesh (where black is no
  30055. * displacement, and white is maximum displacement). Without a displacement
  30056. * map set, this value is not applied.
  30057. *
  30058. * @type {number}
  30059. * @default 0
  30060. */
  30061. this.displacementScale = 1;
  30062. /**
  30063. * The offset of the displacement map's values on the mesh's vertices.
  30064. * The bias is added to the scaled sample of the displacement map.
  30065. * Without a displacement map set, this value is not applied.
  30066. *
  30067. * @type {number}
  30068. * @default 0
  30069. */
  30070. this.displacementBias = 0;
  30071. /**
  30072. * Renders the geometry as a wireframe.
  30073. *
  30074. * @type {boolean}
  30075. * @default false
  30076. */
  30077. this.wireframe = false;
  30078. /**
  30079. * Controls the thickness of the wireframe.
  30080. *
  30081. * WebGL and WebGPU ignore this property and always render
  30082. * 1 pixel wide lines.
  30083. *
  30084. * @type {number}
  30085. * @default 1
  30086. */
  30087. this.wireframeLinewidth = 1;
  30088. this.setValues( parameters );
  30089. }
  30090. copy( source ) {
  30091. super.copy( source );
  30092. this.depthPacking = source.depthPacking;
  30093. this.map = source.map;
  30094. this.alphaMap = source.alphaMap;
  30095. this.displacementMap = source.displacementMap;
  30096. this.displacementScale = source.displacementScale;
  30097. this.displacementBias = source.displacementBias;
  30098. this.wireframe = source.wireframe;
  30099. this.wireframeLinewidth = source.wireframeLinewidth;
  30100. return this;
  30101. }
  30102. }
  30103. /**
  30104. * A material used internally for implementing shadow mapping with
  30105. * point lights.
  30106. *
  30107. * Can also be used to customize the shadow casting of an object by assigning
  30108. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  30109. * The following examples demonstrates this approach in order to ensure
  30110. * transparent parts of objects do not cast shadows.
  30111. *
  30112. * @augments Material
  30113. */
  30114. class MeshDistanceMaterial extends Material {
  30115. /**
  30116. * Constructs a new mesh distance material.
  30117. *
  30118. * @param {Object} [parameters] - An object with one or more properties
  30119. * defining the material's appearance. Any property of the material
  30120. * (including any property from inherited materials) can be passed
  30121. * in here. Color values can be passed any type of value accepted
  30122. * by {@link Color#set}.
  30123. */
  30124. constructor( parameters ) {
  30125. super();
  30126. /**
  30127. * This flag can be used for type testing.
  30128. *
  30129. * @type {boolean}
  30130. * @readonly
  30131. * @default true
  30132. */
  30133. this.isMeshDistanceMaterial = true;
  30134. this.type = 'MeshDistanceMaterial';
  30135. /**
  30136. * The color map. May optionally include an alpha channel, typically combined
  30137. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30138. *
  30139. * `map` represents color data, and the texture must be assigned a
  30140. * {@link Texture#colorSpace}. Most `map` textures set
  30141. * `texture.colorSpace = SRGBColorSpace`.
  30142. *
  30143. * @type {?Texture}
  30144. * @default null
  30145. */
  30146. this.map = null;
  30147. /**
  30148. * The alpha map is a grayscale texture that controls the opacity across the
  30149. * surface (black: fully transparent; white: fully opaque).
  30150. *
  30151. * Only the color of the texture is used, ignoring the alpha channel if one
  30152. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30153. * when sampling this texture due to the extra bit of precision provided for
  30154. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30155. * luminance/alpha textures will also still work as expected.
  30156. *
  30157. * `alphaMap` represents non-color data. Any texture assigned must have
  30158. * `texture.colorSpace = NoColorSpace` (default).
  30159. *
  30160. * @type {?Texture}
  30161. * @default null
  30162. */
  30163. this.alphaMap = null;
  30164. /**
  30165. * The displacement map affects the position of the mesh's vertices. Unlike
  30166. * other maps which only affect the light and shade of the material the
  30167. * displaced vertices can cast shadows, block other objects, and otherwise
  30168. * act as real geometry. The displacement texture is an image where the value
  30169. * of each pixel (white being the highest) is mapped against, and
  30170. * repositions, the vertices of the mesh.
  30171. *
  30172. * `displacementMap` represents non-color data. Any texture assigned must have
  30173. * `texture.colorSpace = NoColorSpace` (default).
  30174. *
  30175. * @type {?Texture}
  30176. * @default null
  30177. */
  30178. this.displacementMap = null;
  30179. /**
  30180. * How much the displacement map affects the mesh (where black is no
  30181. * displacement, and white is maximum displacement). Without a displacement
  30182. * map set, this value is not applied.
  30183. *
  30184. * @type {number}
  30185. * @default 0
  30186. */
  30187. this.displacementScale = 1;
  30188. /**
  30189. * The offset of the displacement map's values on the mesh's vertices.
  30190. * The bias is added to the scaled sample of the displacement map.
  30191. * Without a displacement map set, this value is not applied.
  30192. *
  30193. * @type {number}
  30194. * @default 0
  30195. */
  30196. this.displacementBias = 0;
  30197. this.setValues( parameters );
  30198. }
  30199. copy( source ) {
  30200. super.copy( source );
  30201. this.map = source.map;
  30202. this.alphaMap = source.alphaMap;
  30203. this.displacementMap = source.displacementMap;
  30204. this.displacementScale = source.displacementScale;
  30205. this.displacementBias = source.displacementBias;
  30206. return this;
  30207. }
  30208. }
  30209. /**
  30210. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  30211. * material color and shading.
  30212. *
  30213. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  30214. * baked lighting. It will cast a shadow onto an object that receives shadows
  30215. * (and shadow clipping works), but it will not self-shadow or receive
  30216. * shadows.
  30217. *
  30218. * @augments Material
  30219. * @demo scenes/material-browser.html#MeshMatcapMaterial
  30220. */
  30221. class MeshMatcapMaterial extends Material {
  30222. /**
  30223. * Constructs a new mesh matcap material.
  30224. *
  30225. * @param {Object} [parameters] - An object with one or more properties
  30226. * defining the material's appearance. Any property of the material
  30227. * (including any property from inherited materials) can be passed
  30228. * in here. Color values can be passed any type of value accepted
  30229. * by {@link Color#set}.
  30230. */
  30231. constructor( parameters ) {
  30232. super();
  30233. /**
  30234. * This flag can be used for type testing.
  30235. *
  30236. * @type {boolean}
  30237. * @readonly
  30238. * @default true
  30239. */
  30240. this.isMeshMatcapMaterial = true;
  30241. this.defines = { 'MATCAP': '' };
  30242. this.type = 'MeshMatcapMaterial';
  30243. /**
  30244. * Color of the material.
  30245. *
  30246. * @type {Color}
  30247. * @default (1,1,1)
  30248. */
  30249. this.color = new Color( 0xffffff ); // diffuse
  30250. /**
  30251. * The matcap map.
  30252. *
  30253. * `matcap` represents luminance data, and the texture must be assigned
  30254. * a {@link Texture#colorSpace}. HDR `matcap` textures (e.g. `.exr`)
  30255. * typically set `texture.colorSpace = LinearSRGBColorSpace`, while LDR
  30256. * `matcap` textures (e.g. `.png`, `.jpg`, `.webp`) typically set
  30257. * `texture.colorSpace = SRGBColorSpace`.
  30258. *
  30259. * @type {?Texture}
  30260. * @default null
  30261. */
  30262. this.matcap = null;
  30263. /**
  30264. * The color map. May optionally include an alpha channel, typically combined
  30265. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30266. * color is modulated by the diffuse `color`.
  30267. *
  30268. * `map` represents color data, and the texture must be assigned a
  30269. * {@link Texture#colorSpace}. Most `map` textures set
  30270. * `texture.colorSpace = SRGBColorSpace`.
  30271. *
  30272. * @type {?Texture}
  30273. * @default null
  30274. */
  30275. this.map = null;
  30276. /**
  30277. * The texture to create a bump map. The black and white values map to the
  30278. * perceived depth in relation to the lights. Bump doesn't actually affect
  30279. * the geometry of the object, only the lighting. If a normal map is defined
  30280. * this will be ignored.
  30281. *
  30282. * `bumpMap` represents non-color data. Any texture assigned must have
  30283. * `texture.colorSpace = NoColorSpace` (default).
  30284. *
  30285. * @type {?Texture}
  30286. * @default null
  30287. */
  30288. this.bumpMap = null;
  30289. /**
  30290. * How much the bump map affects the material. Typical range is `[0,1]`.
  30291. *
  30292. * @type {number}
  30293. * @default 1
  30294. */
  30295. this.bumpScale = 1;
  30296. /**
  30297. * The texture to create a normal map. The RGB values affect the surface
  30298. * normal for each pixel fragment and change the way the color is lit. Normal
  30299. * maps do not change the actual shape of the surface, only the lighting. In
  30300. * case the material has a normal map authored using the left handed
  30301. * convention, the `y` component of `normalScale` should be negated to compensate
  30302. * for the different handedness.
  30303. *
  30304. * `normalMap` represents non-color data. Any texture assigned must have
  30305. * `texture.colorSpace = NoColorSpace` (default).
  30306. *
  30307. * @type {?Texture}
  30308. * @default null
  30309. */
  30310. this.normalMap = null;
  30311. /**
  30312. * The type of normal map.
  30313. *
  30314. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30315. * @default TangentSpaceNormalMap
  30316. */
  30317. this.normalMapType = TangentSpaceNormalMap;
  30318. /**
  30319. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30320. *
  30321. * @type {Vector2}
  30322. * @default (1,1)
  30323. */
  30324. this.normalScale = new Vector2( 1, 1 );
  30325. /**
  30326. * The displacement map affects the position of the mesh's vertices. Unlike
  30327. * other maps which only affect the light and shade of the material the
  30328. * displaced vertices can cast shadows, block other objects, and otherwise
  30329. * act as real geometry. The displacement texture is an image where the value
  30330. * of each pixel (white being the highest) is mapped against, and
  30331. * repositions, the vertices of the mesh. For best results, pair a
  30332. * displacement map with a matching normal map, since the renderer can
  30333. * not recompute surface normals from the displaced vertices.
  30334. *
  30335. * `displacementMap` represents non-color data. Any texture assigned must have
  30336. * `texture.colorSpace = NoColorSpace` (default).
  30337. *
  30338. * @type {?Texture}
  30339. * @default null
  30340. */
  30341. this.displacementMap = null;
  30342. /**
  30343. * How much the displacement map affects the mesh (where black is no
  30344. * displacement, and white is maximum displacement). Without a displacement
  30345. * map set, this value is not applied.
  30346. *
  30347. * @type {number}
  30348. * @default 0
  30349. */
  30350. this.displacementScale = 1;
  30351. /**
  30352. * The offset of the displacement map's values on the mesh's vertices.
  30353. * The bias is added to the scaled sample of the displacement map.
  30354. * Without a displacement map set, this value is not applied.
  30355. *
  30356. * @type {number}
  30357. * @default 0
  30358. */
  30359. this.displacementBias = 0;
  30360. /**
  30361. * The alpha map is a grayscale texture that controls the opacity across the
  30362. * surface (black: fully transparent; white: fully opaque).
  30363. *
  30364. * Only the color of the texture is used, ignoring the alpha channel if one
  30365. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30366. * when sampling this texture due to the extra bit of precision provided for
  30367. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30368. * luminance/alpha textures will also still work as expected.
  30369. *
  30370. * `alphaMap` represents non-color data. Any texture assigned must have
  30371. * `texture.colorSpace = NoColorSpace` (default).
  30372. *
  30373. * @type {?Texture}
  30374. * @default null
  30375. */
  30376. this.alphaMap = null;
  30377. /**
  30378. * Renders the geometry as a wireframe.
  30379. *
  30380. * @type {boolean}
  30381. * @default false
  30382. */
  30383. this.wireframe = false;
  30384. /**
  30385. * Controls the thickness of the wireframe.
  30386. *
  30387. * Can only be used with {@link SVGRenderer}.
  30388. *
  30389. * @type {number}
  30390. * @default 1
  30391. */
  30392. this.wireframeLinewidth = 1;
  30393. /**
  30394. * Whether the material is rendered with flat shading or not.
  30395. *
  30396. * @type {boolean}
  30397. * @default false
  30398. */
  30399. this.flatShading = false;
  30400. /**
  30401. * Whether the material is affected by fog or not.
  30402. *
  30403. * @type {boolean}
  30404. * @default true
  30405. */
  30406. this.fog = true;
  30407. this.setValues( parameters );
  30408. }
  30409. copy( source ) {
  30410. super.copy( source );
  30411. this.defines = { 'MATCAP': '' };
  30412. this.color.copy( source.color );
  30413. this.matcap = source.matcap;
  30414. this.map = source.map;
  30415. this.bumpMap = source.bumpMap;
  30416. this.bumpScale = source.bumpScale;
  30417. this.normalMap = source.normalMap;
  30418. this.normalMapType = source.normalMapType;
  30419. this.normalScale.copy( source.normalScale );
  30420. this.displacementMap = source.displacementMap;
  30421. this.displacementScale = source.displacementScale;
  30422. this.displacementBias = source.displacementBias;
  30423. this.alphaMap = source.alphaMap;
  30424. this.wireframe = source.wireframe;
  30425. this.wireframeLinewidth = source.wireframeLinewidth;
  30426. this.flatShading = source.flatShading;
  30427. this.fog = source.fog;
  30428. return this;
  30429. }
  30430. }
  30431. /**
  30432. * A material for rendering line primitives.
  30433. *
  30434. * Materials define the appearance of renderable 3D objects.
  30435. *
  30436. * ```js
  30437. * const material = new THREE.LineDashedMaterial( {
  30438. * color: 0xffffff,
  30439. * scale: 1,
  30440. * dashSize: 3,
  30441. * gapSize: 1,
  30442. * } );
  30443. * ```
  30444. *
  30445. * @augments LineBasicMaterial
  30446. */
  30447. class LineDashedMaterial extends LineBasicMaterial {
  30448. /**
  30449. * Constructs a new line dashed material.
  30450. *
  30451. * @param {Object} [parameters] - An object with one or more properties
  30452. * defining the material's appearance. Any property of the material
  30453. * (including any property from inherited materials) can be passed
  30454. * in here. Color values can be passed any type of value accepted
  30455. * by {@link Color#set}.
  30456. */
  30457. constructor( parameters ) {
  30458. super();
  30459. /**
  30460. * This flag can be used for type testing.
  30461. *
  30462. * @type {boolean}
  30463. * @readonly
  30464. * @default true
  30465. */
  30466. this.isLineDashedMaterial = true;
  30467. this.type = 'LineDashedMaterial';
  30468. /**
  30469. * The scale of the dashed part of a line.
  30470. *
  30471. * @type {number}
  30472. * @default 1
  30473. */
  30474. this.scale = 1;
  30475. /**
  30476. * The size of the dash. This is both the gap with the stroke.
  30477. *
  30478. * @type {number}
  30479. * @default 3
  30480. */
  30481. this.dashSize = 3;
  30482. /**
  30483. * The size of the gap.
  30484. *
  30485. * @type {number}
  30486. * @default 1
  30487. */
  30488. this.gapSize = 1;
  30489. this.setValues( parameters );
  30490. }
  30491. copy( source ) {
  30492. super.copy( source );
  30493. this.scale = source.scale;
  30494. this.dashSize = source.dashSize;
  30495. this.gapSize = source.gapSize;
  30496. return this;
  30497. }
  30498. }
  30499. /**
  30500. * Converts an array to a specific type.
  30501. *
  30502. * @param {TypedArray|Array} array - The array to convert.
  30503. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30504. * @return {TypedArray} The converted array.
  30505. */
  30506. function convertArray( array, type ) {
  30507. if ( ! array || array.constructor === type ) return array;
  30508. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30509. return new type( array ); // create typed array
  30510. }
  30511. return Array.prototype.slice.call( array ); // create Array
  30512. }
  30513. /**
  30514. * Returns an array by which times and values can be sorted.
  30515. *
  30516. * @param {Array<number>} times - The keyframe time values.
  30517. * @return {Array<number>} The array.
  30518. */
  30519. function getKeyframeOrder( times ) {
  30520. function compareTime( i, j ) {
  30521. return times[ i ] - times[ j ];
  30522. }
  30523. const n = times.length;
  30524. const result = new Array( n );
  30525. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30526. result.sort( compareTime );
  30527. return result;
  30528. }
  30529. /**
  30530. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30531. *
  30532. * @param {Array<number>} values - The values to sort.
  30533. * @param {number} stride - The stride.
  30534. * @param {Array<number>} order - The sort order.
  30535. * @return {Array<number>} The sorted values.
  30536. */
  30537. function sortedArray( values, stride, order ) {
  30538. const nValues = values.length;
  30539. const result = new values.constructor( nValues );
  30540. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30541. const srcOffset = order[ i ] * stride;
  30542. for ( let j = 0; j !== stride; ++ j ) {
  30543. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30544. }
  30545. }
  30546. return result;
  30547. }
  30548. /**
  30549. * Used for parsing AOS keyframe formats.
  30550. *
  30551. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30552. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30553. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30554. * @param {string} valuePropertyName - The name of the property to use.
  30555. */
  30556. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30557. let i = 1, key = jsonKeys[ 0 ];
  30558. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30559. key = jsonKeys[ i ++ ];
  30560. }
  30561. if ( key === undefined ) return; // no data
  30562. let value = key[ valuePropertyName ];
  30563. if ( value === undefined ) return; // no data
  30564. if ( Array.isArray( value ) ) {
  30565. do {
  30566. value = key[ valuePropertyName ];
  30567. if ( value !== undefined ) {
  30568. times.push( key.time );
  30569. values.push( ...value ); // push all elements
  30570. }
  30571. key = jsonKeys[ i ++ ];
  30572. } while ( key !== undefined );
  30573. } else if ( value.toArray !== undefined ) {
  30574. // ...assume THREE.Math-ish
  30575. do {
  30576. value = key[ valuePropertyName ];
  30577. if ( value !== undefined ) {
  30578. times.push( key.time );
  30579. value.toArray( values, values.length );
  30580. }
  30581. key = jsonKeys[ i ++ ];
  30582. } while ( key !== undefined );
  30583. } else {
  30584. // otherwise push as-is
  30585. do {
  30586. value = key[ valuePropertyName ];
  30587. if ( value !== undefined ) {
  30588. times.push( key.time );
  30589. values.push( value );
  30590. }
  30591. key = jsonKeys[ i ++ ];
  30592. } while ( key !== undefined );
  30593. }
  30594. }
  30595. /**
  30596. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30597. *
  30598. * @param {AnimationClip} sourceClip - The values to sort.
  30599. * @param {string} name - The name of the clip.
  30600. * @param {number} startFrame - The start frame.
  30601. * @param {number} endFrame - The end frame.
  30602. * @param {number} [fps=30] - The FPS.
  30603. * @return {AnimationClip} The new sub clip.
  30604. */
  30605. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30606. const clip = sourceClip.clone();
  30607. clip.name = name;
  30608. const tracks = [];
  30609. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30610. const track = clip.tracks[ i ];
  30611. const valueSize = track.getValueSize();
  30612. const times = [];
  30613. const values = [];
  30614. for ( let j = 0; j < track.times.length; ++ j ) {
  30615. const frame = track.times[ j ] * fps;
  30616. if ( frame < startFrame || frame >= endFrame ) continue;
  30617. times.push( track.times[ j ] );
  30618. for ( let k = 0; k < valueSize; ++ k ) {
  30619. values.push( track.values[ j * valueSize + k ] );
  30620. }
  30621. }
  30622. if ( times.length === 0 ) continue;
  30623. track.times = convertArray( times, track.times.constructor );
  30624. track.values = convertArray( values, track.values.constructor );
  30625. tracks.push( track );
  30626. }
  30627. clip.tracks = tracks;
  30628. // find minimum .times value across all tracks in the trimmed clip
  30629. let minStartTime = Infinity;
  30630. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30631. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30632. minStartTime = clip.tracks[ i ].times[ 0 ];
  30633. }
  30634. }
  30635. // shift all tracks such that clip begins at t=0
  30636. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30637. clip.tracks[ i ].shift( -1 * minStartTime );
  30638. }
  30639. clip.resetDuration();
  30640. return clip;
  30641. }
  30642. /**
  30643. * Converts the keyframes of the given animation clip to an additive format.
  30644. *
  30645. * @param {AnimationClip} targetClip - The clip to make additive.
  30646. * @param {number} [referenceFrame=0] - The reference frame.
  30647. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30648. * @param {number} [fps=30] - The FPS.
  30649. * @return {AnimationClip} The updated clip which is now additive.
  30650. */
  30651. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30652. if ( fps <= 0 ) fps = 30;
  30653. const numTracks = referenceClip.tracks.length;
  30654. const referenceTime = referenceFrame / fps;
  30655. // Make each track's values relative to the values at the reference frame
  30656. for ( let i = 0; i < numTracks; ++ i ) {
  30657. const referenceTrack = referenceClip.tracks[ i ];
  30658. const referenceTrackType = referenceTrack.ValueTypeName;
  30659. // Skip this track if it's non-numeric
  30660. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30661. // Find the track in the target clip whose name and type matches the reference track
  30662. const targetTrack = targetClip.tracks.find( function ( track ) {
  30663. return track.name === referenceTrack.name
  30664. && track.ValueTypeName === referenceTrackType;
  30665. } );
  30666. if ( targetTrack === undefined ) continue;
  30667. let referenceOffset = 0;
  30668. const referenceValueSize = referenceTrack.getValueSize();
  30669. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30670. referenceOffset = referenceValueSize / 3;
  30671. }
  30672. let targetOffset = 0;
  30673. const targetValueSize = targetTrack.getValueSize();
  30674. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30675. targetOffset = targetValueSize / 3;
  30676. }
  30677. const lastIndex = referenceTrack.times.length - 1;
  30678. let referenceValue;
  30679. // Find the value to subtract out of the track
  30680. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30681. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30682. const startIndex = referenceOffset;
  30683. const endIndex = referenceValueSize - referenceOffset;
  30684. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30685. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30686. // Reference frame is after the last keyframe, so just use the last keyframe
  30687. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30688. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30689. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30690. } else {
  30691. // Interpolate to the reference value
  30692. const interpolant = referenceTrack.createInterpolant();
  30693. const startIndex = referenceOffset;
  30694. const endIndex = referenceValueSize - referenceOffset;
  30695. interpolant.evaluate( referenceTime );
  30696. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30697. }
  30698. // Conjugate the quaternion
  30699. if ( referenceTrackType === 'quaternion' ) {
  30700. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30701. referenceQuat.toArray( referenceValue );
  30702. }
  30703. // Subtract the reference value from all of the track values
  30704. const numTimes = targetTrack.times.length;
  30705. for ( let j = 0; j < numTimes; ++ j ) {
  30706. const valueStart = j * targetValueSize + targetOffset;
  30707. if ( referenceTrackType === 'quaternion' ) {
  30708. // Multiply the conjugate for quaternion track types
  30709. Quaternion.multiplyQuaternionsFlat(
  30710. targetTrack.values,
  30711. valueStart,
  30712. referenceValue,
  30713. 0,
  30714. targetTrack.values,
  30715. valueStart
  30716. );
  30717. } else {
  30718. const valueEnd = targetValueSize - targetOffset * 2;
  30719. // Subtract each value for all other numeric track types
  30720. for ( let k = 0; k < valueEnd; ++ k ) {
  30721. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30722. }
  30723. }
  30724. }
  30725. }
  30726. targetClip.blendMode = AdditiveAnimationBlendMode;
  30727. return targetClip;
  30728. }
  30729. /**
  30730. * A class with various methods to assist with animations.
  30731. *
  30732. * @hideconstructor
  30733. */
  30734. class AnimationUtils {
  30735. /**
  30736. * Converts an array to a specific type
  30737. *
  30738. * @static
  30739. * @param {TypedArray|Array} array - The array to convert.
  30740. * @param {TypedArray.constructor} type - The constructor of a type array.
  30741. * @return {TypedArray} The converted array
  30742. */
  30743. static convertArray( array, type ) {
  30744. return convertArray( array, type );
  30745. }
  30746. /**
  30747. * Returns `true` if the given object is a typed array.
  30748. *
  30749. * @static
  30750. * @param {any} object - The object to check.
  30751. * @return {boolean} Whether the given object is a typed array.
  30752. */
  30753. static isTypedArray( object ) {
  30754. return isTypedArray( object );
  30755. }
  30756. /**
  30757. * Returns an array by which times and values can be sorted.
  30758. *
  30759. * @static
  30760. * @param {Array<number>} times - The keyframe time values.
  30761. * @return {Array<number>} The array.
  30762. */
  30763. static getKeyframeOrder( times ) {
  30764. return getKeyframeOrder( times );
  30765. }
  30766. /**
  30767. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30768. *
  30769. * @static
  30770. * @param {Array<number>} values - The values to sort.
  30771. * @param {number} stride - The stride.
  30772. * @param {Array<number>} order - The sort order.
  30773. * @return {Array<number>} The sorted values.
  30774. */
  30775. static sortedArray( values, stride, order ) {
  30776. return sortedArray( values, stride, order );
  30777. }
  30778. /**
  30779. * Used for parsing AOS keyframe formats.
  30780. *
  30781. * @static
  30782. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30783. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30784. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30785. * @param {string} valuePropertyName - The name of the property to use.
  30786. */
  30787. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30788. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30789. }
  30790. /**
  30791. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30792. *
  30793. * @static
  30794. * @param {AnimationClip} sourceClip - The values to sort.
  30795. * @param {string} name - The name of the clip.
  30796. * @param {number} startFrame - The start frame.
  30797. * @param {number} endFrame - The end frame.
  30798. * @param {number} [fps=30] - The FPS.
  30799. * @return {AnimationClip} The new sub clip.
  30800. */
  30801. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30802. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30803. }
  30804. /**
  30805. * Converts the keyframes of the given animation clip to an additive format.
  30806. *
  30807. * @static
  30808. * @param {AnimationClip} targetClip - The clip to make additive.
  30809. * @param {number} [referenceFrame=0] - The reference frame.
  30810. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30811. * @param {number} [fps=30] - The FPS.
  30812. * @return {AnimationClip} The updated clip which is now additive.
  30813. */
  30814. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30815. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30816. }
  30817. }
  30818. /**
  30819. * Abstract base class of interpolants over parametric samples.
  30820. *
  30821. * The parameter domain is one dimensional, typically the time or a path
  30822. * along a curve defined by the data.
  30823. *
  30824. * The sample values can have any dimensionality and derived classes may
  30825. * apply special interpretations to the data.
  30826. *
  30827. * This class provides the interval seek in a Template Method, deferring
  30828. * the actual interpolation to derived classes.
  30829. *
  30830. * Time complexity is O(1) for linear access crossing at most two points
  30831. * and O(log N) for random access, where N is the number of positions.
  30832. *
  30833. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30834. *
  30835. * @abstract
  30836. */
  30837. class Interpolant {
  30838. /**
  30839. * Constructs a new interpolant.
  30840. *
  30841. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30842. * @param {TypedArray} sampleValues - The sample values.
  30843. * @param {number} sampleSize - The sample size
  30844. * @param {TypedArray} [resultBuffer] - The result buffer.
  30845. */
  30846. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30847. /**
  30848. * The parameter positions.
  30849. *
  30850. * @type {TypedArray}
  30851. */
  30852. this.parameterPositions = parameterPositions;
  30853. /**
  30854. * A cache index.
  30855. *
  30856. * @private
  30857. * @type {number}
  30858. * @default 0
  30859. */
  30860. this._cachedIndex = 0;
  30861. /**
  30862. * The result buffer.
  30863. *
  30864. * @type {TypedArray}
  30865. */
  30866. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30867. /**
  30868. * The sample values.
  30869. *
  30870. * @type {TypedArray}
  30871. */
  30872. this.sampleValues = sampleValues;
  30873. /**
  30874. * The value size.
  30875. *
  30876. * @type {TypedArray}
  30877. */
  30878. this.valueSize = sampleSize;
  30879. /**
  30880. * The interpolation settings.
  30881. *
  30882. * @type {?Object}
  30883. * @default null
  30884. */
  30885. this.settings = null;
  30886. /**
  30887. * The default settings object.
  30888. *
  30889. * @type {Object}
  30890. */
  30891. this.DefaultSettings_ = {};
  30892. }
  30893. /**
  30894. * Evaluate the interpolant at position `t`.
  30895. *
  30896. * @param {number} t - The interpolation factor.
  30897. * @return {TypedArray} The result buffer.
  30898. */
  30899. evaluate( t ) {
  30900. const pp = this.parameterPositions;
  30901. let i1 = this._cachedIndex,
  30902. t1 = pp[ i1 ],
  30903. t0 = pp[ i1 - 1 ];
  30904. validate_interval: {
  30905. seek: {
  30906. let right;
  30907. linear_scan: {
  30908. //- See http://jsperf.com/comparison-to-undefined/3
  30909. //- slower code:
  30910. //-
  30911. //- if ( t >= t1 || t1 === undefined ) {
  30912. forward_scan: if ( ! ( t < t1 ) ) {
  30913. for ( let giveUpAt = i1 + 2; ; ) {
  30914. if ( t1 === undefined ) {
  30915. if ( t < t0 ) break forward_scan;
  30916. // after end
  30917. i1 = pp.length;
  30918. this._cachedIndex = i1;
  30919. return this.copySampleValue_( i1 - 1 );
  30920. }
  30921. if ( i1 === giveUpAt ) break; // this loop
  30922. t0 = t1;
  30923. t1 = pp[ ++ i1 ];
  30924. if ( t < t1 ) {
  30925. // we have arrived at the sought interval
  30926. break seek;
  30927. }
  30928. }
  30929. // prepare binary search on the right side of the index
  30930. right = pp.length;
  30931. break linear_scan;
  30932. }
  30933. //- slower code:
  30934. //- if ( t < t0 || t0 === undefined ) {
  30935. if ( ! ( t >= t0 ) ) {
  30936. // looping?
  30937. const t1global = pp[ 1 ];
  30938. if ( t < t1global ) {
  30939. i1 = 2; // + 1, using the scan for the details
  30940. t0 = t1global;
  30941. }
  30942. // linear reverse scan
  30943. for ( let giveUpAt = i1 - 2; ; ) {
  30944. if ( t0 === undefined ) {
  30945. // before start
  30946. this._cachedIndex = 0;
  30947. return this.copySampleValue_( 0 );
  30948. }
  30949. if ( i1 === giveUpAt ) break; // this loop
  30950. t1 = t0;
  30951. t0 = pp[ -- i1 - 1 ];
  30952. if ( t >= t0 ) {
  30953. // we have arrived at the sought interval
  30954. break seek;
  30955. }
  30956. }
  30957. // prepare binary search on the left side of the index
  30958. right = i1;
  30959. i1 = 0;
  30960. break linear_scan;
  30961. }
  30962. // the interval is valid
  30963. break validate_interval;
  30964. } // linear scan
  30965. // binary search
  30966. while ( i1 < right ) {
  30967. const mid = ( i1 + right ) >>> 1;
  30968. if ( t < pp[ mid ] ) {
  30969. right = mid;
  30970. } else {
  30971. i1 = mid + 1;
  30972. }
  30973. }
  30974. t1 = pp[ i1 ];
  30975. t0 = pp[ i1 - 1 ];
  30976. // check boundary cases, again
  30977. if ( t0 === undefined ) {
  30978. this._cachedIndex = 0;
  30979. return this.copySampleValue_( 0 );
  30980. }
  30981. if ( t1 === undefined ) {
  30982. i1 = pp.length;
  30983. this._cachedIndex = i1;
  30984. return this.copySampleValue_( i1 - 1 );
  30985. }
  30986. } // seek
  30987. this._cachedIndex = i1;
  30988. this.intervalChanged_( i1, t0, t1 );
  30989. } // validate_interval
  30990. return this.interpolate_( i1, t0, t, t1 );
  30991. }
  30992. /**
  30993. * Returns the interpolation settings.
  30994. *
  30995. * @return {Object} The interpolation settings.
  30996. */
  30997. getSettings_() {
  30998. return this.settings || this.DefaultSettings_;
  30999. }
  31000. /**
  31001. * Copies a sample value to the result buffer.
  31002. *
  31003. * @param {number} index - An index into the sample value buffer.
  31004. * @return {TypedArray} The result buffer.
  31005. */
  31006. copySampleValue_( index ) {
  31007. // copies a sample value to the result buffer
  31008. const result = this.resultBuffer,
  31009. values = this.sampleValues,
  31010. stride = this.valueSize,
  31011. offset = index * stride;
  31012. for ( let i = 0; i !== stride; ++ i ) {
  31013. result[ i ] = values[ offset + i ];
  31014. }
  31015. return result;
  31016. }
  31017. /**
  31018. * Copies a sample value to the result buffer.
  31019. *
  31020. * @abstract
  31021. * @param {number} i1 - An index into the sample value buffer.
  31022. * @param {number} t0 - The previous interpolation factor.
  31023. * @param {number} t - The current interpolation factor.
  31024. * @param {number} t1 - The next interpolation factor.
  31025. * @return {TypedArray} The result buffer.
  31026. */
  31027. interpolate_( /* i1, t0, t, t1 */ ) {
  31028. throw new Error( 'THREE.Interpolant: Call to abstract method.' );
  31029. // implementations shall return this.resultBuffer
  31030. }
  31031. /**
  31032. * Optional method that is executed when the interval has changed.
  31033. *
  31034. * @param {number} i1 - An index into the sample value buffer.
  31035. * @param {number} t0 - The previous interpolation factor.
  31036. * @param {number} t - The current interpolation factor.
  31037. */
  31038. intervalChanged_( /* i1, t0, t1 */ ) {
  31039. // empty
  31040. }
  31041. }
  31042. /**
  31043. * Fast and simple cubic spline interpolant.
  31044. *
  31045. * It was derived from a Hermitian construction setting the first derivative
  31046. * at each sample position to the linear slope between neighboring positions
  31047. * over their parameter interval.
  31048. *
  31049. * @augments Interpolant
  31050. */
  31051. class CubicInterpolant extends Interpolant {
  31052. /**
  31053. * Constructs a new cubic interpolant.
  31054. *
  31055. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31056. * @param {TypedArray} sampleValues - The sample values.
  31057. * @param {number} sampleSize - The sample size
  31058. * @param {TypedArray} [resultBuffer] - The result buffer.
  31059. */
  31060. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31061. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31062. this._weightPrev = -0;
  31063. this._offsetPrev = -0;
  31064. this._weightNext = -0;
  31065. this._offsetNext = -0;
  31066. this.DefaultSettings_ = {
  31067. endingStart: ZeroCurvatureEnding,
  31068. endingEnd: ZeroCurvatureEnding
  31069. };
  31070. }
  31071. intervalChanged_( i1, t0, t1 ) {
  31072. const pp = this.parameterPositions;
  31073. let iPrev = i1 - 2,
  31074. iNext = i1 + 1,
  31075. tPrev = pp[ iPrev ],
  31076. tNext = pp[ iNext ];
  31077. if ( tPrev === undefined ) {
  31078. switch ( this.getSettings_().endingStart ) {
  31079. case ZeroSlopeEnding:
  31080. // f'(t0) = 0
  31081. iPrev = i1;
  31082. tPrev = 2 * t0 - t1;
  31083. break;
  31084. case WrapAroundEnding:
  31085. // use the other end of the curve
  31086. iPrev = pp.length - 2;
  31087. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  31088. break;
  31089. default: // ZeroCurvatureEnding
  31090. // f''(t0) = 0 a.k.a. Natural Spline
  31091. iPrev = i1;
  31092. tPrev = t1;
  31093. }
  31094. }
  31095. if ( tNext === undefined ) {
  31096. switch ( this.getSettings_().endingEnd ) {
  31097. case ZeroSlopeEnding:
  31098. // f'(tN) = 0
  31099. iNext = i1;
  31100. tNext = 2 * t1 - t0;
  31101. break;
  31102. case WrapAroundEnding:
  31103. // use the other end of the curve
  31104. iNext = 1;
  31105. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  31106. break;
  31107. default: // ZeroCurvatureEnding
  31108. // f''(tN) = 0, a.k.a. Natural Spline
  31109. iNext = i1 - 1;
  31110. tNext = t0;
  31111. }
  31112. }
  31113. const halfDt = ( t1 - t0 ) * 0.5,
  31114. stride = this.valueSize;
  31115. this._weightPrev = halfDt / ( t0 - tPrev );
  31116. this._weightNext = halfDt / ( tNext - t1 );
  31117. this._offsetPrev = iPrev * stride;
  31118. this._offsetNext = iNext * stride;
  31119. }
  31120. interpolate_( i1, t0, t, t1 ) {
  31121. const result = this.resultBuffer,
  31122. values = this.sampleValues,
  31123. stride = this.valueSize,
  31124. o1 = i1 * stride, o0 = o1 - stride,
  31125. oP = this._offsetPrev, oN = this._offsetNext,
  31126. wP = this._weightPrev, wN = this._weightNext,
  31127. p = ( t - t0 ) / ( t1 - t0 ),
  31128. pp = p * p,
  31129. ppp = pp * p;
  31130. // evaluate polynomials
  31131. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  31132. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  31133. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  31134. const sN = wN * ppp - wN * pp;
  31135. // combine data linearly
  31136. for ( let i = 0; i !== stride; ++ i ) {
  31137. result[ i ] =
  31138. sP * values[ oP + i ] +
  31139. s0 * values[ o0 + i ] +
  31140. s1 * values[ o1 + i ] +
  31141. sN * values[ oN + i ];
  31142. }
  31143. return result;
  31144. }
  31145. }
  31146. /**
  31147. * A basic linear interpolant.
  31148. *
  31149. * @augments Interpolant
  31150. */
  31151. class LinearInterpolant extends Interpolant {
  31152. /**
  31153. * Constructs a new linear interpolant.
  31154. *
  31155. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31156. * @param {TypedArray} sampleValues - The sample values.
  31157. * @param {number} sampleSize - The sample size
  31158. * @param {TypedArray} [resultBuffer] - The result buffer.
  31159. */
  31160. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31161. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31162. }
  31163. interpolate_( i1, t0, t, t1 ) {
  31164. const result = this.resultBuffer,
  31165. values = this.sampleValues,
  31166. stride = this.valueSize,
  31167. offset1 = i1 * stride,
  31168. offset0 = offset1 - stride,
  31169. weight1 = ( t - t0 ) / ( t1 - t0 ),
  31170. weight0 = 1 - weight1;
  31171. for ( let i = 0; i !== stride; ++ i ) {
  31172. result[ i ] =
  31173. values[ offset0 + i ] * weight0 +
  31174. values[ offset1 + i ] * weight1;
  31175. }
  31176. return result;
  31177. }
  31178. }
  31179. /**
  31180. * Interpolant that evaluates to the sample value at the position preceding
  31181. * the parameter.
  31182. *
  31183. * @augments Interpolant
  31184. */
  31185. class DiscreteInterpolant extends Interpolant {
  31186. /**
  31187. * Constructs a new discrete interpolant.
  31188. *
  31189. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31190. * @param {TypedArray} sampleValues - The sample values.
  31191. * @param {number} sampleSize - The sample size
  31192. * @param {TypedArray} [resultBuffer] - The result buffer.
  31193. */
  31194. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31195. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31196. }
  31197. interpolate_( i1 /*, t0, t, t1 */ ) {
  31198. return this.copySampleValue_( i1 - 1 );
  31199. }
  31200. }
  31201. /**
  31202. * A Bezier interpolant using cubic Bezier curves with 2D control points.
  31203. *
  31204. * This interpolant supports the COLLADA/Maya style of Bezier animation where
  31205. * each keyframe has explicit in/out tangent control points specified as
  31206. * 2D coordinates (time, value).
  31207. *
  31208. * Tangent data is read from `inTangents` and `outTangents` on the interpolant
  31209. * (populated by `KeyframeTrack.InterpolantFactoryMethodBezier`).
  31210. *
  31211. * For a track with N keyframes and stride S:
  31212. * - Each tangent array has N * S * 2 values
  31213. * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value,
  31214. * k1_c0_time, k1_c0_value, ...]
  31215. *
  31216. * @augments Interpolant
  31217. */
  31218. class BezierInterpolant extends Interpolant {
  31219. interpolate_( i1, t0, t, t1 ) {
  31220. const result = this.resultBuffer;
  31221. const values = this.sampleValues;
  31222. const stride = this.valueSize;
  31223. const offset1 = i1 * stride;
  31224. const offset0 = offset1 - stride;
  31225. const inTangents = this.inTangents;
  31226. const outTangents = this.outTangents;
  31227. // If no tangent data, fall back to linear interpolation
  31228. if ( ! inTangents || ! outTangents ) {
  31229. const weight1 = ( t - t0 ) / ( t1 - t0 );
  31230. const weight0 = 1 - weight1;
  31231. for ( let i = 0; i !== stride; ++ i ) {
  31232. result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1;
  31233. }
  31234. return result;
  31235. }
  31236. const tangentStride = stride * 2;
  31237. const i0 = i1 - 1;
  31238. for ( let i = 0; i !== stride; ++ i ) {
  31239. const v0 = values[ offset0 + i ];
  31240. const v1 = values[ offset1 + i ];
  31241. // outTangent of previous keyframe (C0)
  31242. const outTangentOffset = i0 * tangentStride + i * 2;
  31243. const c0x = outTangents[ outTangentOffset ];
  31244. const c0y = outTangents[ outTangentOffset + 1 ];
  31245. // inTangent of current keyframe (C1)
  31246. const inTangentOffset = i1 * tangentStride + i * 2;
  31247. const c1x = inTangents[ inTangentOffset ];
  31248. const c1y = inTangents[ inTangentOffset + 1 ];
  31249. // Find the curve parameter s where the Bezier X(s) matches t, then evaluate Y(s)
  31250. const s = solveBezierParameter( t, t0, c0x, c1x, t1 );
  31251. result[ i ] = cubicBezier( s, v0, c0y, c1y, v1 );
  31252. }
  31253. return result;
  31254. }
  31255. }
  31256. function cubicBezier( s, p0, p1, p2, p3 ) {
  31257. const k = 1 - s;
  31258. return k * k * k * p0 + 3 * k * k * s * p1 + 3 * k * s * s * p2 + s * s * s * p3;
  31259. }
  31260. function cubicBezierSlope( s, p0, p1, p2, p3 ) {
  31261. const k = 1 - s;
  31262. return 3 * k * k * ( p1 - p0 ) + 6 * k * s * ( p2 - p1 ) + 3 * s * s * ( p3 - p2 );
  31263. }
  31264. // Solves cubicBezier( s, x0, x1, x2, x3 ) = x for s in [0,1] using Newton-Raphson
  31265. function solveBezierParameter( x, x0, x1, x2, x3 ) {
  31266. let s = ( x - x0 ) / ( x3 - x0 );
  31267. for ( let i = 0; i < 8; i ++ ) {
  31268. const error = cubicBezier( s, x0, x1, x2, x3 ) - x;
  31269. if ( Math.abs( error ) < 1e-10 ) break;
  31270. const slope = cubicBezierSlope( s, x0, x1, x2, x3 );
  31271. if ( Math.abs( slope ) < 1e-10 ) break;
  31272. s = Math.max( 0, Math.min( 1, s - error / slope ) );
  31273. }
  31274. return s;
  31275. }
  31276. /**
  31277. * Represents a timed sequence of keyframes, which are composed of lists of
  31278. * times and related values, and which are used to animate a specific property
  31279. * of an object.
  31280. */
  31281. class KeyframeTrack {
  31282. /**
  31283. * Constructs a new keyframe track.
  31284. *
  31285. * @param {string} name - The keyframe track's name.
  31286. * @param {Array<number>} times - A list of keyframe times.
  31287. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  31288. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type.
  31289. */
  31290. constructor( name, times, values, interpolation ) {
  31291. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  31292. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  31293. /**
  31294. * The track's name can refer to morph targets or bones or
  31295. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  31296. * for the forms of strings that can be parsed for property binding.
  31297. *
  31298. * @type {string}
  31299. */
  31300. this.name = name;
  31301. /**
  31302. * The keyframe times.
  31303. *
  31304. * @type {Float32Array}
  31305. */
  31306. this.times = convertArray( times, this.TimeBufferType );
  31307. /**
  31308. * The keyframe values.
  31309. *
  31310. * @type {Float32Array}
  31311. */
  31312. this.values = convertArray( values, this.ValueBufferType );
  31313. this.setInterpolation( interpolation || this.DefaultInterpolation );
  31314. }
  31315. /**
  31316. * Converts the keyframe track to JSON.
  31317. *
  31318. * @static
  31319. * @param {KeyframeTrack} track - The keyframe track to serialize.
  31320. * @return {Object} The serialized keyframe track as JSON.
  31321. */
  31322. static toJSON( track ) {
  31323. const trackType = track.constructor;
  31324. let json;
  31325. // derived classes can define a static toJSON method
  31326. if ( trackType.toJSON !== this.toJSON ) {
  31327. json = trackType.toJSON( track );
  31328. } else {
  31329. // by default, we assume the data can be serialized as-is
  31330. json = {
  31331. 'name': track.name,
  31332. 'times': convertArray( track.times, Array ),
  31333. 'values': convertArray( track.values, Array )
  31334. };
  31335. const interpolation = track.getInterpolation();
  31336. if ( interpolation !== track.DefaultInterpolation ) {
  31337. json.interpolation = interpolation;
  31338. }
  31339. }
  31340. json.type = track.ValueTypeName; // mandatory
  31341. return json;
  31342. }
  31343. /**
  31344. * Factory method for creating a new discrete interpolant.
  31345. *
  31346. * @static
  31347. * @param {TypedArray} [result] - The result buffer.
  31348. * @return {DiscreteInterpolant} The new interpolant.
  31349. */
  31350. InterpolantFactoryMethodDiscrete( result ) {
  31351. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31352. }
  31353. /**
  31354. * Factory method for creating a new linear interpolant.
  31355. *
  31356. * @static
  31357. * @param {TypedArray} [result] - The result buffer.
  31358. * @return {LinearInterpolant} The new interpolant.
  31359. */
  31360. InterpolantFactoryMethodLinear( result ) {
  31361. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31362. }
  31363. /**
  31364. * Factory method for creating a new smooth interpolant.
  31365. *
  31366. * @static
  31367. * @param {TypedArray} [result] - The result buffer.
  31368. * @return {CubicInterpolant} The new interpolant.
  31369. */
  31370. InterpolantFactoryMethodSmooth( result ) {
  31371. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31372. }
  31373. /**
  31374. * Factory method for creating a new Bezier interpolant.
  31375. *
  31376. * The Bezier interpolant requires tangent data to be set via the `settings` property
  31377. * on the track before creating the interpolant. The settings should contain:
  31378. * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component
  31379. * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component
  31380. *
  31381. * @static
  31382. * @param {TypedArray} [result] - The result buffer.
  31383. * @return {BezierInterpolant} The new interpolant.
  31384. */
  31385. InterpolantFactoryMethodBezier( result ) {
  31386. const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result );
  31387. if ( this.settings ) {
  31388. interpolant.inTangents = this.settings.inTangents;
  31389. interpolant.outTangents = this.settings.outTangents;
  31390. }
  31391. return interpolant;
  31392. }
  31393. /**
  31394. * Defines the interpolation factor method for this keyframe track.
  31395. *
  31396. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type.
  31397. * @return {KeyframeTrack} A reference to this keyframe track.
  31398. */
  31399. setInterpolation( interpolation ) {
  31400. let factoryMethod;
  31401. switch ( interpolation ) {
  31402. case InterpolateDiscrete:
  31403. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31404. break;
  31405. case InterpolateLinear:
  31406. factoryMethod = this.InterpolantFactoryMethodLinear;
  31407. break;
  31408. case InterpolateSmooth:
  31409. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31410. break;
  31411. case InterpolateBezier:
  31412. factoryMethod = this.InterpolantFactoryMethodBezier;
  31413. break;
  31414. }
  31415. if ( factoryMethod === undefined ) {
  31416. const message = 'unsupported interpolation for ' +
  31417. this.ValueTypeName + ' keyframe track named ' + this.name;
  31418. if ( this.createInterpolant === undefined ) {
  31419. // fall back to default, unless the default itself is messed up
  31420. if ( interpolation !== this.DefaultInterpolation ) {
  31421. this.setInterpolation( this.DefaultInterpolation );
  31422. } else {
  31423. throw new Error( message ); // fatal, in this case
  31424. }
  31425. }
  31426. warn( 'KeyframeTrack:', message );
  31427. return this;
  31428. }
  31429. this.createInterpolant = factoryMethod;
  31430. return this;
  31431. }
  31432. /**
  31433. * Returns the current interpolation type.
  31434. *
  31435. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type.
  31436. */
  31437. getInterpolation() {
  31438. switch ( this.createInterpolant ) {
  31439. case this.InterpolantFactoryMethodDiscrete:
  31440. return InterpolateDiscrete;
  31441. case this.InterpolantFactoryMethodLinear:
  31442. return InterpolateLinear;
  31443. case this.InterpolantFactoryMethodSmooth:
  31444. return InterpolateSmooth;
  31445. case this.InterpolantFactoryMethodBezier:
  31446. return InterpolateBezier;
  31447. }
  31448. }
  31449. /**
  31450. * Returns the value size.
  31451. *
  31452. * @return {number} The value size.
  31453. */
  31454. getValueSize() {
  31455. return this.values.length / this.times.length;
  31456. }
  31457. /**
  31458. * Moves all keyframes either forward or backward in time.
  31459. *
  31460. * @param {number} timeOffset - The offset to move the time values.
  31461. * @return {KeyframeTrack} A reference to this keyframe track.
  31462. */
  31463. shift( timeOffset ) {
  31464. if ( timeOffset !== 0.0 ) {
  31465. const times = this.times;
  31466. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31467. times[ i ] += timeOffset;
  31468. }
  31469. }
  31470. return this;
  31471. }
  31472. /**
  31473. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31474. *
  31475. * @param {number} timeScale - The time scale.
  31476. * @return {KeyframeTrack} A reference to this keyframe track.
  31477. */
  31478. scale( timeScale ) {
  31479. if ( timeScale !== 1.0 ) {
  31480. const times = this.times;
  31481. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31482. times[ i ] *= timeScale;
  31483. }
  31484. }
  31485. return this;
  31486. }
  31487. /**
  31488. * Removes keyframes before and after animation without changing any values within the defined time range.
  31489. *
  31490. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31491. * keys this will change their values
  31492. *
  31493. * @param {number} startTime - The start time.
  31494. * @param {number} endTime - The end time.
  31495. * @return {KeyframeTrack} A reference to this keyframe track.
  31496. */
  31497. trim( startTime, endTime ) {
  31498. const times = this.times,
  31499. nKeys = times.length;
  31500. let from = 0,
  31501. to = nKeys - 1;
  31502. while ( from !== nKeys && times[ from ] < startTime ) {
  31503. ++ from;
  31504. }
  31505. while ( to !== -1 && times[ to ] > endTime ) {
  31506. -- to;
  31507. }
  31508. ++ to; // inclusive -> exclusive bound
  31509. if ( from !== 0 || to !== nKeys ) {
  31510. // empty tracks are forbidden, so keep at least one keyframe
  31511. if ( from >= to ) {
  31512. to = Math.max( to, 1 );
  31513. from = to - 1;
  31514. }
  31515. const stride = this.getValueSize();
  31516. this.times = times.slice( from, to );
  31517. this.values = this.values.slice( from * stride, to * stride );
  31518. }
  31519. return this;
  31520. }
  31521. /**
  31522. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31523. * are valid.
  31524. *
  31525. * @return {boolean} Whether the keyframes are valid or not.
  31526. */
  31527. validate() {
  31528. let valid = true;
  31529. const valueSize = this.getValueSize();
  31530. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31531. error( 'KeyframeTrack: Invalid value size in track.', this );
  31532. valid = false;
  31533. }
  31534. const times = this.times,
  31535. values = this.values,
  31536. nKeys = times.length;
  31537. if ( nKeys === 0 ) {
  31538. error( 'KeyframeTrack: Track is empty.', this );
  31539. valid = false;
  31540. }
  31541. let prevTime = null;
  31542. for ( let i = 0; i !== nKeys; i ++ ) {
  31543. const currTime = times[ i ];
  31544. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31545. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31546. valid = false;
  31547. break;
  31548. }
  31549. if ( prevTime !== null && prevTime > currTime ) {
  31550. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31551. valid = false;
  31552. break;
  31553. }
  31554. prevTime = currTime;
  31555. }
  31556. if ( values !== undefined ) {
  31557. if ( isTypedArray( values ) ) {
  31558. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31559. const value = values[ i ];
  31560. if ( isNaN( value ) ) {
  31561. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31562. valid = false;
  31563. break;
  31564. }
  31565. }
  31566. }
  31567. }
  31568. return valid;
  31569. }
  31570. /**
  31571. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31572. * common in morph target sequences).
  31573. *
  31574. * @return {KeyframeTrack} A reference to this keyframe track.
  31575. */
  31576. optimize() {
  31577. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31578. // times or values may be shared with other tracks, so overwriting is unsafe
  31579. const times = this.times.slice(),
  31580. values = this.values.slice(),
  31581. stride = this.getValueSize(),
  31582. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31583. lastIndex = times.length - 1;
  31584. let writeIndex = 1;
  31585. for ( let i = 1; i < lastIndex; ++ i ) {
  31586. let keep = false;
  31587. const time = times[ i ];
  31588. const timeNext = times[ i + 1 ];
  31589. // remove adjacent keyframes scheduled at the same time
  31590. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31591. if ( ! smoothInterpolation ) {
  31592. // remove unnecessary keyframes same as their neighbors
  31593. const offset = i * stride,
  31594. offsetP = offset - stride,
  31595. offsetN = offset + stride;
  31596. for ( let j = 0; j !== stride; ++ j ) {
  31597. const value = values[ offset + j ];
  31598. if ( value !== values[ offsetP + j ] ||
  31599. value !== values[ offsetN + j ] ) {
  31600. keep = true;
  31601. break;
  31602. }
  31603. }
  31604. } else {
  31605. keep = true;
  31606. }
  31607. }
  31608. // in-place compaction
  31609. if ( keep ) {
  31610. if ( i !== writeIndex ) {
  31611. times[ writeIndex ] = times[ i ];
  31612. const readOffset = i * stride,
  31613. writeOffset = writeIndex * stride;
  31614. for ( let j = 0; j !== stride; ++ j ) {
  31615. values[ writeOffset + j ] = values[ readOffset + j ];
  31616. }
  31617. }
  31618. ++ writeIndex;
  31619. }
  31620. }
  31621. // flush last keyframe (compaction looks ahead)
  31622. if ( lastIndex > 0 ) {
  31623. times[ writeIndex ] = times[ lastIndex ];
  31624. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31625. values[ writeOffset + j ] = values[ readOffset + j ];
  31626. }
  31627. ++ writeIndex;
  31628. }
  31629. if ( writeIndex !== times.length ) {
  31630. this.times = times.slice( 0, writeIndex );
  31631. this.values = values.slice( 0, writeIndex * stride );
  31632. } else {
  31633. this.times = times;
  31634. this.values = values;
  31635. }
  31636. return this;
  31637. }
  31638. /**
  31639. * Returns a new keyframe track with copied values from this instance.
  31640. *
  31641. * @return {KeyframeTrack} A clone of this instance.
  31642. */
  31643. clone() {
  31644. const times = this.times.slice();
  31645. const values = this.values.slice();
  31646. const TypedKeyframeTrack = this.constructor;
  31647. const track = new TypedKeyframeTrack( this.name, times, values );
  31648. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31649. track.createInterpolant = this.createInterpolant;
  31650. return track;
  31651. }
  31652. }
  31653. /**
  31654. * The value type name.
  31655. *
  31656. * @type {string}
  31657. * @default ''
  31658. */
  31659. KeyframeTrack.prototype.ValueTypeName = '';
  31660. /**
  31661. * The time buffer type of this keyframe track.
  31662. *
  31663. * @type {TypedArray|Array}
  31664. * @default Float32Array.constructor
  31665. */
  31666. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31667. /**
  31668. * The value buffer type of this keyframe track.
  31669. *
  31670. * @type {TypedArray|Array}
  31671. * @default Float32Array.constructor
  31672. */
  31673. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31674. /**
  31675. * The default interpolation type of this keyframe track.
  31676. *
  31677. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)}
  31678. * @default InterpolateLinear
  31679. */
  31680. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31681. /**
  31682. * A track for boolean keyframe values.
  31683. *
  31684. * @augments KeyframeTrack
  31685. */
  31686. class BooleanKeyframeTrack extends KeyframeTrack {
  31687. /**
  31688. * Constructs a new boolean keyframe track.
  31689. *
  31690. * This keyframe track type has no `interpolation` parameter because the
  31691. * interpolation is always discrete.
  31692. *
  31693. * @param {string} name - The keyframe track's name.
  31694. * @param {Array<number>} times - A list of keyframe times.
  31695. * @param {Array<boolean>} values - A list of keyframe values.
  31696. */
  31697. constructor( name, times, values ) {
  31698. super( name, times, values );
  31699. }
  31700. }
  31701. /**
  31702. * The value type name.
  31703. *
  31704. * @type {string}
  31705. * @default 'bool'
  31706. */
  31707. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31708. /**
  31709. * The value buffer type of this keyframe track.
  31710. *
  31711. * @type {TypedArray|Array}
  31712. * @default Array.constructor
  31713. */
  31714. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31715. /**
  31716. * The default interpolation type of this keyframe track.
  31717. *
  31718. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31719. * @default InterpolateDiscrete
  31720. */
  31721. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31722. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31723. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31724. /**
  31725. * A track for color keyframe values.
  31726. *
  31727. * @augments KeyframeTrack
  31728. */
  31729. class ColorKeyframeTrack extends KeyframeTrack {
  31730. /**
  31731. * Constructs a new color keyframe track.
  31732. *
  31733. * @param {string} name - The keyframe track's name.
  31734. * @param {Array<number>} times - A list of keyframe times.
  31735. * @param {Array<number>} values - A list of keyframe values.
  31736. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31737. */
  31738. constructor( name, times, values, interpolation ) {
  31739. super( name, times, values, interpolation );
  31740. }
  31741. }
  31742. /**
  31743. * The value type name.
  31744. *
  31745. * @type {string}
  31746. * @default 'color'
  31747. */
  31748. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31749. /**
  31750. * A track for numeric keyframe values.
  31751. *
  31752. * @augments KeyframeTrack
  31753. */
  31754. class NumberKeyframeTrack extends KeyframeTrack {
  31755. /**
  31756. * Constructs a new number keyframe track.
  31757. *
  31758. * @param {string} name - The keyframe track's name.
  31759. * @param {Array<number>} times - A list of keyframe times.
  31760. * @param {Array<number>} values - A list of keyframe values.
  31761. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31762. */
  31763. constructor( name, times, values, interpolation ) {
  31764. super( name, times, values, interpolation );
  31765. }
  31766. }
  31767. /**
  31768. * The value type name.
  31769. *
  31770. * @type {string}
  31771. * @default 'number'
  31772. */
  31773. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31774. /**
  31775. * Spherical linear unit quaternion interpolant.
  31776. *
  31777. * @augments Interpolant
  31778. */
  31779. class QuaternionLinearInterpolant extends Interpolant {
  31780. /**
  31781. * Constructs a new SLERP interpolant.
  31782. *
  31783. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31784. * @param {TypedArray} sampleValues - The sample values.
  31785. * @param {number} sampleSize - The sample size
  31786. * @param {TypedArray} [resultBuffer] - The result buffer.
  31787. */
  31788. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31789. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31790. }
  31791. interpolate_( i1, t0, t, t1 ) {
  31792. const result = this.resultBuffer,
  31793. values = this.sampleValues,
  31794. stride = this.valueSize,
  31795. alpha = ( t - t0 ) / ( t1 - t0 );
  31796. let offset = i1 * stride;
  31797. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31798. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31799. }
  31800. return result;
  31801. }
  31802. }
  31803. /**
  31804. * A track for Quaternion keyframe values.
  31805. *
  31806. * @augments KeyframeTrack
  31807. */
  31808. class QuaternionKeyframeTrack extends KeyframeTrack {
  31809. /**
  31810. * Constructs a new Quaternion keyframe track.
  31811. *
  31812. * @param {string} name - The keyframe track's name.
  31813. * @param {Array<number>} times - A list of keyframe times.
  31814. * @param {Array<number>} values - A list of keyframe values.
  31815. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31816. */
  31817. constructor( name, times, values, interpolation ) {
  31818. super( name, times, values, interpolation );
  31819. }
  31820. /**
  31821. * Overwritten so the method returns Quaternion based interpolant.
  31822. *
  31823. * @static
  31824. * @param {TypedArray} [result] - The result buffer.
  31825. * @return {QuaternionLinearInterpolant} The new interpolant.
  31826. */
  31827. InterpolantFactoryMethodLinear( result ) {
  31828. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31829. }
  31830. }
  31831. /**
  31832. * The value type name.
  31833. *
  31834. * @type {string}
  31835. * @default 'quaternion'
  31836. */
  31837. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31838. // ValueBufferType is inherited
  31839. // DefaultInterpolation is inherited;
  31840. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31841. /**
  31842. * A track for string keyframe values.
  31843. *
  31844. * @augments KeyframeTrack
  31845. */
  31846. class StringKeyframeTrack extends KeyframeTrack {
  31847. /**
  31848. * Constructs a new string keyframe track.
  31849. *
  31850. * This keyframe track type has no `interpolation` parameter because the
  31851. * interpolation is always discrete.
  31852. *
  31853. * @param {string} name - The keyframe track's name.
  31854. * @param {Array<number>} times - A list of keyframe times.
  31855. * @param {Array<string>} values - A list of keyframe values.
  31856. */
  31857. constructor( name, times, values ) {
  31858. super( name, times, values );
  31859. }
  31860. }
  31861. /**
  31862. * The value type name.
  31863. *
  31864. * @type {string}
  31865. * @default 'string'
  31866. */
  31867. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31868. /**
  31869. * The value buffer type of this keyframe track.
  31870. *
  31871. * @type {TypedArray|Array}
  31872. * @default Array.constructor
  31873. */
  31874. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31875. /**
  31876. * The default interpolation type of this keyframe track.
  31877. *
  31878. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31879. * @default InterpolateDiscrete
  31880. */
  31881. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31882. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31883. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31884. /**
  31885. * A track for vector keyframe values.
  31886. *
  31887. * @augments KeyframeTrack
  31888. */
  31889. class VectorKeyframeTrack extends KeyframeTrack {
  31890. /**
  31891. * Constructs a new vector keyframe track.
  31892. *
  31893. * @param {string} name - The keyframe track's name.
  31894. * @param {Array<number>} times - A list of keyframe times.
  31895. * @param {Array<number>} values - A list of keyframe values.
  31896. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31897. */
  31898. constructor( name, times, values, interpolation ) {
  31899. super( name, times, values, interpolation );
  31900. }
  31901. }
  31902. /**
  31903. * The value type name.
  31904. *
  31905. * @type {string}
  31906. * @default 'vector'
  31907. */
  31908. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31909. /**
  31910. * A reusable set of keyframe tracks which represent an animation.
  31911. */
  31912. class AnimationClip {
  31913. /**
  31914. * Constructs a new animation clip.
  31915. *
  31916. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31917. * use the static interface of this class for creating clips. In most cases though, animation clips
  31918. * will automatically be created by loaders when importing animated 3D assets.
  31919. *
  31920. * @param {string} [name=''] - The clip's name.
  31921. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31922. * the duration will be calculated from the passed keyframes.
  31923. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31924. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31925. * is blended/combined when two or more animations are simultaneously played.
  31926. */
  31927. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31928. /**
  31929. * The clip's name.
  31930. *
  31931. * @type {string}
  31932. */
  31933. this.name = name;
  31934. /**
  31935. * An array of keyframe tracks.
  31936. *
  31937. * @type {Array<KeyframeTrack>}
  31938. */
  31939. this.tracks = tracks;
  31940. /**
  31941. * The clip's duration in seconds.
  31942. *
  31943. * @type {number}
  31944. */
  31945. this.duration = duration;
  31946. /**
  31947. * Defines how the animation is blended/combined when two or more animations
  31948. * are simultaneously played.
  31949. *
  31950. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31951. */
  31952. this.blendMode = blendMode;
  31953. /**
  31954. * The UUID of the animation clip.
  31955. *
  31956. * @type {string}
  31957. * @readonly
  31958. */
  31959. this.uuid = generateUUID();
  31960. /**
  31961. * An object that can be used to store custom data about the animation clip.
  31962. * It should not hold references to functions as these will not be cloned.
  31963. *
  31964. * @type {Object}
  31965. */
  31966. this.userData = {};
  31967. // this means it should figure out its duration by scanning the tracks
  31968. if ( this.duration < 0 ) {
  31969. this.resetDuration();
  31970. }
  31971. }
  31972. /**
  31973. * Factory method for creating an animation clip from the given JSON.
  31974. *
  31975. * @static
  31976. * @param {Object} json - The serialized animation clip.
  31977. * @return {AnimationClip} The new animation clip.
  31978. */
  31979. static parse( json ) {
  31980. const tracks = [],
  31981. jsonTracks = json.tracks,
  31982. frameTime = 1.0 / ( json.fps || 1.0 );
  31983. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31984. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31985. }
  31986. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31987. clip.uuid = json.uuid;
  31988. clip.userData = JSON.parse( json.userData || '{}' );
  31989. return clip;
  31990. }
  31991. /**
  31992. * Serializes the given animation clip into JSON.
  31993. *
  31994. * @static
  31995. * @param {AnimationClip} clip - The animation clip to serialize.
  31996. * @return {Object} The JSON object.
  31997. */
  31998. static toJSON( clip ) {
  31999. const tracks = [],
  32000. clipTracks = clip.tracks;
  32001. const json = {
  32002. 'name': clip.name,
  32003. 'duration': clip.duration,
  32004. 'tracks': tracks,
  32005. 'uuid': clip.uuid,
  32006. 'blendMode': clip.blendMode,
  32007. 'userData': JSON.stringify( clip.userData ),
  32008. };
  32009. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  32010. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  32011. }
  32012. return json;
  32013. }
  32014. /**
  32015. * Returns a new animation clip from the passed morph targets array of a
  32016. * geometry, taking a name and the number of frames per second.
  32017. *
  32018. * Note: The fps parameter is required, but the animation speed can be
  32019. * overridden via {@link AnimationAction#setDuration}.
  32020. *
  32021. * @static
  32022. * @param {string} name - The name of the animation clip.
  32023. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  32024. * @param {number} fps - The Frames-Per-Second value.
  32025. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  32026. * @return {AnimationClip} The new animation clip.
  32027. */
  32028. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  32029. const numMorphTargets = morphTargetSequence.length;
  32030. const tracks = [];
  32031. for ( let i = 0; i < numMorphTargets; i ++ ) {
  32032. let times = [];
  32033. let values = [];
  32034. times.push(
  32035. ( i + numMorphTargets - 1 ) % numMorphTargets,
  32036. i,
  32037. ( i + 1 ) % numMorphTargets );
  32038. values.push( 0, 1, 0 );
  32039. const order = getKeyframeOrder( times );
  32040. times = sortedArray( times, 1, order );
  32041. values = sortedArray( values, 1, order );
  32042. // if there is a key at the first frame, duplicate it as the
  32043. // last frame as well for perfect loop.
  32044. if ( ! noLoop && times[ 0 ] === 0 ) {
  32045. times.push( numMorphTargets );
  32046. values.push( values[ 0 ] );
  32047. }
  32048. tracks.push(
  32049. new NumberKeyframeTrack(
  32050. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  32051. times, values
  32052. ).scale( 1.0 / fps ) );
  32053. }
  32054. return new this( name, -1, tracks );
  32055. }
  32056. /**
  32057. * Searches for an animation clip by name, taking as its first parameter
  32058. * either an array of clips, or a mesh or geometry that contains an
  32059. * array named "animations" property.
  32060. *
  32061. * @static
  32062. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  32063. * @param {string} name - The name to search for.
  32064. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  32065. */
  32066. static findByName( objectOrClipArray, name ) {
  32067. let clipArray = objectOrClipArray;
  32068. if ( ! Array.isArray( objectOrClipArray ) ) {
  32069. const o = objectOrClipArray;
  32070. clipArray = o.geometry && o.geometry.animations || o.animations;
  32071. }
  32072. for ( let i = 0; i < clipArray.length; i ++ ) {
  32073. if ( clipArray[ i ].name === name ) {
  32074. return clipArray[ i ];
  32075. }
  32076. }
  32077. return null;
  32078. }
  32079. /**
  32080. * Returns an array of new AnimationClips created from the morph target
  32081. * sequences of a geometry, trying to sort morph target names into
  32082. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  32083. *
  32084. * See {@link MD2Loader#parse} as an example for how the method should be used.
  32085. *
  32086. * @static
  32087. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  32088. * @param {number} fps - The Frames-Per-Second value.
  32089. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  32090. * @return {Array<AnimationClip>} An array of new animation clips.
  32091. */
  32092. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  32093. const animationToMorphTargets = {};
  32094. // tested with https://regex101.com/ on trick sequences
  32095. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  32096. const pattern = /^([\w-]*?)([\d]+)$/;
  32097. // sort morph target names into animation groups based
  32098. // patterns like Walk_001, Walk_002, Run_001, Run_002
  32099. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  32100. const morphTarget = morphTargets[ i ];
  32101. const parts = morphTarget.name.match( pattern );
  32102. if ( parts && parts.length > 1 ) {
  32103. const name = parts[ 1 ];
  32104. let animationMorphTargets = animationToMorphTargets[ name ];
  32105. if ( ! animationMorphTargets ) {
  32106. animationToMorphTargets[ name ] = animationMorphTargets = [];
  32107. }
  32108. animationMorphTargets.push( morphTarget );
  32109. }
  32110. }
  32111. const clips = [];
  32112. for ( const name in animationToMorphTargets ) {
  32113. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  32114. }
  32115. return clips;
  32116. }
  32117. /**
  32118. * Sets the duration of this clip to the duration of its longest keyframe track.
  32119. *
  32120. * @return {AnimationClip} A reference to this animation clip.
  32121. */
  32122. resetDuration() {
  32123. const tracks = this.tracks;
  32124. let duration = 0;
  32125. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  32126. const track = this.tracks[ i ];
  32127. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  32128. }
  32129. this.duration = duration;
  32130. return this;
  32131. }
  32132. /**
  32133. * Trims all tracks to the clip's duration.
  32134. *
  32135. * @return {AnimationClip} A reference to this animation clip.
  32136. */
  32137. trim() {
  32138. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32139. this.tracks[ i ].trim( 0, this.duration );
  32140. }
  32141. return this;
  32142. }
  32143. /**
  32144. * Performs minimal validation on each track in the clip. Returns `true` if all
  32145. * tracks are valid.
  32146. *
  32147. * @return {boolean} Whether the clip's keyframes are valid or not.
  32148. */
  32149. validate() {
  32150. let valid = true;
  32151. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32152. valid = valid && this.tracks[ i ].validate();
  32153. }
  32154. return valid;
  32155. }
  32156. /**
  32157. * Optimizes each track by removing equivalent sequential keys (which are
  32158. * common in morph target sequences).
  32159. *
  32160. * @return {AnimationClip} A reference to this animation clip.
  32161. */
  32162. optimize() {
  32163. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32164. this.tracks[ i ].optimize();
  32165. }
  32166. return this;
  32167. }
  32168. /**
  32169. * Returns a new animation clip with copied values from this instance.
  32170. *
  32171. * @return {AnimationClip} A clone of this instance.
  32172. */
  32173. clone() {
  32174. const tracks = [];
  32175. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32176. tracks.push( this.tracks[ i ].clone() );
  32177. }
  32178. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  32179. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  32180. return clip;
  32181. }
  32182. /**
  32183. * Serializes this animation clip into JSON.
  32184. *
  32185. * @return {Object} The JSON object.
  32186. */
  32187. toJSON() {
  32188. return this.constructor.toJSON( this );
  32189. }
  32190. }
  32191. function getTrackTypeForValueTypeName( typeName ) {
  32192. switch ( typeName.toLowerCase() ) {
  32193. case 'scalar':
  32194. case 'double':
  32195. case 'float':
  32196. case 'number':
  32197. case 'integer':
  32198. return NumberKeyframeTrack;
  32199. case 'vector':
  32200. case 'vector2':
  32201. case 'vector3':
  32202. case 'vector4':
  32203. return VectorKeyframeTrack;
  32204. case 'color':
  32205. return ColorKeyframeTrack;
  32206. case 'quaternion':
  32207. return QuaternionKeyframeTrack;
  32208. case 'bool':
  32209. case 'boolean':
  32210. return BooleanKeyframeTrack;
  32211. case 'string':
  32212. return StringKeyframeTrack;
  32213. }
  32214. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  32215. }
  32216. function parseKeyframeTrack( json ) {
  32217. if ( json.type === undefined ) {
  32218. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  32219. }
  32220. const trackType = getTrackTypeForValueTypeName( json.type );
  32221. if ( json.times === undefined ) {
  32222. const times = [], values = [];
  32223. flattenJSON( json.keys, times, values, 'value' );
  32224. json.times = times;
  32225. json.values = values;
  32226. }
  32227. // derived classes can define a static parse method
  32228. if ( trackType.parse !== undefined ) {
  32229. return trackType.parse( json );
  32230. } else {
  32231. // by default, we assume a constructor compatible with the base
  32232. return new trackType( json.name, json.times, json.values, json.interpolation );
  32233. }
  32234. }
  32235. /**
  32236. * @class
  32237. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  32238. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  32239. * @hideconstructor
  32240. */
  32241. const Cache = {
  32242. /**
  32243. * Whether caching is enabled or not.
  32244. *
  32245. * @static
  32246. * @type {boolean}
  32247. * @default false
  32248. */
  32249. enabled: false,
  32250. /**
  32251. * A dictionary that holds cached files.
  32252. *
  32253. * @static
  32254. * @type {Object<string,Object>}
  32255. */
  32256. files: {},
  32257. /**
  32258. * Adds a cache entry with a key to reference the file. If this key already
  32259. * holds a file, it is overwritten.
  32260. *
  32261. * @static
  32262. * @param {string} key - The key to reference the cached file.
  32263. * @param {Object} file - The file to be cached.
  32264. */
  32265. add: function ( key, file ) {
  32266. if ( this.enabled === false ) return;
  32267. if ( isBlobURL( key ) ) return;
  32268. // log( 'Cache', 'Adding key:', key );
  32269. this.files[ key ] = file;
  32270. },
  32271. /**
  32272. * Gets the cached value for the given key.
  32273. *
  32274. * @static
  32275. * @param {string} key - The key to reference the cached file.
  32276. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  32277. */
  32278. get: function ( key ) {
  32279. if ( this.enabled === false ) return;
  32280. if ( isBlobURL( key ) ) return;
  32281. // log( 'Cache', 'Checking key:', key );
  32282. return this.files[ key ];
  32283. },
  32284. /**
  32285. * Removes the cached file associated with the given key.
  32286. *
  32287. * @static
  32288. * @param {string} key - The key to reference the cached file.
  32289. */
  32290. remove: function ( key ) {
  32291. delete this.files[ key ];
  32292. },
  32293. /**
  32294. * Remove all values from the cache.
  32295. *
  32296. * @static
  32297. */
  32298. clear: function () {
  32299. this.files = {};
  32300. }
  32301. };
  32302. /**
  32303. * Returns true if the given cache key contains the blob: scheme.
  32304. *
  32305. * @private
  32306. * @param {string} key - The cache key.
  32307. * @return {boolean} Whether the given cache key contains the blob: scheme or not.
  32308. */
  32309. function isBlobURL( key ) {
  32310. try {
  32311. const urlString = key.slice( key.indexOf( ':' ) + 1 ); // remove type identifier
  32312. const url = new URL( urlString );
  32313. return url.protocol === 'blob:';
  32314. } catch ( e ) {
  32315. // If the string is not a valid URL, it throws an error
  32316. return false;
  32317. }
  32318. }
  32319. /**
  32320. * Handles and keeps track of loaded and pending data. A default global
  32321. * instance of this class is created and used by loaders if not supplied
  32322. * manually.
  32323. *
  32324. * In general that should be sufficient, however there are times when it can
  32325. * be useful to have separate loaders - for example if you want to show
  32326. * separate loading bars for objects and textures.
  32327. *
  32328. * ```js
  32329. * const manager = new THREE.LoadingManager();
  32330. * manager.onLoad = () => console.log( 'Loading complete!' );
  32331. *
  32332. * const loader1 = new OBJLoader( manager );
  32333. * const loader2 = new ColladaLoader( manager );
  32334. * ```
  32335. */
  32336. class LoadingManager {
  32337. /**
  32338. * Constructs a new loading manager.
  32339. *
  32340. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32341. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32342. * @param {Function} [onError] - Executes when an error occurs.
  32343. */
  32344. constructor( onLoad, onProgress, onError ) {
  32345. const scope = this;
  32346. let isLoading = false;
  32347. let itemsLoaded = 0;
  32348. let itemsTotal = 0;
  32349. let urlModifier = undefined;
  32350. const handlers = [];
  32351. // Refer to #5689 for the reason why we don't set .onStart
  32352. // in the constructor
  32353. /**
  32354. * Executes when an item starts loading.
  32355. *
  32356. * @type {Function|undefined}
  32357. * @default undefined
  32358. */
  32359. this.onStart = undefined;
  32360. /**
  32361. * Executes when all items have been loaded.
  32362. *
  32363. * @type {Function|undefined}
  32364. * @default undefined
  32365. */
  32366. this.onLoad = onLoad;
  32367. /**
  32368. * Executes when single items have been loaded.
  32369. *
  32370. * @type {Function|undefined}
  32371. * @default undefined
  32372. */
  32373. this.onProgress = onProgress;
  32374. /**
  32375. * Executes when an error occurs.
  32376. *
  32377. * @type {Function|undefined}
  32378. * @default undefined
  32379. */
  32380. this.onError = onError;
  32381. /**
  32382. * Used for aborting ongoing requests in loaders using this manager.
  32383. *
  32384. * @private
  32385. * @type {AbortController | null}
  32386. */
  32387. this._abortController = null;
  32388. /**
  32389. * This should be called by any loader using the manager when the loader
  32390. * starts loading an item.
  32391. *
  32392. * @param {string} url - The URL to load.
  32393. */
  32394. this.itemStart = function ( url ) {
  32395. itemsTotal ++;
  32396. if ( isLoading === false ) {
  32397. if ( scope.onStart !== undefined ) {
  32398. scope.onStart( url, itemsLoaded, itemsTotal );
  32399. }
  32400. }
  32401. isLoading = true;
  32402. };
  32403. /**
  32404. * This should be called by any loader using the manager when the loader
  32405. * ended loading an item.
  32406. *
  32407. * @param {string} url - The URL of the loaded item.
  32408. */
  32409. this.itemEnd = function ( url ) {
  32410. itemsLoaded ++;
  32411. if ( scope.onProgress !== undefined ) {
  32412. scope.onProgress( url, itemsLoaded, itemsTotal );
  32413. }
  32414. if ( itemsLoaded === itemsTotal ) {
  32415. isLoading = false;
  32416. if ( scope.onLoad !== undefined ) {
  32417. scope.onLoad();
  32418. }
  32419. }
  32420. };
  32421. /**
  32422. * This should be called by any loader using the manager when the loader
  32423. * encounters an error when loading an item.
  32424. *
  32425. * @param {string} url - The URL of the item that produces an error.
  32426. */
  32427. this.itemError = function ( url ) {
  32428. if ( scope.onError !== undefined ) {
  32429. scope.onError( url );
  32430. }
  32431. };
  32432. /**
  32433. * Given a URL, uses the URL modifier callback (if any) and returns a
  32434. * resolved URL. If no URL modifier is set, returns the original URL.
  32435. *
  32436. * @param {string} url - The URL to load.
  32437. * @return {string} The resolved URL.
  32438. */
  32439. this.resolveURL = function ( url ) {
  32440. // Normalize to NFC so that Unicode URIs (e.g. from glTF)
  32441. // are percent-encoded correctly per RFC 3987.
  32442. url = url.normalize( 'NFC' );
  32443. if ( urlModifier ) {
  32444. return urlModifier( url );
  32445. }
  32446. return url;
  32447. };
  32448. /**
  32449. * If provided, the callback will be passed each resource URL before a
  32450. * request is sent. The callback may return the original URL, or a new URL to
  32451. * override loading behavior. This behavior can be used to load assets from
  32452. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32453. *
  32454. * ```js
  32455. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32456. *
  32457. * const manager = new THREE.LoadingManager();
  32458. *
  32459. * // Initialize loading manager with URL callback.
  32460. * const objectURLs = [];
  32461. * manager.setURLModifier( ( url ) => {
  32462. *
  32463. * url = URL.createObjectURL( blobs[ url ] );
  32464. * objectURLs.push( url );
  32465. * return url;
  32466. *
  32467. * } );
  32468. *
  32469. * // Load as usual, then revoke the blob URLs.
  32470. * const loader = new GLTFLoader( manager );
  32471. * loader.load( 'fish.gltf', (gltf) => {
  32472. *
  32473. * scene.add( gltf.scene );
  32474. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32475. *
  32476. * } );
  32477. * ```
  32478. *
  32479. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32480. * @return {LoadingManager} A reference to this loading manager.
  32481. */
  32482. this.setURLModifier = function ( transform ) {
  32483. urlModifier = transform;
  32484. return this;
  32485. };
  32486. /**
  32487. * Registers a loader with the given regular expression. Can be used to
  32488. * define what loader should be used in order to load specific files. A
  32489. * typical use case is to overwrite the default loader for textures.
  32490. *
  32491. * ```js
  32492. * // add handler for TGA textures
  32493. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32494. * ```
  32495. *
  32496. * @param {string} regex - A regular expression.
  32497. * @param {Loader} loader - A loader that should handle matched cases.
  32498. * @return {LoadingManager} A reference to this loading manager.
  32499. */
  32500. this.addHandler = function ( regex, loader ) {
  32501. handlers.push( regex, loader );
  32502. return this;
  32503. };
  32504. /**
  32505. * Removes the loader for the given regular expression.
  32506. *
  32507. * @param {string} regex - A regular expression.
  32508. * @return {LoadingManager} A reference to this loading manager.
  32509. */
  32510. this.removeHandler = function ( regex ) {
  32511. const index = handlers.indexOf( regex );
  32512. if ( index !== -1 ) {
  32513. handlers.splice( index, 2 );
  32514. }
  32515. return this;
  32516. };
  32517. /**
  32518. * Can be used to retrieve the registered loader for the given file path.
  32519. *
  32520. * @param {string} file - The file path.
  32521. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32522. */
  32523. this.getHandler = function ( file ) {
  32524. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32525. const regex = handlers[ i ];
  32526. const loader = handlers[ i + 1 ];
  32527. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32528. if ( regex.test( file ) ) {
  32529. return loader;
  32530. }
  32531. }
  32532. return null;
  32533. };
  32534. /**
  32535. * Can be used to abort ongoing loading requests in loaders using this manager.
  32536. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32537. * is supported in the browser.
  32538. *
  32539. * @return {LoadingManager} A reference to this loading manager.
  32540. */
  32541. this.abort = function () {
  32542. this.abortController.abort();
  32543. this._abortController = null;
  32544. return this;
  32545. };
  32546. }
  32547. // TODO: Revert this back to a single member variable once this issue has been fixed
  32548. // https://github.com/cloudflare/workerd/issues/3657
  32549. /**
  32550. * Used for aborting ongoing requests in loaders using this manager.
  32551. *
  32552. * @type {AbortController}
  32553. */
  32554. get abortController() {
  32555. if ( ! this._abortController ) {
  32556. this._abortController = new AbortController();
  32557. }
  32558. return this._abortController;
  32559. }
  32560. }
  32561. /**
  32562. * The global default loading manager.
  32563. *
  32564. * @constant
  32565. * @type {LoadingManager}
  32566. */
  32567. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32568. /**
  32569. * Abstract base class for loaders.
  32570. *
  32571. * @abstract
  32572. */
  32573. class Loader {
  32574. /**
  32575. * Constructs a new loader.
  32576. *
  32577. * @param {LoadingManager} [manager] - The loading manager.
  32578. */
  32579. constructor( manager ) {
  32580. /**
  32581. * The loading manager.
  32582. *
  32583. * @type {LoadingManager}
  32584. * @default DefaultLoadingManager
  32585. */
  32586. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32587. /**
  32588. * The crossOrigin string to implement CORS for loading the url from a
  32589. * different domain that allows CORS.
  32590. *
  32591. * @type {string}
  32592. * @default 'anonymous'
  32593. */
  32594. this.crossOrigin = 'anonymous';
  32595. /**
  32596. * Whether the XMLHttpRequest uses credentials.
  32597. *
  32598. * @type {boolean}
  32599. * @default false
  32600. */
  32601. this.withCredentials = false;
  32602. /**
  32603. * The base path from which the asset will be loaded.
  32604. *
  32605. * @type {string}
  32606. */
  32607. this.path = '';
  32608. /**
  32609. * The base path from which additional resources like textures will be loaded.
  32610. *
  32611. * @type {string}
  32612. */
  32613. this.resourcePath = '';
  32614. /**
  32615. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32616. * used in HTTP request.
  32617. *
  32618. * @type {Object<string, any>}
  32619. */
  32620. this.requestHeader = {};
  32621. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32622. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32623. }
  32624. }
  32625. /**
  32626. * This method needs to be implemented by all concrete loaders. It holds the
  32627. * logic for loading assets from the backend.
  32628. *
  32629. * @abstract
  32630. * @param {string} url - The path/URL of the file to be loaded.
  32631. * @param {Function} onLoad - Executed when the loading process has been finished.
  32632. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32633. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32634. */
  32635. load( /* url, onLoad, onProgress, onError */ ) {}
  32636. /**
  32637. * A async version of {@link Loader#load}.
  32638. *
  32639. * @param {string} url - The path/URL of the file to be loaded.
  32640. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32641. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32642. */
  32643. loadAsync( url, onProgress ) {
  32644. const scope = this;
  32645. return new Promise( function ( resolve, reject ) {
  32646. scope.load( url, resolve, onProgress, reject );
  32647. } );
  32648. }
  32649. /**
  32650. * This method needs to be implemented by all concrete loaders. It holds the
  32651. * logic for parsing the asset into three.js entities.
  32652. *
  32653. * @abstract
  32654. * @param {any} data - The data to parse.
  32655. */
  32656. parse( /* data */ ) {}
  32657. /**
  32658. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32659. * from a different domain that allows CORS.
  32660. *
  32661. * @param {string} crossOrigin - The `crossOrigin` value.
  32662. * @return {Loader} A reference to this instance.
  32663. */
  32664. setCrossOrigin( crossOrigin ) {
  32665. this.crossOrigin = crossOrigin;
  32666. return this;
  32667. }
  32668. /**
  32669. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32670. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32671. *
  32672. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32673. *
  32674. * @param {boolean} value - The `withCredentials` value.
  32675. * @return {Loader} A reference to this instance.
  32676. */
  32677. setWithCredentials( value ) {
  32678. this.withCredentials = value;
  32679. return this;
  32680. }
  32681. /**
  32682. * Sets the base path for the asset.
  32683. *
  32684. * @param {string} path - The base path.
  32685. * @return {Loader} A reference to this instance.
  32686. */
  32687. setPath( path ) {
  32688. this.path = path;
  32689. return this;
  32690. }
  32691. /**
  32692. * Sets the base path for dependent resources like textures.
  32693. *
  32694. * @param {string} resourcePath - The resource path.
  32695. * @return {Loader} A reference to this instance.
  32696. */
  32697. setResourcePath( resourcePath ) {
  32698. this.resourcePath = resourcePath;
  32699. return this;
  32700. }
  32701. /**
  32702. * Sets the given request header.
  32703. *
  32704. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32705. * for configuring the HTTP request.
  32706. * @return {Loader} A reference to this instance.
  32707. */
  32708. setRequestHeader( requestHeader ) {
  32709. this.requestHeader = requestHeader;
  32710. return this;
  32711. }
  32712. /**
  32713. * This method can be implemented in loaders for aborting ongoing requests.
  32714. *
  32715. * @abstract
  32716. * @return {Loader} A reference to this instance.
  32717. */
  32718. abort() {
  32719. return this;
  32720. }
  32721. }
  32722. /**
  32723. * Callback for onProgress in loaders.
  32724. *
  32725. * @callback onProgressCallback
  32726. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32727. */
  32728. /**
  32729. * Callback for onError in loaders.
  32730. *
  32731. * @callback onErrorCallback
  32732. * @param {Error} error - The error which occurred during the loading process.
  32733. */
  32734. /**
  32735. * The default material name that is used by loaders
  32736. * when creating materials for loaded 3D objects.
  32737. *
  32738. * Note: Not all loaders might honor this setting.
  32739. *
  32740. * @static
  32741. * @type {string}
  32742. * @default '__DEFAULT'
  32743. */
  32744. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32745. const loading = {};
  32746. class HttpError extends Error {
  32747. constructor( message, response ) {
  32748. super( message );
  32749. this.response = response;
  32750. }
  32751. }
  32752. /**
  32753. * A low level class for loading resources with the Fetch API, used internally by
  32754. * most loaders. It can also be used directly to load any file type that does
  32755. * not have a loader.
  32756. *
  32757. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32758. * once to your application.
  32759. *
  32760. * ```js
  32761. * const loader = new THREE.FileLoader();
  32762. * const data = await loader.loadAsync( 'example.txt' );
  32763. * ```
  32764. *
  32765. * @augments Loader
  32766. */
  32767. class FileLoader extends Loader {
  32768. /**
  32769. * Constructs a new file loader.
  32770. *
  32771. * @param {LoadingManager} [manager] - The loading manager.
  32772. */
  32773. constructor( manager ) {
  32774. super( manager );
  32775. /**
  32776. * The expected mime type. Valid values can be found
  32777. * [here](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32778. *
  32779. * @type {string}
  32780. */
  32781. this.mimeType = '';
  32782. /**
  32783. * The expected response type.
  32784. *
  32785. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32786. * @default ''
  32787. */
  32788. this.responseType = '';
  32789. /**
  32790. * Used for aborting requests.
  32791. *
  32792. * @private
  32793. * @type {AbortController}
  32794. */
  32795. this._abortController = new AbortController();
  32796. }
  32797. /**
  32798. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32799. *
  32800. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32801. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32802. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32803. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32804. */
  32805. load( url, onLoad, onProgress, onError ) {
  32806. if ( url === undefined ) url = '';
  32807. if ( this.path !== undefined ) url = this.path + url;
  32808. url = this.manager.resolveURL( url );
  32809. const cached = Cache.get( `file:${url}` );
  32810. if ( cached !== undefined ) {
  32811. this.manager.itemStart( url );
  32812. setTimeout( () => {
  32813. if ( onLoad ) onLoad( cached );
  32814. this.manager.itemEnd( url );
  32815. }, 0 );
  32816. return;
  32817. }
  32818. // Check if request is duplicate
  32819. if ( loading[ url ] !== undefined ) {
  32820. loading[ url ].push( {
  32821. onLoad: onLoad,
  32822. onProgress: onProgress,
  32823. onError: onError
  32824. } );
  32825. return;
  32826. }
  32827. // Initialise array for duplicate requests
  32828. loading[ url ] = [];
  32829. loading[ url ].push( {
  32830. onLoad: onLoad,
  32831. onProgress: onProgress,
  32832. onError: onError,
  32833. } );
  32834. // create request
  32835. const req = new Request( url, {
  32836. headers: new Headers( this.requestHeader ),
  32837. credentials: this.withCredentials ? 'include' : 'same-origin',
  32838. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32839. } );
  32840. // record states ( avoid data race )
  32841. const mimeType = this.mimeType;
  32842. const responseType = this.responseType;
  32843. // start the fetch
  32844. fetch( req )
  32845. .then( response => {
  32846. if ( response.status === 200 || response.status === 0 ) {
  32847. // Some browsers return HTTP Status 0 when using non-http protocol
  32848. // e.g. 'file://' or 'data://'. Handle as success.
  32849. if ( response.status === 0 ) {
  32850. warn( 'FileLoader: HTTP Status 0 received.' );
  32851. }
  32852. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32853. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32854. return response;
  32855. }
  32856. const callbacks = loading[ url ];
  32857. const reader = response.body.getReader();
  32858. // Nginx needs X-File-Size check
  32859. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32860. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32861. const total = contentLength ? parseInt( contentLength ) : 0;
  32862. const lengthComputable = total !== 0;
  32863. let loaded = 0;
  32864. // periodically read data into the new stream tracking while download progress
  32865. const stream = new ReadableStream( {
  32866. start( controller ) {
  32867. readData();
  32868. function readData() {
  32869. reader.read().then( ( { done, value } ) => {
  32870. if ( done ) {
  32871. controller.close();
  32872. } else {
  32873. loaded += value.byteLength;
  32874. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32875. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32876. const callback = callbacks[ i ];
  32877. if ( callback.onProgress ) callback.onProgress( event );
  32878. }
  32879. controller.enqueue( value );
  32880. readData();
  32881. }
  32882. }, ( e ) => {
  32883. controller.error( e );
  32884. } );
  32885. }
  32886. }
  32887. } );
  32888. return new Response( stream );
  32889. } else {
  32890. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32891. }
  32892. } )
  32893. .then( response => {
  32894. switch ( responseType ) {
  32895. case 'arraybuffer':
  32896. return response.arrayBuffer();
  32897. case 'blob':
  32898. return response.blob();
  32899. case 'document':
  32900. return response.text()
  32901. .then( text => {
  32902. const parser = new DOMParser();
  32903. return parser.parseFromString( text, mimeType );
  32904. } );
  32905. case 'json':
  32906. return response.json();
  32907. default:
  32908. if ( mimeType === '' ) {
  32909. return response.text();
  32910. } else {
  32911. // sniff encoding
  32912. const re = /charset="?([^;"\s]*)"?/i;
  32913. const exec = re.exec( mimeType );
  32914. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32915. const decoder = new TextDecoder( label );
  32916. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32917. }
  32918. }
  32919. } )
  32920. .then( data => {
  32921. // Add to cache only on HTTP success, so that we do not cache
  32922. // error response bodies as proper responses to requests.
  32923. Cache.add( `file:${url}`, data );
  32924. const callbacks = loading[ url ];
  32925. delete loading[ url ];
  32926. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32927. const callback = callbacks[ i ];
  32928. if ( callback.onLoad ) callback.onLoad( data );
  32929. }
  32930. } )
  32931. .catch( err => {
  32932. // Abort errors and other errors are handled the same
  32933. const callbacks = loading[ url ];
  32934. if ( callbacks === undefined ) {
  32935. // When onLoad was called and url was deleted in `loading`
  32936. this.manager.itemError( url );
  32937. throw err;
  32938. }
  32939. delete loading[ url ];
  32940. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32941. const callback = callbacks[ i ];
  32942. if ( callback.onError ) callback.onError( err );
  32943. }
  32944. this.manager.itemError( url );
  32945. } )
  32946. .finally( () => {
  32947. this.manager.itemEnd( url );
  32948. } );
  32949. this.manager.itemStart( url );
  32950. }
  32951. /**
  32952. * Sets the expected response type.
  32953. *
  32954. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32955. * @return {FileLoader} A reference to this file loader.
  32956. */
  32957. setResponseType( value ) {
  32958. this.responseType = value;
  32959. return this;
  32960. }
  32961. /**
  32962. * Sets the expected mime type of the loaded file.
  32963. *
  32964. * @param {string} value - The mime type.
  32965. * @return {FileLoader} A reference to this file loader.
  32966. */
  32967. setMimeType( value ) {
  32968. this.mimeType = value;
  32969. return this;
  32970. }
  32971. /**
  32972. * Aborts ongoing fetch requests.
  32973. *
  32974. * @return {FileLoader} A reference to this instance.
  32975. */
  32976. abort() {
  32977. this._abortController.abort();
  32978. this._abortController = new AbortController();
  32979. return this;
  32980. }
  32981. }
  32982. /**
  32983. * Class for loading animation clips in the JSON format. The files are internally
  32984. * loaded via {@link FileLoader}.
  32985. *
  32986. * ```js
  32987. * const loader = new THREE.AnimationLoader();
  32988. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32989. * ```
  32990. *
  32991. * @augments Loader
  32992. */
  32993. class AnimationLoader extends Loader {
  32994. /**
  32995. * Constructs a new animation loader.
  32996. *
  32997. * @param {LoadingManager} [manager] - The loading manager.
  32998. */
  32999. constructor( manager ) {
  33000. super( manager );
  33001. }
  33002. /**
  33003. * Starts loading from the given URL and pass the loaded animations as an array
  33004. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  33005. *
  33006. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33007. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  33008. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33009. * @param {onErrorCallback} onError - Executed when errors occur.
  33010. */
  33011. load( url, onLoad, onProgress, onError ) {
  33012. const scope = this;
  33013. const loader = new FileLoader( this.manager );
  33014. loader.setPath( this.path );
  33015. loader.setRequestHeader( this.requestHeader );
  33016. loader.setWithCredentials( this.withCredentials );
  33017. loader.load( url, function ( text ) {
  33018. try {
  33019. onLoad( scope.parse( JSON.parse( text ) ) );
  33020. } catch ( e ) {
  33021. if ( onError ) {
  33022. onError( e );
  33023. } else {
  33024. error( e );
  33025. }
  33026. scope.manager.itemError( url );
  33027. }
  33028. }, onProgress, onError );
  33029. }
  33030. /**
  33031. * Parses the given JSON object and returns an array of animation clips.
  33032. *
  33033. * @param {Object} json - The serialized animation clips.
  33034. * @return {Array<AnimationClip>} The parsed animation clips.
  33035. */
  33036. parse( json ) {
  33037. const animations = [];
  33038. for ( let i = 0; i < json.length; i ++ ) {
  33039. const clip = AnimationClip.parse( json[ i ] );
  33040. animations.push( clip );
  33041. }
  33042. return animations;
  33043. }
  33044. }
  33045. /**
  33046. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  33047. * Textures are internally loaded via {@link FileLoader}.
  33048. *
  33049. * Derived classes have to implement the `parse()` method which holds the parsing
  33050. * for the respective format.
  33051. *
  33052. * @abstract
  33053. * @augments Loader
  33054. */
  33055. class CompressedTextureLoader extends Loader {
  33056. /**
  33057. * Constructs a new compressed texture loader.
  33058. *
  33059. * @param {LoadingManager} [manager] - The loading manager.
  33060. */
  33061. constructor( manager ) {
  33062. super( manager );
  33063. }
  33064. /**
  33065. * Starts loading from the given URL and passes the loaded compressed texture
  33066. * to the `onLoad()` callback. The method also returns a new texture object which can
  33067. * directly be used for material creation. If you do it this way, the texture
  33068. * may pop up in your scene once the respective loading process is finished.
  33069. *
  33070. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33071. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  33072. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33073. * @param {onErrorCallback} onError - Executed when errors occur.
  33074. * @return {CompressedTexture} The compressed texture.
  33075. */
  33076. load( url, onLoad, onProgress, onError ) {
  33077. const scope = this;
  33078. const images = [];
  33079. const texture = new CompressedTexture();
  33080. const loader = new FileLoader( this.manager );
  33081. loader.setPath( this.path );
  33082. loader.setResponseType( 'arraybuffer' );
  33083. loader.setRequestHeader( this.requestHeader );
  33084. loader.setWithCredentials( scope.withCredentials );
  33085. let loaded = 0;
  33086. function loadTexture( i ) {
  33087. loader.load( url[ i ], function ( buffer ) {
  33088. const texDatas = scope.parse( buffer, true );
  33089. images[ i ] = {
  33090. width: texDatas.width,
  33091. height: texDatas.height,
  33092. format: texDatas.format,
  33093. mipmaps: texDatas.mipmaps
  33094. };
  33095. loaded += 1;
  33096. if ( loaded === 6 ) {
  33097. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  33098. texture.image = images;
  33099. texture.format = texDatas.format;
  33100. texture.needsUpdate = true;
  33101. if ( onLoad ) onLoad( texture );
  33102. }
  33103. }, onProgress, onError );
  33104. }
  33105. if ( Array.isArray( url ) ) {
  33106. for ( let i = 0, il = url.length; i < il; ++ i ) {
  33107. loadTexture( i );
  33108. }
  33109. } else {
  33110. // compressed cubemap texture stored in a single DDS file
  33111. loader.load( url, function ( buffer ) {
  33112. const texDatas = scope.parse( buffer, true );
  33113. if ( texDatas.isCubemap ) {
  33114. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  33115. for ( let f = 0; f < faces; f ++ ) {
  33116. images[ f ] = { mipmaps: [] };
  33117. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  33118. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  33119. images[ f ].format = texDatas.format;
  33120. images[ f ].width = texDatas.width;
  33121. images[ f ].height = texDatas.height;
  33122. }
  33123. }
  33124. texture.image = images;
  33125. } else {
  33126. texture.image.width = texDatas.width;
  33127. texture.image.height = texDatas.height;
  33128. texture.mipmaps = texDatas.mipmaps;
  33129. }
  33130. if ( texDatas.mipmapCount === 1 ) {
  33131. texture.minFilter = LinearFilter;
  33132. }
  33133. texture.format = texDatas.format;
  33134. texture.needsUpdate = true;
  33135. if ( onLoad ) onLoad( texture );
  33136. }, onProgress, onError );
  33137. }
  33138. return texture;
  33139. }
  33140. }
  33141. const _loading = new WeakMap();
  33142. /**
  33143. * A loader for loading images. The class loads images with the HTML `Image` API.
  33144. *
  33145. * ```js
  33146. * const loader = new THREE.ImageLoader();
  33147. * const image = await loader.loadAsync( 'image.png' );
  33148. * ```
  33149. * Please note that `ImageLoader` has dropped support for progress
  33150. * events in `r84`. For an `ImageLoader` that supports progress events, see
  33151. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  33152. *
  33153. * @augments Loader
  33154. */
  33155. class ImageLoader extends Loader {
  33156. /**
  33157. * Constructs a new image loader.
  33158. *
  33159. * @param {LoadingManager} [manager] - The loading manager.
  33160. */
  33161. constructor( manager ) {
  33162. super( manager );
  33163. }
  33164. /**
  33165. * Starts loading from the given URL and passes the loaded image
  33166. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  33167. * directly be used for texture creation. If you do it this way, the texture
  33168. * may pop up in your scene once the respective loading process is finished.
  33169. *
  33170. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33171. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  33172. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33173. * @param {onErrorCallback} onError - Executed when errors occur.
  33174. * @return {Image} The image.
  33175. */
  33176. load( url, onLoad, onProgress, onError ) {
  33177. if ( this.path !== undefined ) url = this.path + url;
  33178. url = this.manager.resolveURL( url );
  33179. const scope = this;
  33180. const cached = Cache.get( `image:${url}` );
  33181. if ( cached !== undefined ) {
  33182. if ( cached.complete === true ) {
  33183. scope.manager.itemStart( url );
  33184. setTimeout( function () {
  33185. if ( onLoad ) onLoad( cached );
  33186. scope.manager.itemEnd( url );
  33187. }, 0 );
  33188. } else {
  33189. let arr = _loading.get( cached );
  33190. if ( arr === undefined ) {
  33191. arr = [];
  33192. _loading.set( cached, arr );
  33193. }
  33194. arr.push( { onLoad, onError } );
  33195. }
  33196. return cached;
  33197. }
  33198. const image = createElementNS( 'img' );
  33199. function onImageLoad() {
  33200. removeEventListeners();
  33201. if ( onLoad ) onLoad( this );
  33202. //
  33203. const callbacks = _loading.get( this ) || [];
  33204. for ( let i = 0; i < callbacks.length; i ++ ) {
  33205. const callback = callbacks[ i ];
  33206. if ( callback.onLoad ) callback.onLoad( this );
  33207. }
  33208. _loading.delete( this );
  33209. scope.manager.itemEnd( url );
  33210. }
  33211. function onImageError( event ) {
  33212. removeEventListeners();
  33213. if ( onError ) onError( event );
  33214. Cache.remove( `image:${url}` );
  33215. //
  33216. const callbacks = _loading.get( this ) || [];
  33217. for ( let i = 0; i < callbacks.length; i ++ ) {
  33218. const callback = callbacks[ i ];
  33219. if ( callback.onError ) callback.onError( event );
  33220. }
  33221. _loading.delete( this );
  33222. scope.manager.itemError( url );
  33223. scope.manager.itemEnd( url );
  33224. }
  33225. function removeEventListeners() {
  33226. image.removeEventListener( 'load', onImageLoad, false );
  33227. image.removeEventListener( 'error', onImageError, false );
  33228. }
  33229. image.addEventListener( 'load', onImageLoad, false );
  33230. image.addEventListener( 'error', onImageError, false );
  33231. if ( url.slice( 0, 5 ) !== 'data:' ) {
  33232. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  33233. }
  33234. Cache.add( `image:${url}`, image );
  33235. scope.manager.itemStart( url );
  33236. image.src = url;
  33237. return image;
  33238. }
  33239. }
  33240. /**
  33241. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  33242. *
  33243. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  33244. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  33245. * like vertical and horizontal cross, column and row layouts are not supported.
  33246. *
  33247. * Note that, by convention, cube maps are specified in a coordinate system
  33248. * in which positive-x is to the right when looking up the positive-z axis --
  33249. * in other words, using a left-handed coordinate system. Since three.js uses
  33250. * a right-handed coordinate system, environment maps used in three.js will
  33251. * have pos-x and neg-x swapped.
  33252. *
  33253. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  33254. * is set to `SRGBColorSpace` by default.
  33255. *
  33256. * ```js
  33257. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  33258. * const cubeTexture = await loader.loadAsync( [
  33259. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  33260. * ] );
  33261. * scene.background = cubeTexture;
  33262. * ```
  33263. *
  33264. * @augments Loader
  33265. */
  33266. class CubeTextureLoader extends Loader {
  33267. /**
  33268. * Constructs a new cube texture loader.
  33269. *
  33270. * @param {LoadingManager} [manager] - The loading manager.
  33271. */
  33272. constructor( manager ) {
  33273. super( manager );
  33274. }
  33275. /**
  33276. * Starts loading from the given URL and pass the fully loaded cube texture
  33277. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  33278. * directly be used for material creation. If you do it this way, the cube texture
  33279. * may pop up in your scene once the respective loading process is finished.
  33280. *
  33281. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  33282. * cube texture. The urls should be specified in the following order: pos-x,
  33283. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  33284. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  33285. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33286. * @param {onErrorCallback} onError - Executed when errors occur.
  33287. * @return {CubeTexture} The cube texture.
  33288. */
  33289. load( urls, onLoad, onProgress, onError ) {
  33290. const texture = new CubeTexture();
  33291. texture.colorSpace = SRGBColorSpace;
  33292. const loader = new ImageLoader( this.manager );
  33293. loader.setCrossOrigin( this.crossOrigin );
  33294. loader.setPath( this.path );
  33295. let loaded = 0;
  33296. function loadTexture( i ) {
  33297. loader.load( urls[ i ], function ( image ) {
  33298. texture.images[ i ] = image;
  33299. loaded ++;
  33300. if ( loaded === 6 ) {
  33301. texture.needsUpdate = true;
  33302. if ( onLoad ) onLoad( texture );
  33303. }
  33304. }, undefined, onError );
  33305. }
  33306. for ( let i = 0; i < urls.length; ++ i ) {
  33307. loadTexture( i );
  33308. }
  33309. return texture;
  33310. }
  33311. }
  33312. /**
  33313. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33314. * Textures are internally loaded via {@link FileLoader}.
  33315. *
  33316. * Derived classes have to implement the `parse()` method which holds the parsing
  33317. * for the respective format.
  33318. *
  33319. * @abstract
  33320. * @augments Loader
  33321. */
  33322. class DataTextureLoader extends Loader {
  33323. /**
  33324. * Constructs a new data texture loader.
  33325. *
  33326. * @param {LoadingManager} [manager] - The loading manager.
  33327. */
  33328. constructor( manager ) {
  33329. super( manager );
  33330. }
  33331. /**
  33332. * Starts loading from the given URL and passes the loaded data texture
  33333. * to the `onLoad()` callback. The method also returns a new texture object which can
  33334. * directly be used for material creation. If you do it this way, the texture
  33335. * may pop up in your scene once the respective loading process is finished.
  33336. *
  33337. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33338. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33339. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33340. * @param {onErrorCallback} onError - Executed when errors occur.
  33341. * @return {DataTexture} The data texture.
  33342. */
  33343. load( url, onLoad, onProgress, onError ) {
  33344. const scope = this;
  33345. const texture = new DataTexture();
  33346. const loader = new FileLoader( this.manager );
  33347. loader.setResponseType( 'arraybuffer' );
  33348. loader.setRequestHeader( this.requestHeader );
  33349. loader.setPath( this.path );
  33350. loader.setWithCredentials( scope.withCredentials );
  33351. loader.load( url, function ( buffer ) {
  33352. let texData;
  33353. try {
  33354. texData = scope.parse( buffer );
  33355. } catch ( e ) {
  33356. if ( onError !== undefined ) {
  33357. onError( e );
  33358. } else {
  33359. error( e );
  33360. }
  33361. return;
  33362. }
  33363. scope._applyTexData( texture, texData );
  33364. if ( onLoad ) onLoad( texture, texData );
  33365. }, onProgress, onError );
  33366. return texture;
  33367. }
  33368. /**
  33369. * Parses the given buffer and returns a configured data texture. Use this method
  33370. * for parsing texture data that is already in memory (e.g. drag and drop or data
  33371. * loaded from a server) without going through {@link DataTextureLoader#load}.
  33372. *
  33373. * @param {ArrayBuffer} buffer - The raw texture data.
  33374. * @return {DataTexture} The data texture.
  33375. */
  33376. createDataTexture( buffer ) {
  33377. const texture = new DataTexture();
  33378. this._applyTexData( texture, this.parse( buffer ) );
  33379. return texture;
  33380. }
  33381. /**
  33382. * Applies the given parsed texture data to the given data texture.
  33383. *
  33384. * @private
  33385. * @param {DataTexture} texture - The data texture.
  33386. * @param {DataTextureLoader~TexData} texData - The parsed texture data.
  33387. */
  33388. _applyTexData( texture, texData ) {
  33389. if ( texData.image !== undefined ) {
  33390. texture.image = texData.image;
  33391. } else if ( texData.data !== undefined ) {
  33392. texture.image.width = texData.width;
  33393. texture.image.height = texData.height;
  33394. texture.image.data = texData.data;
  33395. }
  33396. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33397. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33398. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33399. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33400. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33401. if ( texData.colorSpace !== undefined ) {
  33402. texture.colorSpace = texData.colorSpace;
  33403. }
  33404. if ( texData.flipY !== undefined ) {
  33405. texture.flipY = texData.flipY;
  33406. }
  33407. if ( texData.format !== undefined ) {
  33408. texture.format = texData.format;
  33409. }
  33410. if ( texData.type !== undefined ) {
  33411. texture.type = texData.type;
  33412. }
  33413. if ( texData.mipmaps !== undefined ) {
  33414. texture.mipmaps = texData.mipmaps;
  33415. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33416. }
  33417. if ( texData.mipmapCount === 1 ) {
  33418. texture.minFilter = LinearFilter;
  33419. }
  33420. if ( texData.generateMipmaps !== undefined ) {
  33421. texture.generateMipmaps = texData.generateMipmaps;
  33422. }
  33423. texture.needsUpdate = true;
  33424. }
  33425. }
  33426. /**
  33427. * Class for loading textures. Images are internally
  33428. * loaded via {@link ImageLoader}.
  33429. *
  33430. * ```js
  33431. * const loader = new THREE.TextureLoader();
  33432. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33433. *
  33434. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33435. * ```
  33436. * Please note that `TextureLoader` has dropped support for progress
  33437. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33438. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33439. *
  33440. * @augments Loader
  33441. */
  33442. class TextureLoader extends Loader {
  33443. /**
  33444. * Constructs a new texture loader.
  33445. *
  33446. * @param {LoadingManager} [manager] - The loading manager.
  33447. */
  33448. constructor( manager ) {
  33449. super( manager );
  33450. }
  33451. /**
  33452. * Starts loading from the given URL and pass the fully loaded texture
  33453. * to the `onLoad()` callback. The method also returns a new texture object which can
  33454. * directly be used for material creation. If you do it this way, the texture
  33455. * may pop up in your scene once the respective loading process is finished.
  33456. *
  33457. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33458. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33459. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33460. * @param {onErrorCallback} onError - Executed when errors occur.
  33461. * @return {Texture} The texture.
  33462. */
  33463. load( url, onLoad, onProgress, onError ) {
  33464. const texture = new Texture();
  33465. const loader = new ImageLoader( this.manager );
  33466. loader.setCrossOrigin( this.crossOrigin );
  33467. loader.setPath( this.path );
  33468. loader.load( url, function ( image ) {
  33469. texture.image = image;
  33470. texture.needsUpdate = true;
  33471. if ( onLoad !== undefined ) {
  33472. onLoad( texture );
  33473. }
  33474. }, onProgress, onError );
  33475. return texture;
  33476. }
  33477. }
  33478. /**
  33479. * Abstract base class for lights - all other light types inherit the
  33480. * properties and methods described here.
  33481. *
  33482. * @abstract
  33483. * @augments Object3D
  33484. */
  33485. class Light extends Object3D {
  33486. /**
  33487. * Constructs a new light.
  33488. *
  33489. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33490. * @param {number} [intensity=1] - The light's strength/intensity.
  33491. */
  33492. constructor( color, intensity = 1 ) {
  33493. super();
  33494. /**
  33495. * This flag can be used for type testing.
  33496. *
  33497. * @type {boolean}
  33498. * @readonly
  33499. * @default true
  33500. */
  33501. this.isLight = true;
  33502. this.type = 'Light';
  33503. /**
  33504. * The light's color.
  33505. *
  33506. * @type {Color}
  33507. */
  33508. this.color = new Color( color );
  33509. /**
  33510. * The light's intensity.
  33511. *
  33512. * @type {number}
  33513. * @default 1
  33514. */
  33515. this.intensity = intensity;
  33516. }
  33517. /**
  33518. * Frees the GPU-related resources allocated by this instance. Call this
  33519. * method whenever this instance is no longer used in your app.
  33520. */
  33521. dispose() {
  33522. this.dispatchEvent( { type: 'dispose' } );
  33523. }
  33524. copy( source, recursive ) {
  33525. super.copy( source, recursive );
  33526. this.color.copy( source.color );
  33527. this.intensity = source.intensity;
  33528. return this;
  33529. }
  33530. toJSON( meta ) {
  33531. const data = super.toJSON( meta );
  33532. data.object.color = this.color.getHex();
  33533. data.object.intensity = this.intensity;
  33534. return data;
  33535. }
  33536. }
  33537. /**
  33538. * A light source positioned directly above the scene, with color fading from
  33539. * the sky color to the ground color.
  33540. *
  33541. * This light cannot be used to cast shadows.
  33542. *
  33543. * ```js
  33544. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33545. * scene.add( light );
  33546. * ```
  33547. *
  33548. * @augments Light
  33549. */
  33550. class HemisphereLight extends Light {
  33551. /**
  33552. * Constructs a new hemisphere light.
  33553. *
  33554. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33555. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33556. * @param {number} [intensity=1] - The light's strength/intensity.
  33557. */
  33558. constructor( skyColor, groundColor, intensity ) {
  33559. super( skyColor, intensity );
  33560. /**
  33561. * This flag can be used for type testing.
  33562. *
  33563. * @type {boolean}
  33564. * @readonly
  33565. * @default true
  33566. */
  33567. this.isHemisphereLight = true;
  33568. this.type = 'HemisphereLight';
  33569. this.position.copy( Object3D.DEFAULT_UP );
  33570. this.updateMatrix();
  33571. /**
  33572. * The light's ground color.
  33573. *
  33574. * @type {Color}
  33575. */
  33576. this.groundColor = new Color( groundColor );
  33577. }
  33578. copy( source, recursive ) {
  33579. super.copy( source, recursive );
  33580. this.groundColor.copy( source.groundColor );
  33581. return this;
  33582. }
  33583. toJSON( meta ) {
  33584. const data = super.toJSON( meta );
  33585. data.object.groundColor = this.groundColor.getHex();
  33586. return data;
  33587. }
  33588. }
  33589. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33590. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33591. const _lookTarget = /*@__PURE__*/ new Vector3();
  33592. /**
  33593. * Abstract base class for light shadow classes. These classes
  33594. * represent the shadow configuration for different light types.
  33595. *
  33596. * @abstract
  33597. */
  33598. class LightShadow {
  33599. /**
  33600. * Constructs a new light shadow.
  33601. *
  33602. * @param {Camera} camera - The light's view of the world.
  33603. */
  33604. constructor( camera ) {
  33605. /**
  33606. * The light's view of the world.
  33607. *
  33608. * @type {Camera}
  33609. */
  33610. this.camera = camera;
  33611. /**
  33612. * The intensity of the shadow. The default is `1`.
  33613. * Valid values are in the range `[0, 1]`.
  33614. *
  33615. * @type {number}
  33616. * @default 1
  33617. */
  33618. this.intensity = 1;
  33619. /**
  33620. * Shadow map bias, how much to add or subtract from the normalized depth
  33621. * when deciding whether a surface is in shadow.
  33622. *
  33623. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33624. * may help reduce artifacts in shadows.
  33625. *
  33626. * @type {number}
  33627. * @default 0
  33628. */
  33629. this.bias = 0;
  33630. /**
  33631. * A node version of `bias`. Only supported with `WebGPURenderer`.
  33632. *
  33633. * If a bias node is defined, `bias` has no effect.
  33634. *
  33635. * @type {?Node<float>}
  33636. * @default null
  33637. */
  33638. this.biasNode = null;
  33639. /**
  33640. * Defines how much the position used to query the shadow map is offset along
  33641. * the object normal. The default is `0`. Increasing this value can be used to
  33642. * reduce shadow acne especially in large scenes where light shines onto
  33643. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33644. *
  33645. * @type {number}
  33646. * @default 0
  33647. */
  33648. this.normalBias = 0;
  33649. /**
  33650. * Setting this to values greater than 1 will blur the edges of the shadow.
  33651. * High values will cause unwanted banding effects in the shadows - a greater
  33652. * map size will allow for a higher value to be used here before these effects
  33653. * become visible.
  33654. *
  33655. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33656. *
  33657. * @type {number}
  33658. * @default 1
  33659. */
  33660. this.radius = 1;
  33661. /**
  33662. * The amount of samples to use when blurring a VSM shadow map.
  33663. *
  33664. * @type {number}
  33665. * @default 8
  33666. */
  33667. this.blurSamples = 8;
  33668. /**
  33669. * Defines the width and height of the shadow map. Higher values give better quality
  33670. * shadows at the cost of computation time. Values must be powers of two.
  33671. *
  33672. * @type {Vector2}
  33673. * @default (512,512)
  33674. */
  33675. this.mapSize = new Vector2( 512, 512 );
  33676. /**
  33677. * The type of shadow texture. The default is `UnsignedByteType`.
  33678. *
  33679. * @type {number}
  33680. * @default UnsignedByteType
  33681. */
  33682. this.mapType = UnsignedByteType;
  33683. /**
  33684. * The depth map generated using the internal camera; a location beyond a
  33685. * pixel's depth is in shadow. Computed internally during rendering.
  33686. *
  33687. * @type {?RenderTarget}
  33688. * @default null
  33689. */
  33690. this.map = null;
  33691. /**
  33692. * The distribution map generated using the internal camera; an occlusion is
  33693. * calculated based on the distribution of depths. Computed internally during
  33694. * rendering.
  33695. *
  33696. * @type {?RenderTarget}
  33697. * @default null
  33698. */
  33699. this.mapPass = null;
  33700. /**
  33701. * Model to shadow camera space, to compute location and depth in shadow map.
  33702. * This is computed internally during rendering.
  33703. *
  33704. * @type {Matrix4}
  33705. */
  33706. this.matrix = new Matrix4();
  33707. /**
  33708. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33709. * lighting / shadows, you may set this to `false`.
  33710. *
  33711. * @type {boolean}
  33712. * @default true
  33713. */
  33714. this.autoUpdate = true;
  33715. /**
  33716. * When set to `true`, shadow maps will be updated in the next `render` call.
  33717. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33718. * set this property to `true` and then make a render call to update the light's shadow.
  33719. *
  33720. * @type {boolean}
  33721. * @default false
  33722. */
  33723. this.needsUpdate = false;
  33724. this._frustum = new Frustum();
  33725. this._frameExtents = new Vector2( 1, 1 );
  33726. this._viewportCount = 1;
  33727. this._viewports = [
  33728. new Vector4( 0, 0, 1, 1 )
  33729. ];
  33730. }
  33731. /**
  33732. * Used internally by the renderer to get the number of viewports that need
  33733. * to be rendered for this shadow.
  33734. *
  33735. * @return {number} The viewport count.
  33736. */
  33737. getViewportCount() {
  33738. return this._viewportCount;
  33739. }
  33740. /**
  33741. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33742. *
  33743. * @return {Frustum} The shadow camera frustum.
  33744. */
  33745. getFrustum() {
  33746. return this._frustum;
  33747. }
  33748. /**
  33749. * Update the matrices for the camera and shadow, used internally by the renderer.
  33750. *
  33751. * @param {Light} light - The light for which the shadow is being rendered.
  33752. */
  33753. updateMatrices( light ) {
  33754. const shadowCamera = this.camera;
  33755. const shadowMatrix = this.matrix;
  33756. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33757. shadowCamera.position.copy( _lightPositionWorld );
  33758. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  33759. shadowCamera.lookAt( _lookTarget );
  33760. shadowCamera.updateMatrixWorld();
  33761. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33762. this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33763. if ( shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth ) {
  33764. shadowMatrix.set(
  33765. 0.5, 0.0, 0.0, 0.5,
  33766. 0.0, 0.5, 0.0, 0.5,
  33767. 0.0, 0.0, 1.0, 0.0, // Identity Z (preserving the correct [0, 1] range from the projection matrix)
  33768. 0.0, 0.0, 0.0, 1.0
  33769. );
  33770. } else {
  33771. shadowMatrix.set(
  33772. 0.5, 0.0, 0.0, 0.5,
  33773. 0.0, 0.5, 0.0, 0.5,
  33774. 0.0, 0.0, 0.5, 0.5,
  33775. 0.0, 0.0, 0.0, 1.0
  33776. );
  33777. }
  33778. shadowMatrix.multiply( _projScreenMatrix );
  33779. }
  33780. /**
  33781. * Returns a viewport definition for the given viewport index.
  33782. *
  33783. * @param {number} viewportIndex - The viewport index.
  33784. * @return {Vector4} The viewport.
  33785. */
  33786. getViewport( viewportIndex ) {
  33787. return this._viewports[ viewportIndex ];
  33788. }
  33789. /**
  33790. * Returns the frame extends.
  33791. *
  33792. * @return {Vector2} The frame extends.
  33793. */
  33794. getFrameExtents() {
  33795. return this._frameExtents;
  33796. }
  33797. /**
  33798. * Frees the GPU-related resources allocated by this instance. Call this
  33799. * method whenever this instance is no longer used in your app.
  33800. */
  33801. dispose() {
  33802. if ( this.map ) {
  33803. this.map.dispose();
  33804. }
  33805. if ( this.mapPass ) {
  33806. this.mapPass.dispose();
  33807. }
  33808. }
  33809. /**
  33810. * Copies the values of the given light shadow instance to this instance.
  33811. *
  33812. * @param {LightShadow} source - The light shadow to copy.
  33813. * @return {LightShadow} A reference to this light shadow instance.
  33814. */
  33815. copy( source ) {
  33816. this.camera = source.camera.clone();
  33817. this.intensity = source.intensity;
  33818. this.bias = source.bias;
  33819. this.radius = source.radius;
  33820. this.autoUpdate = source.autoUpdate;
  33821. this.needsUpdate = source.needsUpdate;
  33822. this.normalBias = source.normalBias;
  33823. this.blurSamples = source.blurSamples;
  33824. this.mapSize.copy( source.mapSize );
  33825. this.biasNode = source.biasNode;
  33826. return this;
  33827. }
  33828. /**
  33829. * Returns a new light shadow instance with copied values from this instance.
  33830. *
  33831. * @return {LightShadow} A clone of this instance.
  33832. */
  33833. clone() {
  33834. return new this.constructor().copy( this );
  33835. }
  33836. /**
  33837. * Serializes the light shadow into JSON.
  33838. *
  33839. * @return {Object} A JSON object representing the serialized light shadow.
  33840. * @see {@link ObjectLoader#parse}
  33841. */
  33842. toJSON() {
  33843. const object = {};
  33844. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33845. if ( this.bias !== 0 ) object.bias = this.bias;
  33846. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33847. if ( this.radius !== 1 ) object.radius = this.radius;
  33848. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33849. object.camera = this.camera.toJSON( false ).object;
  33850. delete object.camera.matrix;
  33851. return object;
  33852. }
  33853. }
  33854. const _position$2 = /*@__PURE__*/ new Vector3();
  33855. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  33856. const _scale$2 = /*@__PURE__*/ new Vector3();
  33857. /**
  33858. * Abstract base class for cameras. This class should always be inherited
  33859. * when you build a new camera.
  33860. *
  33861. * @abstract
  33862. * @augments Object3D
  33863. */
  33864. class Camera extends Object3D {
  33865. /**
  33866. * Constructs a new camera.
  33867. */
  33868. constructor() {
  33869. super();
  33870. /**
  33871. * This flag can be used for type testing.
  33872. *
  33873. * @type {boolean}
  33874. * @readonly
  33875. * @default true
  33876. */
  33877. this.isCamera = true;
  33878. this.type = 'Camera';
  33879. /**
  33880. * The inverse of the camera's world matrix.
  33881. *
  33882. * @type {Matrix4}
  33883. */
  33884. this.matrixWorldInverse = new Matrix4();
  33885. /**
  33886. * The camera's projection matrix.
  33887. *
  33888. * @type {Matrix4}
  33889. */
  33890. this.projectionMatrix = new Matrix4();
  33891. /**
  33892. * The inverse of the camera's projection matrix.
  33893. *
  33894. * @type {Matrix4}
  33895. */
  33896. this.projectionMatrixInverse = new Matrix4();
  33897. /**
  33898. * The coordinate system in which the camera is used.
  33899. *
  33900. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  33901. */
  33902. this.coordinateSystem = WebGLCoordinateSystem;
  33903. this._reversedDepth = false;
  33904. }
  33905. /**
  33906. * The flag that indicates whether the camera uses a reversed depth buffer.
  33907. *
  33908. * @type {boolean}
  33909. * @default false
  33910. */
  33911. get reversedDepth() {
  33912. return this._reversedDepth;
  33913. }
  33914. copy( source, recursive ) {
  33915. super.copy( source, recursive );
  33916. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  33917. this.projectionMatrix.copy( source.projectionMatrix );
  33918. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  33919. this.coordinateSystem = source.coordinateSystem;
  33920. return this;
  33921. }
  33922. /**
  33923. * Returns a vector representing the ("look") direction of the 3D object in world space.
  33924. *
  33925. * This method is overwritten since cameras have a different forward vector compared to other
  33926. * 3D objects. A camera looks down its local, negative z-axis by default.
  33927. *
  33928. * @param {Vector3} target - The target vector the result is stored to.
  33929. * @return {Vector3} The 3D object's direction in world space.
  33930. */
  33931. getWorldDirection( target ) {
  33932. return super.getWorldDirection( target ).negate();
  33933. }
  33934. updateMatrixWorld( force ) {
  33935. super.updateMatrixWorld( force );
  33936. // exclude scale from view matrix to be glTF conform
  33937. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33938. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33939. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33940. } else {
  33941. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33942. }
  33943. }
  33944. updateWorldMatrix( updateParents, updateChildren, force = false ) {
  33945. super.updateWorldMatrix( updateParents, updateChildren, force );
  33946. // exclude scale from view matrix to be glTF conform
  33947. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33948. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33949. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33950. } else {
  33951. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33952. }
  33953. }
  33954. clone() {
  33955. return new this.constructor().copy( this );
  33956. }
  33957. }
  33958. const _v3$1 = /*@__PURE__*/ new Vector3();
  33959. const _minTarget = /*@__PURE__*/ new Vector2();
  33960. const _maxTarget = /*@__PURE__*/ new Vector2();
  33961. /**
  33962. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  33963. *
  33964. * This projection mode is designed to mimic the way the human eye sees. It
  33965. * is the most common projection mode used for rendering a 3D scene.
  33966. *
  33967. * ```js
  33968. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  33969. * scene.add( camera );
  33970. * ```
  33971. *
  33972. * @augments Camera
  33973. */
  33974. class PerspectiveCamera extends Camera {
  33975. /**
  33976. * Constructs a new perspective camera.
  33977. *
  33978. * @param {number} [fov=50] - The vertical field of view.
  33979. * @param {number} [aspect=1] - The aspect ratio.
  33980. * @param {number} [near=0.1] - The camera's near plane.
  33981. * @param {number} [far=2000] - The camera's far plane.
  33982. */
  33983. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  33984. super();
  33985. /**
  33986. * This flag can be used for type testing.
  33987. *
  33988. * @type {boolean}
  33989. * @readonly
  33990. * @default true
  33991. */
  33992. this.isPerspectiveCamera = true;
  33993. this.type = 'PerspectiveCamera';
  33994. /**
  33995. * The vertical field of view, from bottom to top of view,
  33996. * in degrees.
  33997. *
  33998. * @type {number}
  33999. * @default 50
  34000. */
  34001. this.fov = fov;
  34002. /**
  34003. * The zoom factor of the camera.
  34004. *
  34005. * @type {number}
  34006. * @default 1
  34007. */
  34008. this.zoom = 1;
  34009. /**
  34010. * The camera's near plane. The valid range is greater than `0`
  34011. * and less than the current value of {@link PerspectiveCamera#far}.
  34012. *
  34013. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  34014. * valid value for a perspective camera's near plane.
  34015. *
  34016. * @type {number}
  34017. * @default 0.1
  34018. */
  34019. this.near = near;
  34020. /**
  34021. * The camera's far plane. Must be greater than the
  34022. * current value of {@link PerspectiveCamera#near}.
  34023. *
  34024. * @type {number}
  34025. * @default 2000
  34026. */
  34027. this.far = far;
  34028. /**
  34029. * Object distance used for stereoscopy and depth-of-field effects. This
  34030. * parameter does not influence the projection matrix unless a
  34031. * {@link StereoCamera} is being used.
  34032. *
  34033. * @type {number}
  34034. * @default 10
  34035. */
  34036. this.focus = 10;
  34037. /**
  34038. * The aspect ratio, usually the canvas width / canvas height.
  34039. *
  34040. * @type {number}
  34041. * @default 1
  34042. */
  34043. this.aspect = aspect;
  34044. /**
  34045. * Represents the frustum window specification. This property should not be edited
  34046. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34047. *
  34048. * @type {?Object}
  34049. * @default null
  34050. */
  34051. this.view = null;
  34052. /**
  34053. * Film size used for the larger axis. Default is `35` (millimeters). This
  34054. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  34055. * is set to a nonzero value.
  34056. *
  34057. * @type {number}
  34058. * @default 35
  34059. */
  34060. this.filmGauge = 35;
  34061. /**
  34062. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  34063. *
  34064. * @type {number}
  34065. * @default 0
  34066. */
  34067. this.filmOffset = 0;
  34068. this.updateProjectionMatrix();
  34069. }
  34070. copy( source, recursive ) {
  34071. super.copy( source, recursive );
  34072. this.fov = source.fov;
  34073. this.zoom = source.zoom;
  34074. this.near = source.near;
  34075. this.far = source.far;
  34076. this.focus = source.focus;
  34077. this.aspect = source.aspect;
  34078. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34079. this.filmGauge = source.filmGauge;
  34080. this.filmOffset = source.filmOffset;
  34081. return this;
  34082. }
  34083. /**
  34084. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  34085. *
  34086. * The default film gauge is 35, so that the focal length can be specified for
  34087. * a 35mm (full frame) camera.
  34088. *
  34089. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  34090. */
  34091. setFocalLength( focalLength ) {
  34092. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  34093. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  34094. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  34095. this.updateProjectionMatrix();
  34096. }
  34097. /**
  34098. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  34099. * {@link PerspectiveCamera#filmGauge}.
  34100. *
  34101. * @return {number} The computed focal length.
  34102. */
  34103. getFocalLength() {
  34104. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  34105. return 0.5 * this.getFilmHeight() / vExtentSlope;
  34106. }
  34107. /**
  34108. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  34109. *
  34110. * @return {number} The effective FOV.
  34111. */
  34112. getEffectiveFOV() {
  34113. return RAD2DEG * 2 * Math.atan(
  34114. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  34115. }
  34116. /**
  34117. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  34118. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  34119. *
  34120. * @return {number} The film width.
  34121. */
  34122. getFilmWidth() {
  34123. // film not completely covered in portrait format (aspect < 1)
  34124. return this.filmGauge * Math.min( this.aspect, 1 );
  34125. }
  34126. /**
  34127. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  34128. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  34129. *
  34130. * @return {number} The film width.
  34131. */
  34132. getFilmHeight() {
  34133. // film not completely covered in landscape format (aspect > 1)
  34134. return this.filmGauge / Math.max( this.aspect, 1 );
  34135. }
  34136. /**
  34137. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  34138. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  34139. *
  34140. * @param {number} distance - The viewing distance.
  34141. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  34142. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  34143. */
  34144. getViewBounds( distance, minTarget, maxTarget ) {
  34145. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  34146. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  34147. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  34148. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  34149. }
  34150. /**
  34151. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  34152. *
  34153. * @param {number} distance - The viewing distance.
  34154. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  34155. * @returns {Vector2} The view size.
  34156. */
  34157. getViewSize( distance, target ) {
  34158. this.getViewBounds( distance, _minTarget, _maxTarget );
  34159. return target.subVectors( _maxTarget, _minTarget );
  34160. }
  34161. /**
  34162. * Sets an offset in a larger frustum. This is useful for multi-window or
  34163. * multi-monitor/multi-machine setups.
  34164. *
  34165. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  34166. * the monitors are in grid like this
  34167. *```
  34168. * +---+---+---+
  34169. * | A | B | C |
  34170. * +---+---+---+
  34171. * | D | E | F |
  34172. * +---+---+---+
  34173. *```
  34174. * then for each monitor you would call it like this:
  34175. *```js
  34176. * const w = 1920;
  34177. * const h = 1080;
  34178. * const fullWidth = w * 3;
  34179. * const fullHeight = h * 2;
  34180. *
  34181. * // --A--
  34182. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  34183. * // --B--
  34184. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  34185. * // --C--
  34186. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  34187. * // --D--
  34188. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  34189. * // --E--
  34190. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  34191. * // --F--
  34192. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  34193. * ```
  34194. *
  34195. * Note there is no reason monitors have to be the same size or in a grid.
  34196. *
  34197. * @param {number} fullWidth - The full width of multiview setup.
  34198. * @param {number} fullHeight - The full height of multiview setup.
  34199. * @param {number} x - The horizontal offset of the subcamera.
  34200. * @param {number} y - The vertical offset of the subcamera.
  34201. * @param {number} width - The width of subcamera.
  34202. * @param {number} height - The height of subcamera.
  34203. */
  34204. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34205. this.aspect = fullWidth / fullHeight;
  34206. if ( this.view === null ) {
  34207. this.view = {
  34208. enabled: true,
  34209. fullWidth: 1,
  34210. fullHeight: 1,
  34211. offsetX: 0,
  34212. offsetY: 0,
  34213. width: 1,
  34214. height: 1
  34215. };
  34216. }
  34217. this.view.enabled = true;
  34218. this.view.fullWidth = fullWidth;
  34219. this.view.fullHeight = fullHeight;
  34220. this.view.offsetX = x;
  34221. this.view.offsetY = y;
  34222. this.view.width = width;
  34223. this.view.height = height;
  34224. this.updateProjectionMatrix();
  34225. }
  34226. /**
  34227. * Removes the view offset from the projection matrix.
  34228. */
  34229. clearViewOffset() {
  34230. if ( this.view !== null ) {
  34231. this.view.enabled = false;
  34232. }
  34233. this.updateProjectionMatrix();
  34234. }
  34235. /**
  34236. * Updates the camera's projection matrix. Must be called after any change of
  34237. * camera properties.
  34238. */
  34239. updateProjectionMatrix() {
  34240. const near = this.near;
  34241. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  34242. let height = 2 * top;
  34243. let width = this.aspect * height;
  34244. let left = -0.5 * width;
  34245. const view = this.view;
  34246. if ( this.view !== null && this.view.enabled ) {
  34247. const fullWidth = view.fullWidth,
  34248. fullHeight = view.fullHeight;
  34249. left += view.offsetX * width / fullWidth;
  34250. top -= view.offsetY * height / fullHeight;
  34251. width *= view.width / fullWidth;
  34252. height *= view.height / fullHeight;
  34253. }
  34254. const skew = this.filmOffset;
  34255. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  34256. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  34257. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34258. }
  34259. toJSON( meta ) {
  34260. const data = super.toJSON( meta );
  34261. data.object.fov = this.fov;
  34262. data.object.zoom = this.zoom;
  34263. data.object.near = this.near;
  34264. data.object.far = this.far;
  34265. data.object.focus = this.focus;
  34266. data.object.aspect = this.aspect;
  34267. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34268. data.object.filmGauge = this.filmGauge;
  34269. data.object.filmOffset = this.filmOffset;
  34270. return data;
  34271. }
  34272. }
  34273. /**
  34274. * Represents the shadow configuration of directional lights.
  34275. *
  34276. * @augments LightShadow
  34277. */
  34278. class SpotLightShadow extends LightShadow {
  34279. /**
  34280. * Constructs a new spot light shadow.
  34281. */
  34282. constructor() {
  34283. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  34284. /**
  34285. * This flag can be used for type testing.
  34286. *
  34287. * @type {boolean}
  34288. * @readonly
  34289. * @default true
  34290. */
  34291. this.isSpotLightShadow = true;
  34292. /**
  34293. * Used to focus the shadow camera. The camera's field of view is set as a
  34294. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  34295. *
  34296. * @type {number}
  34297. * @default 1
  34298. */
  34299. this.focus = 1;
  34300. /**
  34301. * Texture aspect ratio.
  34302. *
  34303. * @type {number}
  34304. * @default 1
  34305. */
  34306. this.aspect = 1;
  34307. }
  34308. updateMatrices( light ) {
  34309. const camera = this.camera;
  34310. const fov = RAD2DEG * 2 * light.angle * this.focus;
  34311. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  34312. const far = light.distance || camera.far;
  34313. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  34314. camera.fov = fov;
  34315. camera.aspect = aspect;
  34316. camera.far = far;
  34317. camera.updateProjectionMatrix();
  34318. }
  34319. super.updateMatrices( light );
  34320. }
  34321. copy( source ) {
  34322. super.copy( source );
  34323. this.focus = source.focus;
  34324. return this;
  34325. }
  34326. }
  34327. /**
  34328. * This light gets emitted from a single point in one direction, along a cone
  34329. * that increases in size the further from the light it gets.
  34330. *
  34331. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  34332. *
  34333. * ```js
  34334. * // white spotlight shining from the side, modulated by a texture
  34335. * const spotLight = new THREE.SpotLight( 0xffffff );
  34336. * spotLight.position.set( 100, 1000, 100 );
  34337. * spotLight.map = new THREE.TextureLoader().load( url );
  34338. *
  34339. * spotLight.castShadow = true;
  34340. * spotLight.shadow.mapSize.width = 1024;
  34341. * spotLight.shadow.mapSize.height = 1024;
  34342. * spotLight.shadow.camera.near = 500;
  34343. * spotLight.shadow.camera.far = 4000;
  34344. * spotLight.shadow.camera.fov = 30;s
  34345. * ```
  34346. *
  34347. * @augments Light
  34348. */
  34349. class SpotLight extends Light {
  34350. /**
  34351. * Constructs a new spot light.
  34352. *
  34353. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34354. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  34355. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  34356. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  34357. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  34358. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  34359. */
  34360. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  34361. super( color, intensity );
  34362. /**
  34363. * This flag can be used for type testing.
  34364. *
  34365. * @type {boolean}
  34366. * @readonly
  34367. * @default true
  34368. */
  34369. this.isSpotLight = true;
  34370. this.type = 'SpotLight';
  34371. this.position.copy( Object3D.DEFAULT_UP );
  34372. this.updateMatrix();
  34373. /**
  34374. * The spot light points from its position to the
  34375. * target's position.
  34376. *
  34377. * For the target's position to be changed to anything other
  34378. * than the default, it must be added to the scene.
  34379. *
  34380. * It is also possible to set the target to be another 3D object
  34381. * in the scene. The light will now track the target object.
  34382. *
  34383. * @type {Object3D}
  34384. */
  34385. this.target = new Object3D();
  34386. /**
  34387. * Maximum range of the light. `0` means no limit.
  34388. *
  34389. * @type {number}
  34390. * @default 0
  34391. */
  34392. this.distance = distance;
  34393. /**
  34394. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  34395. *
  34396. * @type {number}
  34397. * @default Math.PI/3
  34398. */
  34399. this.angle = angle;
  34400. /**
  34401. * Percent of the spotlight cone that is attenuated due to penumbra.
  34402. * Value range is `[0,1]`.
  34403. *
  34404. * @type {number}
  34405. * @default 0
  34406. */
  34407. this.penumbra = penumbra;
  34408. /**
  34409. * The amount the light dims along the distance of the light. In context of
  34410. * physically-correct rendering the default value should not be changed.
  34411. *
  34412. * @type {number}
  34413. * @default 2
  34414. */
  34415. this.decay = decay;
  34416. /**
  34417. * A texture used to modulate the color of the light. The spot light
  34418. * color is mixed with the RGB value of this texture, with a ratio
  34419. * corresponding to its alpha value. The cookie-like masking effect is
  34420. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  34421. *
  34422. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  34423. *
  34424. * @type {?Texture}
  34425. * @default null
  34426. */
  34427. this.map = null;
  34428. /**
  34429. * This property holds the light's shadow configuration.
  34430. *
  34431. * @type {SpotLightShadow}
  34432. */
  34433. this.shadow = new SpotLightShadow();
  34434. }
  34435. /**
  34436. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34437. * Changing the power will also change the light's intensity.
  34438. *
  34439. * @type {number}
  34440. */
  34441. get power() {
  34442. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34443. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  34444. return this.intensity * Math.PI;
  34445. }
  34446. set power( power ) {
  34447. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34448. this.intensity = power / Math.PI;
  34449. }
  34450. dispose() {
  34451. super.dispose();
  34452. this.shadow.dispose();
  34453. }
  34454. copy( source, recursive ) {
  34455. super.copy( source, recursive );
  34456. this.distance = source.distance;
  34457. this.angle = source.angle;
  34458. this.penumbra = source.penumbra;
  34459. this.decay = source.decay;
  34460. this.target = source.target.clone();
  34461. this.map = source.map;
  34462. this.shadow = source.shadow.clone();
  34463. return this;
  34464. }
  34465. toJSON( meta ) {
  34466. const data = super.toJSON( meta );
  34467. data.object.distance = this.distance;
  34468. data.object.angle = this.angle;
  34469. data.object.decay = this.decay;
  34470. data.object.penumbra = this.penumbra;
  34471. data.object.target = this.target.uuid;
  34472. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  34473. data.object.shadow = this.shadow.toJSON();
  34474. return data;
  34475. }
  34476. }
  34477. /**
  34478. * Represents the shadow configuration of point lights.
  34479. *
  34480. * @augments LightShadow
  34481. */
  34482. class PointLightShadow extends LightShadow {
  34483. /**
  34484. * Constructs a new point light shadow.
  34485. */
  34486. constructor() {
  34487. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  34488. /**
  34489. * This flag can be used for type testing.
  34490. *
  34491. * @type {boolean}
  34492. * @readonly
  34493. * @default true
  34494. */
  34495. this.isPointLightShadow = true;
  34496. }
  34497. }
  34498. /**
  34499. * A light that gets emitted from a single point in all directions. A common
  34500. * use case for this is to replicate the light emitted from a bare
  34501. * lightbulb.
  34502. *
  34503. * This light can cast shadows - see the {@link PointLightShadow} for details.
  34504. *
  34505. * ```js
  34506. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  34507. * light.position.set( 50, 50, 50 );
  34508. * scene.add( light );
  34509. * ```
  34510. *
  34511. * @augments Light
  34512. */
  34513. class PointLight extends Light {
  34514. /**
  34515. * Constructs a new point light.
  34516. *
  34517. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34518. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  34519. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  34520. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  34521. */
  34522. constructor( color, intensity, distance = 0, decay = 2 ) {
  34523. super( color, intensity );
  34524. /**
  34525. * This flag can be used for type testing.
  34526. *
  34527. * @type {boolean}
  34528. * @readonly
  34529. * @default true
  34530. */
  34531. this.isPointLight = true;
  34532. this.type = 'PointLight';
  34533. /**
  34534. * When distance is zero, light will attenuate according to inverse-square
  34535. * law to infinite distance. When distance is non-zero, light will attenuate
  34536. * according to inverse-square law until near the distance cutoff, where it
  34537. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  34538. * physically correct.
  34539. *
  34540. * @type {number}
  34541. * @default 0
  34542. */
  34543. this.distance = distance;
  34544. /**
  34545. * The amount the light dims along the distance of the light. In context of
  34546. * physically-correct rendering the default value should not be changed.
  34547. *
  34548. * @type {number}
  34549. * @default 2
  34550. */
  34551. this.decay = decay;
  34552. /**
  34553. * This property holds the light's shadow configuration.
  34554. *
  34555. * @type {PointLightShadow}
  34556. */
  34557. this.shadow = new PointLightShadow();
  34558. }
  34559. /**
  34560. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34561. * Changing the power will also change the light's intensity.
  34562. *
  34563. * @type {number}
  34564. */
  34565. get power() {
  34566. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34567. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  34568. return this.intensity * 4 * Math.PI;
  34569. }
  34570. set power( power ) {
  34571. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34572. this.intensity = power / ( 4 * Math.PI );
  34573. }
  34574. dispose() {
  34575. super.dispose();
  34576. this.shadow.dispose();
  34577. }
  34578. copy( source, recursive ) {
  34579. super.copy( source, recursive );
  34580. this.distance = source.distance;
  34581. this.decay = source.decay;
  34582. this.shadow = source.shadow.clone();
  34583. return this;
  34584. }
  34585. toJSON( meta ) {
  34586. const data = super.toJSON( meta );
  34587. data.object.distance = this.distance;
  34588. data.object.decay = this.decay;
  34589. data.object.shadow = this.shadow.toJSON();
  34590. return data;
  34591. }
  34592. }
  34593. /**
  34594. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  34595. *
  34596. * In this projection mode, an object's size in the rendered image stays
  34597. * constant regardless of its distance from the camera. This can be useful
  34598. * for rendering 2D scenes and UI elements, amongst other things.
  34599. *
  34600. * ```js
  34601. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  34602. * scene.add( camera );
  34603. * ```
  34604. *
  34605. * @augments Camera
  34606. */
  34607. class OrthographicCamera extends Camera {
  34608. /**
  34609. * Constructs a new orthographic camera.
  34610. *
  34611. * @param {number} [left=-1] - The left plane of the camera's frustum.
  34612. * @param {number} [right=1] - The right plane of the camera's frustum.
  34613. * @param {number} [top=1] - The top plane of the camera's frustum.
  34614. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  34615. * @param {number} [near=0.1] - The camera's near plane.
  34616. * @param {number} [far=2000] - The camera's far plane.
  34617. */
  34618. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  34619. super();
  34620. /**
  34621. * This flag can be used for type testing.
  34622. *
  34623. * @type {boolean}
  34624. * @readonly
  34625. * @default true
  34626. */
  34627. this.isOrthographicCamera = true;
  34628. this.type = 'OrthographicCamera';
  34629. /**
  34630. * The zoom factor of the camera.
  34631. *
  34632. * @type {number}
  34633. * @default 1
  34634. */
  34635. this.zoom = 1;
  34636. /**
  34637. * Represents the frustum window specification. This property should not be edited
  34638. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34639. *
  34640. * @type {?Object}
  34641. * @default null
  34642. */
  34643. this.view = null;
  34644. /**
  34645. * The left plane of the camera's frustum.
  34646. *
  34647. * @type {number}
  34648. * @default -1
  34649. */
  34650. this.left = left;
  34651. /**
  34652. * The right plane of the camera's frustum.
  34653. *
  34654. * @type {number}
  34655. * @default 1
  34656. */
  34657. this.right = right;
  34658. /**
  34659. * The top plane of the camera's frustum.
  34660. *
  34661. * @type {number}
  34662. * @default 1
  34663. */
  34664. this.top = top;
  34665. /**
  34666. * The bottom plane of the camera's frustum.
  34667. *
  34668. * @type {number}
  34669. * @default -1
  34670. */
  34671. this.bottom = bottom;
  34672. /**
  34673. * The camera's near plane. The valid range is greater than `0`
  34674. * and less than the current value of {@link OrthographicCamera#far}.
  34675. *
  34676. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34677. * valid value for an orthographic camera's near plane.
  34678. *
  34679. * @type {number}
  34680. * @default 0.1
  34681. */
  34682. this.near = near;
  34683. /**
  34684. * The camera's far plane. Must be greater than the
  34685. * current value of {@link OrthographicCamera#near}.
  34686. *
  34687. * @type {number}
  34688. * @default 2000
  34689. */
  34690. this.far = far;
  34691. this.updateProjectionMatrix();
  34692. }
  34693. copy( source, recursive ) {
  34694. super.copy( source, recursive );
  34695. this.left = source.left;
  34696. this.right = source.right;
  34697. this.top = source.top;
  34698. this.bottom = source.bottom;
  34699. this.near = source.near;
  34700. this.far = source.far;
  34701. this.zoom = source.zoom;
  34702. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34703. return this;
  34704. }
  34705. /**
  34706. * Sets an offset in a larger frustum. This is useful for multi-window or
  34707. * multi-monitor/multi-machine setups.
  34708. *
  34709. * @param {number} fullWidth - The full width of multiview setup.
  34710. * @param {number} fullHeight - The full height of multiview setup.
  34711. * @param {number} x - The horizontal offset of the subcamera.
  34712. * @param {number} y - The vertical offset of the subcamera.
  34713. * @param {number} width - The width of subcamera.
  34714. * @param {number} height - The height of subcamera.
  34715. * @see {@link PerspectiveCamera#setViewOffset}
  34716. */
  34717. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34718. if ( this.view === null ) {
  34719. this.view = {
  34720. enabled: true,
  34721. fullWidth: 1,
  34722. fullHeight: 1,
  34723. offsetX: 0,
  34724. offsetY: 0,
  34725. width: 1,
  34726. height: 1
  34727. };
  34728. }
  34729. this.view.enabled = true;
  34730. this.view.fullWidth = fullWidth;
  34731. this.view.fullHeight = fullHeight;
  34732. this.view.offsetX = x;
  34733. this.view.offsetY = y;
  34734. this.view.width = width;
  34735. this.view.height = height;
  34736. this.updateProjectionMatrix();
  34737. }
  34738. /**
  34739. * Removes the view offset from the projection matrix.
  34740. */
  34741. clearViewOffset() {
  34742. if ( this.view !== null ) {
  34743. this.view.enabled = false;
  34744. }
  34745. this.updateProjectionMatrix();
  34746. }
  34747. /**
  34748. * Updates the camera's projection matrix. Must be called after any change of
  34749. * camera properties.
  34750. */
  34751. updateProjectionMatrix() {
  34752. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34753. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34754. const cx = ( this.right + this.left ) / 2;
  34755. const cy = ( this.top + this.bottom ) / 2;
  34756. let left = cx - dx;
  34757. let right = cx + dx;
  34758. let top = cy + dy;
  34759. let bottom = cy - dy;
  34760. if ( this.view !== null && this.view.enabled ) {
  34761. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34762. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34763. left += scaleW * this.view.offsetX;
  34764. right = left + scaleW * this.view.width;
  34765. top -= scaleH * this.view.offsetY;
  34766. bottom = top - scaleH * this.view.height;
  34767. }
  34768. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34769. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34770. }
  34771. toJSON( meta ) {
  34772. const data = super.toJSON( meta );
  34773. data.object.zoom = this.zoom;
  34774. data.object.left = this.left;
  34775. data.object.right = this.right;
  34776. data.object.top = this.top;
  34777. data.object.bottom = this.bottom;
  34778. data.object.near = this.near;
  34779. data.object.far = this.far;
  34780. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34781. return data;
  34782. }
  34783. }
  34784. /**
  34785. * Represents the shadow configuration of directional lights.
  34786. *
  34787. * @augments LightShadow
  34788. */
  34789. class DirectionalLightShadow extends LightShadow {
  34790. /**
  34791. * Constructs a new directional light shadow.
  34792. */
  34793. constructor() {
  34794. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34795. /**
  34796. * This flag can be used for type testing.
  34797. *
  34798. * @type {boolean}
  34799. * @readonly
  34800. * @default true
  34801. */
  34802. this.isDirectionalLightShadow = true;
  34803. }
  34804. }
  34805. /**
  34806. * A light that gets emitted in a specific direction. This light will behave
  34807. * as though it is infinitely far away and the rays produced from it are all
  34808. * parallel. The common use case for this is to simulate daylight; the sun is
  34809. * far enough away that its position can be considered to be infinite, and
  34810. * all light rays coming from it are parallel.
  34811. *
  34812. * A common point of confusion for directional lights is that setting the
  34813. * rotation has no effect. This is because three.js's DirectionalLight is the
  34814. * equivalent to what is often called a 'Target Direct Light' in other
  34815. * applications.
  34816. *
  34817. * This means that its direction is calculated as pointing from the light's
  34818. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34819. * (as opposed to a 'Free Direct Light' that just has a rotation
  34820. * component).
  34821. *
  34822. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34823. *
  34824. * ```js
  34825. * // White directional light at half intensity shining from the top.
  34826. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34827. * scene.add( directionalLight );
  34828. * ```
  34829. *
  34830. * @augments Light
  34831. */
  34832. class DirectionalLight extends Light {
  34833. /**
  34834. * Constructs a new directional light.
  34835. *
  34836. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34837. * @param {number} [intensity=1] - The light's strength/intensity.
  34838. */
  34839. constructor( color, intensity ) {
  34840. super( color, intensity );
  34841. /**
  34842. * This flag can be used for type testing.
  34843. *
  34844. * @type {boolean}
  34845. * @readonly
  34846. * @default true
  34847. */
  34848. this.isDirectionalLight = true;
  34849. this.type = 'DirectionalLight';
  34850. this.position.copy( Object3D.DEFAULT_UP );
  34851. this.updateMatrix();
  34852. /**
  34853. * The directional light points from its position to the
  34854. * target's position.
  34855. *
  34856. * For the target's position to be changed to anything other
  34857. * than the default, it must be added to the scene.
  34858. *
  34859. * It is also possible to set the target to be another 3D object
  34860. * in the scene. The light will now track the target object.
  34861. *
  34862. * @type {Object3D}
  34863. */
  34864. this.target = new Object3D();
  34865. /**
  34866. * This property holds the light's shadow configuration.
  34867. *
  34868. * @type {DirectionalLightShadow}
  34869. */
  34870. this.shadow = new DirectionalLightShadow();
  34871. }
  34872. dispose() {
  34873. super.dispose();
  34874. this.shadow.dispose();
  34875. }
  34876. copy( source ) {
  34877. super.copy( source );
  34878. this.target = source.target.clone();
  34879. this.shadow = source.shadow.clone();
  34880. return this;
  34881. }
  34882. toJSON( meta ) {
  34883. const data = super.toJSON( meta );
  34884. data.object.shadow = this.shadow.toJSON();
  34885. data.object.target = this.target.uuid;
  34886. return data;
  34887. }
  34888. }
  34889. /**
  34890. * This light globally illuminates all objects in the scene equally.
  34891. *
  34892. * It cannot be used to cast shadows as it does not have a direction.
  34893. *
  34894. * ```js
  34895. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34896. * scene.add( light );
  34897. * ```
  34898. *
  34899. * @augments Light
  34900. */
  34901. class AmbientLight extends Light {
  34902. /**
  34903. * Constructs a new ambient light.
  34904. *
  34905. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34906. * @param {number} [intensity=1] - The light's strength/intensity.
  34907. */
  34908. constructor( color, intensity ) {
  34909. super( color, intensity );
  34910. /**
  34911. * This flag can be used for type testing.
  34912. *
  34913. * @type {boolean}
  34914. * @readonly
  34915. * @default true
  34916. */
  34917. this.isAmbientLight = true;
  34918. this.type = 'AmbientLight';
  34919. }
  34920. }
  34921. /**
  34922. * This class emits light uniformly across the face a rectangular plane.
  34923. * This light type can be used to simulate light sources such as bright
  34924. * windows or strip lighting.
  34925. *
  34926. * Important Notes:
  34927. *
  34928. * - There is no shadow support.
  34929. * - Only PBR materials are supported.
  34930. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34931. * into your app and init the uniforms/textures.
  34932. *
  34933. * ```js
  34934. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34935. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34936. *
  34937. * const intensity = 1; const width = 10; const height = 10;
  34938. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34939. * rectLight.position.set( 5, 5, 0 );
  34940. * rectLight.lookAt( 0, 0, 0 );
  34941. * scene.add( rectLight )
  34942. * ```
  34943. *
  34944. * @augments Light
  34945. */
  34946. class RectAreaLight extends Light {
  34947. /**
  34948. * Constructs a new area light.
  34949. *
  34950. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34951. * @param {number} [intensity=1] - The light's strength/intensity.
  34952. * @param {number} [width=10] - The width of the light.
  34953. * @param {number} [height=10] - The height of the light.
  34954. */
  34955. constructor( color, intensity, width = 10, height = 10 ) {
  34956. super( color, intensity );
  34957. /**
  34958. * This flag can be used for type testing.
  34959. *
  34960. * @type {boolean}
  34961. * @readonly
  34962. * @default true
  34963. */
  34964. this.isRectAreaLight = true;
  34965. this.type = 'RectAreaLight';
  34966. /**
  34967. * The width of the light.
  34968. *
  34969. * @type {number}
  34970. * @default 10
  34971. */
  34972. this.width = width;
  34973. /**
  34974. * The height of the light.
  34975. *
  34976. * @type {number}
  34977. * @default 10
  34978. */
  34979. this.height = height;
  34980. }
  34981. /**
  34982. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34983. * Changing the power will also change the light's intensity.
  34984. *
  34985. * @type {number}
  34986. */
  34987. get power() {
  34988. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34989. return this.intensity * this.width * this.height * Math.PI;
  34990. }
  34991. set power( power ) {
  34992. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34993. this.intensity = power / ( this.width * this.height * Math.PI );
  34994. }
  34995. copy( source ) {
  34996. super.copy( source );
  34997. this.width = source.width;
  34998. this.height = source.height;
  34999. return this;
  35000. }
  35001. toJSON( meta ) {
  35002. const data = super.toJSON( meta );
  35003. data.object.width = this.width;
  35004. data.object.height = this.height;
  35005. return data;
  35006. }
  35007. }
  35008. /**
  35009. * Represents a third-order spherical harmonics (SH). Light probes use this class
  35010. * to encode lighting information.
  35011. *
  35012. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  35013. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  35014. */
  35015. class SphericalHarmonics3 {
  35016. /**
  35017. * Constructs a new spherical harmonics.
  35018. */
  35019. constructor() {
  35020. /**
  35021. * This flag can be used for type testing.
  35022. *
  35023. * @type {boolean}
  35024. * @readonly
  35025. * @default true
  35026. */
  35027. this.isSphericalHarmonics3 = true;
  35028. /**
  35029. * An array holding the (9) SH coefficients.
  35030. *
  35031. * @type {Array<Vector3>}
  35032. */
  35033. this.coefficients = [];
  35034. for ( let i = 0; i < 9; i ++ ) {
  35035. this.coefficients.push( new Vector3() );
  35036. }
  35037. }
  35038. /**
  35039. * Sets the given SH coefficients to this instance by copying
  35040. * the values.
  35041. *
  35042. * @param {Array<Vector3>} coefficients - The SH coefficients.
  35043. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35044. */
  35045. set( coefficients ) {
  35046. for ( let i = 0; i < 9; i ++ ) {
  35047. this.coefficients[ i ].copy( coefficients[ i ] );
  35048. }
  35049. return this;
  35050. }
  35051. /**
  35052. * Sets all SH coefficients to `0`.
  35053. *
  35054. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35055. */
  35056. zero() {
  35057. for ( let i = 0; i < 9; i ++ ) {
  35058. this.coefficients[ i ].set( 0, 0, 0 );
  35059. }
  35060. return this;
  35061. }
  35062. /**
  35063. * Returns the radiance in the direction of the given normal.
  35064. *
  35065. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  35066. * @param {Vector3} target - The target vector that is used to store the method's result.
  35067. * @return {Vector3} The radiance.
  35068. */
  35069. getAt( normal, target ) {
  35070. // normal is assumed to be unit length
  35071. const x = normal.x, y = normal.y, z = normal.z;
  35072. const coeff = this.coefficients;
  35073. // band 0
  35074. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  35075. // band 1
  35076. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  35077. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  35078. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  35079. // band 2
  35080. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  35081. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  35082. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  35083. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  35084. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  35085. return target;
  35086. }
  35087. /**
  35088. * Returns the irradiance (radiance convolved with cosine lobe) in the
  35089. * direction of the given normal.
  35090. *
  35091. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  35092. * @param {Vector3} target - The target vector that is used to store the method's result.
  35093. * @return {Vector3} The irradiance.
  35094. */
  35095. getIrradianceAt( normal, target ) {
  35096. // normal is assumed to be unit length
  35097. const x = normal.x, y = normal.y, z = normal.z;
  35098. const coeff = this.coefficients;
  35099. // band 0
  35100. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  35101. // band 1
  35102. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  35103. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  35104. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  35105. // band 2
  35106. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  35107. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  35108. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  35109. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  35110. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  35111. return target;
  35112. }
  35113. /**
  35114. * Adds the given SH to this instance.
  35115. *
  35116. * @param {SphericalHarmonics3} sh - The SH to add.
  35117. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35118. */
  35119. add( sh ) {
  35120. for ( let i = 0; i < 9; i ++ ) {
  35121. this.coefficients[ i ].add( sh.coefficients[ i ] );
  35122. }
  35123. return this;
  35124. }
  35125. /**
  35126. * A convenience method for performing {@link SphericalHarmonics3#add} and
  35127. * {@link SphericalHarmonics3#scale} at once.
  35128. *
  35129. * @param {SphericalHarmonics3} sh - The SH to add.
  35130. * @param {number} s - The scale factor.
  35131. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35132. */
  35133. addScaledSH( sh, s ) {
  35134. for ( let i = 0; i < 9; i ++ ) {
  35135. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  35136. }
  35137. return this;
  35138. }
  35139. /**
  35140. * Scales this SH by the given scale factor.
  35141. *
  35142. * @param {number} s - The scale factor.
  35143. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35144. */
  35145. scale( s ) {
  35146. for ( let i = 0; i < 9; i ++ ) {
  35147. this.coefficients[ i ].multiplyScalar( s );
  35148. }
  35149. return this;
  35150. }
  35151. /**
  35152. * Linear interpolates between the given SH and this instance by the given
  35153. * alpha factor.
  35154. *
  35155. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  35156. * @param {number} alpha - The alpha factor.
  35157. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35158. */
  35159. lerp( sh, alpha ) {
  35160. for ( let i = 0; i < 9; i ++ ) {
  35161. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  35162. }
  35163. return this;
  35164. }
  35165. /**
  35166. * Returns `true` if this spherical harmonics is equal with the given one.
  35167. *
  35168. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  35169. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  35170. */
  35171. equals( sh ) {
  35172. for ( let i = 0; i < 9; i ++ ) {
  35173. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  35174. return false;
  35175. }
  35176. }
  35177. return true;
  35178. }
  35179. /**
  35180. * Copies the values of the given spherical harmonics to this instance.
  35181. *
  35182. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  35183. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35184. */
  35185. copy( sh ) {
  35186. return this.set( sh.coefficients );
  35187. }
  35188. /**
  35189. * Returns a new spherical harmonics with copied values from this instance.
  35190. *
  35191. * @return {SphericalHarmonics3} A clone of this instance.
  35192. */
  35193. clone() {
  35194. return new this.constructor().copy( this );
  35195. }
  35196. /**
  35197. * Sets the SH coefficients of this instance from the given array.
  35198. *
  35199. * @param {Array<number>} array - An array holding the SH coefficients.
  35200. * @param {number} [offset=0] - The array offset where to start copying.
  35201. * @return {SphericalHarmonics3} A clone of this instance.
  35202. */
  35203. fromArray( array, offset = 0 ) {
  35204. const coefficients = this.coefficients;
  35205. for ( let i = 0; i < 9; i ++ ) {
  35206. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  35207. }
  35208. return this;
  35209. }
  35210. /**
  35211. * Returns an array with the SH coefficients, or copies them into the provided
  35212. * array. The coefficients are represented as numbers.
  35213. *
  35214. * @param {Array<number>} [array=[]] - The target array.
  35215. * @param {number} [offset=0] - The array offset where to start copying.
  35216. * @return {Array<number>} An array with flat SH coefficients.
  35217. */
  35218. toArray( array = [], offset = 0 ) {
  35219. const coefficients = this.coefficients;
  35220. for ( let i = 0; i < 9; i ++ ) {
  35221. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  35222. }
  35223. return array;
  35224. }
  35225. /**
  35226. * Computes the SH basis for the given normal vector.
  35227. *
  35228. * @param {Vector3} normal - The normal.
  35229. * @param {Array<number>} shBasis - The target array holding the SH basis.
  35230. */
  35231. static getBasisAt( normal, shBasis ) {
  35232. // normal is assumed to be unit length
  35233. const x = normal.x, y = normal.y, z = normal.z;
  35234. // band 0
  35235. shBasis[ 0 ] = 0.282095;
  35236. // band 1
  35237. shBasis[ 1 ] = 0.488603 * y;
  35238. shBasis[ 2 ] = 0.488603 * z;
  35239. shBasis[ 3 ] = 0.488603 * x;
  35240. // band 2
  35241. shBasis[ 4 ] = 1.092548 * x * y;
  35242. shBasis[ 5 ] = 1.092548 * y * z;
  35243. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  35244. shBasis[ 7 ] = 1.092548 * x * z;
  35245. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  35246. }
  35247. }
  35248. /**
  35249. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  35250. * classical light sources (e.g. directional, point or spot lights), light
  35251. * probes do not emit light. Instead they store information about light
  35252. * passing through 3D space. During rendering, the light that hits a 3D
  35253. * object is approximated by using the data from the light probe.
  35254. *
  35255. * Light probes are usually created from (radiance) environment maps. The
  35256. * class {@link LightProbeGenerator} can be used to create light probes from
  35257. * cube textures or render targets. However, light estimation data could also
  35258. * be provided in other forms e.g. by WebXR. This enables the rendering of
  35259. * augmented reality content that reacts to real world lighting.
  35260. *
  35261. * The current probe implementation in three.js supports so-called diffuse
  35262. * light probes. This type of light probe is functionally equivalent to an
  35263. * irradiance environment map.
  35264. *
  35265. * @augments Light
  35266. */
  35267. class LightProbe extends Light {
  35268. /**
  35269. * Constructs a new light probe.
  35270. *
  35271. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  35272. * @param {number} [intensity=1] - The light's strength/intensity.
  35273. */
  35274. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  35275. super( undefined, intensity );
  35276. /**
  35277. * This flag can be used for type testing.
  35278. *
  35279. * @type {boolean}
  35280. * @readonly
  35281. * @default true
  35282. */
  35283. this.isLightProbe = true;
  35284. /**
  35285. * A light probe uses spherical harmonics to encode lighting information.
  35286. *
  35287. * @type {SphericalHarmonics3}
  35288. */
  35289. this.sh = sh;
  35290. }
  35291. copy( source ) {
  35292. super.copy( source );
  35293. this.sh.copy( source.sh );
  35294. return this;
  35295. }
  35296. toJSON( meta ) {
  35297. const data = super.toJSON( meta );
  35298. data.object.sh = this.sh.toArray();
  35299. return data;
  35300. }
  35301. }
  35302. const _customMaterials = {};
  35303. /**
  35304. * Class for loading materials. The files are internally
  35305. * loaded via {@link FileLoader}.
  35306. *
  35307. * ```js
  35308. * const loader = new THREE.MaterialLoader();
  35309. * const material = await loader.loadAsync( 'material.json' );
  35310. * ```
  35311. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  35312. *
  35313. * @augments Loader
  35314. */
  35315. class MaterialLoader extends Loader {
  35316. /**
  35317. * Constructs a new material loader.
  35318. *
  35319. * @param {LoadingManager} [manager] - The loading manager.
  35320. */
  35321. constructor( manager ) {
  35322. super( manager );
  35323. /**
  35324. * A dictionary holding textures used by the material.
  35325. *
  35326. * @type {Object<string,Texture>}
  35327. */
  35328. this.textures = {};
  35329. }
  35330. /**
  35331. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  35332. *
  35333. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35334. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  35335. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35336. * @param {onErrorCallback} onError - Executed when errors occur.
  35337. */
  35338. load( url, onLoad, onProgress, onError ) {
  35339. const scope = this;
  35340. const loader = new FileLoader( scope.manager );
  35341. loader.setPath( scope.path );
  35342. loader.setRequestHeader( scope.requestHeader );
  35343. loader.setWithCredentials( scope.withCredentials );
  35344. loader.load( url, function ( text ) {
  35345. try {
  35346. onLoad( scope.parse( JSON.parse( text ) ) );
  35347. } catch ( e ) {
  35348. if ( onError ) {
  35349. onError( e );
  35350. } else {
  35351. error( e );
  35352. }
  35353. scope.manager.itemError( url );
  35354. }
  35355. }, onProgress, onError );
  35356. }
  35357. /**
  35358. * Parses the given JSON object and returns a material.
  35359. *
  35360. * @param {Object} json - The serialized material.
  35361. * @return {Material} The parsed material.
  35362. */
  35363. parse( json ) {
  35364. const material = this.createMaterialFromType( json.type );
  35365. material.fromJSON( json, this.textures );
  35366. return material;
  35367. }
  35368. /**
  35369. * Textures are not embedded in the material JSON so they have
  35370. * to be injected before the loading process starts.
  35371. *
  35372. * @param {Object} value - A dictionary holding textures for material properties.
  35373. * @return {MaterialLoader} A reference to this material loader.
  35374. */
  35375. setTextures( value ) {
  35376. this.textures = value;
  35377. return this;
  35378. }
  35379. /**
  35380. * Creates a material for the given type.
  35381. *
  35382. * @param {string} type - The material type.
  35383. * @return {Material} The new material.
  35384. */
  35385. createMaterialFromType( type ) {
  35386. return MaterialLoader.createMaterialFromType( type );
  35387. }
  35388. /**
  35389. * Creates a material for the given type.
  35390. *
  35391. * @static
  35392. * @param {string} type - The material type.
  35393. * @return {Material} The new material.
  35394. */
  35395. static createMaterialFromType( type ) {
  35396. const materialLib = {
  35397. ShadowMaterial,
  35398. SpriteMaterial,
  35399. RawShaderMaterial,
  35400. ShaderMaterial,
  35401. PointsMaterial,
  35402. MeshPhysicalMaterial,
  35403. MeshStandardMaterial,
  35404. MeshPhongMaterial,
  35405. MeshToonMaterial,
  35406. MeshNormalMaterial,
  35407. MeshLambertMaterial,
  35408. MeshDepthMaterial,
  35409. MeshDistanceMaterial,
  35410. MeshBasicMaterial,
  35411. MeshMatcapMaterial,
  35412. LineDashedMaterial,
  35413. LineBasicMaterial,
  35414. Material,
  35415. ... _customMaterials
  35416. };
  35417. const MaterialType = materialLib[ type ];
  35418. let materialInstance;
  35419. if ( MaterialType === undefined ) {
  35420. warnOnce( `MaterialLoader: Unknown material type "${ type }". Use .registerMaterial() before starting the deserialization process.` );
  35421. materialInstance = new Material();
  35422. } else {
  35423. materialInstance = new MaterialType();
  35424. }
  35425. return materialInstance;
  35426. }
  35427. /**
  35428. * Registers the given material at the internal
  35429. * material library.
  35430. *
  35431. * @static
  35432. * @param {string} type - The material type.
  35433. * @param {Material.constructor} materialClass - The material class.
  35434. */
  35435. static registerMaterial( type, materialClass ) {
  35436. _customMaterials[ type ] = materialClass;
  35437. }
  35438. }
  35439. /**
  35440. * A class with loader utility functions.
  35441. */
  35442. class LoaderUtils {
  35443. /**
  35444. * Extracts the base URL from the given URL.
  35445. *
  35446. * @param {string} url -The URL to extract the base URL from.
  35447. * @return {string} The extracted base URL.
  35448. */
  35449. static extractUrlBase( url ) {
  35450. const index = url.lastIndexOf( '/' );
  35451. if ( index === -1 ) return './';
  35452. return url.slice( 0, index + 1 );
  35453. }
  35454. /**
  35455. * Resolves relative URLs against the given path. Absolute paths, data urls,
  35456. * and blob URLs will be returned as is. Invalid URLs will return an empty
  35457. * string.
  35458. *
  35459. * @param {string} url -The URL to resolve.
  35460. * @param {string} path - The base path for relative URLs to be resolved against.
  35461. * @return {string} The resolved URL.
  35462. */
  35463. static resolveURL( url, path ) {
  35464. // Invalid URL
  35465. if ( typeof url !== 'string' || url === '' ) return '';
  35466. // Host Relative URL
  35467. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35468. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35469. }
  35470. // Absolute URL http://,https://,//
  35471. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35472. // Data URI
  35473. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35474. // Blob URL
  35475. if ( /^blob:.*$/i.test( url ) ) return url;
  35476. // Relative URL
  35477. return path + url;
  35478. }
  35479. }
  35480. /**
  35481. * An instanced version of a geometry.
  35482. */
  35483. class InstancedBufferGeometry extends BufferGeometry {
  35484. /**
  35485. * Constructs a new instanced buffer geometry.
  35486. */
  35487. constructor() {
  35488. super();
  35489. /**
  35490. * This flag can be used for type testing.
  35491. *
  35492. * @type {boolean}
  35493. * @readonly
  35494. * @default true
  35495. */
  35496. this.isInstancedBufferGeometry = true;
  35497. this.type = 'InstancedBufferGeometry';
  35498. /**
  35499. * The instance count.
  35500. *
  35501. * @type {number}
  35502. * @default Infinity
  35503. */
  35504. this.instanceCount = Infinity;
  35505. }
  35506. copy( source ) {
  35507. super.copy( source );
  35508. this.instanceCount = source.instanceCount;
  35509. return this;
  35510. }
  35511. toJSON() {
  35512. const data = super.toJSON();
  35513. data.instanceCount = this.instanceCount;
  35514. data.isInstancedBufferGeometry = true;
  35515. return data;
  35516. }
  35517. }
  35518. /**
  35519. * Class for loading geometries. The files are internally
  35520. * loaded via {@link FileLoader}.
  35521. *
  35522. * ```js
  35523. * const loader = new THREE.BufferGeometryLoader();
  35524. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35525. *
  35526. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35527. * const object = new THREE.Mesh( geometry, material );
  35528. * scene.add( object );
  35529. * ```
  35530. *
  35531. * @augments Loader
  35532. */
  35533. class BufferGeometryLoader extends Loader {
  35534. /**
  35535. * Constructs a new geometry loader.
  35536. *
  35537. * @param {LoadingManager} [manager] - The loading manager.
  35538. */
  35539. constructor( manager ) {
  35540. super( manager );
  35541. }
  35542. /**
  35543. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35544. *
  35545. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35546. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35547. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35548. * @param {onErrorCallback} onError - Executed when errors occur.
  35549. */
  35550. load( url, onLoad, onProgress, onError ) {
  35551. const scope = this;
  35552. const loader = new FileLoader( scope.manager );
  35553. loader.setPath( scope.path );
  35554. loader.setRequestHeader( scope.requestHeader );
  35555. loader.setWithCredentials( scope.withCredentials );
  35556. loader.load( url, function ( text ) {
  35557. try {
  35558. onLoad( scope.parse( JSON.parse( text ) ) );
  35559. } catch ( e ) {
  35560. if ( onError ) {
  35561. onError( e );
  35562. } else {
  35563. error( e );
  35564. }
  35565. scope.manager.itemError( url );
  35566. }
  35567. }, onProgress, onError );
  35568. }
  35569. /**
  35570. * Parses the given JSON object and returns a geometry.
  35571. *
  35572. * @param {Object} json - The serialized geometry.
  35573. * @return {BufferGeometry} The parsed geometry.
  35574. */
  35575. parse( json ) {
  35576. const interleavedBufferMap = {};
  35577. const arrayBufferMap = {};
  35578. function getInterleavedBuffer( json, uuid ) {
  35579. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35580. const interleavedBuffers = json.interleavedBuffers;
  35581. const interleavedBuffer = interleavedBuffers[ uuid ];
  35582. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35583. const array = getTypedArray( interleavedBuffer.type, buffer );
  35584. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35585. ib.uuid = interleavedBuffer.uuid;
  35586. interleavedBufferMap[ uuid ] = ib;
  35587. return ib;
  35588. }
  35589. function getArrayBuffer( json, uuid ) {
  35590. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35591. const arrayBuffers = json.arrayBuffers;
  35592. const arrayBuffer = arrayBuffers[ uuid ];
  35593. const ab = new Uint32Array( arrayBuffer ).buffer;
  35594. arrayBufferMap[ uuid ] = ab;
  35595. return ab;
  35596. }
  35597. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35598. const index = json.data.index;
  35599. if ( index !== undefined ) {
  35600. const typedArray = getTypedArray( index.type, index.array );
  35601. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35602. }
  35603. const attributes = json.data.attributes;
  35604. for ( const key in attributes ) {
  35605. const attribute = attributes[ key ];
  35606. let bufferAttribute;
  35607. if ( attribute.isInterleavedBufferAttribute ) {
  35608. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35609. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35610. } else {
  35611. const typedArray = getTypedArray( attribute.type, attribute.array );
  35612. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35613. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35614. }
  35615. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35616. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35617. geometry.setAttribute( key, bufferAttribute );
  35618. }
  35619. const morphAttributes = json.data.morphAttributes;
  35620. if ( morphAttributes ) {
  35621. for ( const key in morphAttributes ) {
  35622. const attributeArray = morphAttributes[ key ];
  35623. const array = [];
  35624. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35625. const attribute = attributeArray[ i ];
  35626. let bufferAttribute;
  35627. if ( attribute.isInterleavedBufferAttribute ) {
  35628. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35629. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35630. } else {
  35631. const typedArray = getTypedArray( attribute.type, attribute.array );
  35632. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35633. }
  35634. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35635. array.push( bufferAttribute );
  35636. }
  35637. geometry.morphAttributes[ key ] = array;
  35638. }
  35639. }
  35640. const morphTargetsRelative = json.data.morphTargetsRelative;
  35641. if ( morphTargetsRelative ) {
  35642. geometry.morphTargetsRelative = true;
  35643. }
  35644. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35645. if ( groups !== undefined ) {
  35646. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35647. const group = groups[ i ];
  35648. geometry.addGroup( group.start, group.count, group.materialIndex );
  35649. }
  35650. }
  35651. const boundingSphere = json.data.boundingSphere;
  35652. if ( boundingSphere !== undefined ) {
  35653. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35654. }
  35655. if ( json.name ) geometry.name = json.name;
  35656. if ( json.userData ) geometry.userData = json.userData;
  35657. return geometry;
  35658. }
  35659. }
  35660. const _customGeometries = {};
  35661. /**
  35662. * 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).
  35663. * The files are internally loaded via {@link FileLoader}.
  35664. *
  35665. * ```js
  35666. * const loader = new THREE.ObjectLoader();
  35667. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35668. * scene.add( obj );
  35669. *
  35670. * // Alternatively, to parse a previously loaded JSON structure
  35671. * const object = await loader.parseAsync( a_json_object );
  35672. * scene.add( object );
  35673. * ```
  35674. *
  35675. * @augments Loader
  35676. */
  35677. class ObjectLoader extends Loader {
  35678. /**
  35679. * Constructs a new object loader.
  35680. *
  35681. * @param {LoadingManager} [manager] - The loading manager.
  35682. */
  35683. constructor( manager ) {
  35684. super( manager );
  35685. }
  35686. /**
  35687. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35688. *
  35689. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35690. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35691. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35692. * @param {onErrorCallback} onError - Executed when errors occur.
  35693. */
  35694. load( url, onLoad, onProgress, onError ) {
  35695. const scope = this;
  35696. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35697. this.resourcePath = this.resourcePath || path;
  35698. const loader = new FileLoader( this.manager );
  35699. loader.setPath( this.path );
  35700. loader.setRequestHeader( this.requestHeader );
  35701. loader.setWithCredentials( this.withCredentials );
  35702. loader.load( url, function ( text ) {
  35703. let json = null;
  35704. try {
  35705. json = JSON.parse( text );
  35706. } catch ( e ) {
  35707. if ( onError !== undefined ) onError( e );
  35708. error( 'ObjectLoader: Can\'t parse ' + url + '.', e.message );
  35709. return;
  35710. }
  35711. const metadata = json.metadata;
  35712. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35713. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35714. error( 'ObjectLoader: Can\'t load ' + url );
  35715. return;
  35716. }
  35717. scope.parse( json, onLoad );
  35718. }, onProgress, onError );
  35719. }
  35720. /**
  35721. * Async version of {@link ObjectLoader#load}.
  35722. *
  35723. * @async
  35724. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35725. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35726. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35727. */
  35728. async loadAsync( url, onProgress ) {
  35729. const scope = this;
  35730. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35731. this.resourcePath = this.resourcePath || path;
  35732. const loader = new FileLoader( this.manager );
  35733. loader.setPath( this.path );
  35734. loader.setRequestHeader( this.requestHeader );
  35735. loader.setWithCredentials( this.withCredentials );
  35736. const text = await loader.loadAsync( url, onProgress );
  35737. let json;
  35738. try {
  35739. json = JSON.parse( text );
  35740. } catch ( e ) {
  35741. throw new Error( 'THREE.ObjectLoader: Can\'t parse ' + url + '. ' + e.message );
  35742. }
  35743. const metadata = json.metadata;
  35744. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35745. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35746. }
  35747. return await scope.parseAsync( json );
  35748. }
  35749. /**
  35750. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35751. * but can also be used directly to parse a previously loaded JSON structure.
  35752. *
  35753. * @param {Object} json - The serialized 3D object.
  35754. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35755. * @return {Object3D} The parsed 3D object.
  35756. */
  35757. parse( json, onLoad ) {
  35758. const animations = this.parseAnimations( json.animations );
  35759. const shapes = this.parseShapes( json.shapes );
  35760. const geometries = this.parseGeometries( json.geometries, shapes );
  35761. const images = this.parseImages( json.images, function () {
  35762. if ( onLoad !== undefined ) onLoad( object );
  35763. } );
  35764. const textures = this.parseTextures( json.textures, images );
  35765. const materials = this.parseMaterials( json.materials, textures );
  35766. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35767. const skeletons = this.parseSkeletons( json.skeletons, object );
  35768. this.bindSkeletons( object, skeletons );
  35769. this.bindLightTargets( object );
  35770. //
  35771. if ( onLoad !== undefined ) {
  35772. let hasImages = false;
  35773. for ( const uuid in images ) {
  35774. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35775. hasImages = true;
  35776. break;
  35777. }
  35778. }
  35779. if ( hasImages === false ) onLoad( object );
  35780. }
  35781. return object;
  35782. }
  35783. /**
  35784. * Async version of {@link ObjectLoader#parse}.
  35785. *
  35786. * @param {Object} json - The serialized 3D object.
  35787. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35788. */
  35789. async parseAsync( json ) {
  35790. const animations = this.parseAnimations( json.animations );
  35791. const shapes = this.parseShapes( json.shapes );
  35792. const geometries = this.parseGeometries( json.geometries, shapes );
  35793. const images = await this.parseImagesAsync( json.images );
  35794. const textures = this.parseTextures( json.textures, images );
  35795. const materials = this.parseMaterials( json.materials, textures );
  35796. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35797. const skeletons = this.parseSkeletons( json.skeletons, object );
  35798. this.bindSkeletons( object, skeletons );
  35799. this.bindLightTargets( object );
  35800. return object;
  35801. }
  35802. /**
  35803. * Registers the given geometry at the internal
  35804. * geometry library.
  35805. *
  35806. * @static
  35807. * @param {string} type - The geometry type.
  35808. * @param {BufferGeometry.constructor} geometryClass - The geometry class.
  35809. */
  35810. static registerGeometry( type, geometryClass ) {
  35811. _customGeometries[ type ] = geometryClass;
  35812. }
  35813. // internals
  35814. parseShapes( json ) {
  35815. const shapes = {};
  35816. if ( json !== undefined ) {
  35817. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35818. const shape = new Shape().fromJSON( json[ i ] );
  35819. shapes[ shape.uuid ] = shape;
  35820. }
  35821. }
  35822. return shapes;
  35823. }
  35824. parseSkeletons( json, object ) {
  35825. const skeletons = {};
  35826. const bones = {};
  35827. // generate bone lookup table
  35828. object.traverse( function ( child ) {
  35829. if ( child.isBone ) bones[ child.uuid ] = child;
  35830. } );
  35831. // create skeletons
  35832. if ( json !== undefined ) {
  35833. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35834. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35835. skeletons[ skeleton.uuid ] = skeleton;
  35836. }
  35837. }
  35838. return skeletons;
  35839. }
  35840. parseGeometries( json, shapes ) {
  35841. const geometries = {};
  35842. if ( json !== undefined ) {
  35843. const bufferGeometryLoader = new BufferGeometryLoader();
  35844. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35845. let geometry;
  35846. const data = json[ i ];
  35847. switch ( data.type ) {
  35848. case 'BufferGeometry':
  35849. case 'InstancedBufferGeometry':
  35850. geometry = bufferGeometryLoader.parse( data );
  35851. break;
  35852. default:
  35853. if ( data.type in Geometries ) {
  35854. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35855. } else if ( data.type in _customGeometries ) {
  35856. geometry = _customGeometries[ data.type ].fromJSON( data, shapes );
  35857. } else {
  35858. warn( `ObjectLoader: Unknown geometry type "${ data.type }". Use .registerGeometry() before starting the deserialization process.` );
  35859. }
  35860. }
  35861. geometry.uuid = data.uuid;
  35862. if ( data.name !== undefined ) geometry.name = data.name;
  35863. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35864. geometries[ data.uuid ] = geometry;
  35865. }
  35866. }
  35867. return geometries;
  35868. }
  35869. parseMaterials( json, textures ) {
  35870. const cache = {}; // MultiMaterial
  35871. const materials = {};
  35872. if ( json !== undefined ) {
  35873. const loader = new MaterialLoader();
  35874. loader.setTextures( textures );
  35875. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35876. const data = json[ i ];
  35877. if ( cache[ data.uuid ] === undefined ) {
  35878. cache[ data.uuid ] = loader.parse( data );
  35879. }
  35880. materials[ data.uuid ] = cache[ data.uuid ];
  35881. }
  35882. }
  35883. return materials;
  35884. }
  35885. parseAnimations( json ) {
  35886. const animations = {};
  35887. if ( json !== undefined ) {
  35888. for ( let i = 0; i < json.length; i ++ ) {
  35889. const data = json[ i ];
  35890. const clip = AnimationClip.parse( data );
  35891. animations[ clip.uuid ] = clip;
  35892. }
  35893. }
  35894. return animations;
  35895. }
  35896. parseImages( json, onLoad ) {
  35897. const scope = this;
  35898. const images = {};
  35899. let loader;
  35900. function loadImage( url ) {
  35901. url = scope.manager.resolveURL( url );
  35902. scope.manager.itemStart( url );
  35903. return loader.load( url, function () {
  35904. scope.manager.itemEnd( url );
  35905. }, undefined, function () {
  35906. scope.manager.itemError( url );
  35907. scope.manager.itemEnd( url );
  35908. } );
  35909. }
  35910. function deserializeImage( image ) {
  35911. if ( typeof image === 'string' ) {
  35912. const url = image;
  35913. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35914. return loadImage( path );
  35915. } else {
  35916. if ( image.data ) {
  35917. return {
  35918. data: getTypedArray( image.type, image.data ),
  35919. width: image.width,
  35920. height: image.height
  35921. };
  35922. } else {
  35923. return null;
  35924. }
  35925. }
  35926. }
  35927. if ( json !== undefined && json.length > 0 ) {
  35928. const manager = new LoadingManager( onLoad );
  35929. loader = new ImageLoader( manager );
  35930. loader.setCrossOrigin( this.crossOrigin );
  35931. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35932. const image = json[ i ];
  35933. const url = image.url;
  35934. if ( Array.isArray( url ) ) {
  35935. // load array of images e.g CubeTexture
  35936. const imageArray = [];
  35937. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35938. const currentUrl = url[ j ];
  35939. const deserializedImage = deserializeImage( currentUrl );
  35940. if ( deserializedImage !== null ) {
  35941. if ( deserializedImage instanceof HTMLImageElement ) {
  35942. imageArray.push( deserializedImage );
  35943. } else {
  35944. // special case: handle array of data textures for cube textures
  35945. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35946. }
  35947. }
  35948. }
  35949. images[ image.uuid ] = new Source( imageArray );
  35950. } else {
  35951. // load single image
  35952. const deserializedImage = deserializeImage( image.url );
  35953. images[ image.uuid ] = new Source( deserializedImage );
  35954. }
  35955. }
  35956. }
  35957. return images;
  35958. }
  35959. async parseImagesAsync( json ) {
  35960. const scope = this;
  35961. const images = {};
  35962. let loader;
  35963. async function deserializeImage( image ) {
  35964. if ( typeof image === 'string' ) {
  35965. const url = image;
  35966. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35967. return await loader.loadAsync( path );
  35968. } else {
  35969. if ( image.data ) {
  35970. return {
  35971. data: getTypedArray( image.type, image.data ),
  35972. width: image.width,
  35973. height: image.height
  35974. };
  35975. } else {
  35976. return null;
  35977. }
  35978. }
  35979. }
  35980. if ( json !== undefined && json.length > 0 ) {
  35981. loader = new ImageLoader( this.manager );
  35982. loader.setCrossOrigin( this.crossOrigin );
  35983. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35984. const image = json[ i ];
  35985. const url = image.url;
  35986. if ( Array.isArray( url ) ) {
  35987. // load array of images e.g CubeTexture
  35988. const imageArray = [];
  35989. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35990. const currentUrl = url[ j ];
  35991. const deserializedImage = await deserializeImage( currentUrl );
  35992. if ( deserializedImage !== null ) {
  35993. if ( deserializedImage instanceof HTMLImageElement ) {
  35994. imageArray.push( deserializedImage );
  35995. } else {
  35996. // special case: handle array of data textures for cube textures
  35997. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35998. }
  35999. }
  36000. }
  36001. images[ image.uuid ] = new Source( imageArray );
  36002. } else {
  36003. // load single image
  36004. const deserializedImage = await deserializeImage( image.url );
  36005. images[ image.uuid ] = new Source( deserializedImage );
  36006. }
  36007. }
  36008. }
  36009. return images;
  36010. }
  36011. parseTextures( json, images ) {
  36012. function parseConstant( value, type ) {
  36013. if ( typeof value === 'number' ) return value;
  36014. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  36015. return type[ value ];
  36016. }
  36017. const textures = {};
  36018. if ( json !== undefined ) {
  36019. for ( let i = 0, l = json.length; i < l; i ++ ) {
  36020. const data = json[ i ];
  36021. if ( data.image === undefined ) {
  36022. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  36023. }
  36024. if ( images[ data.image ] === undefined ) {
  36025. warn( 'ObjectLoader: Undefined image', data.image );
  36026. }
  36027. const source = images[ data.image ];
  36028. const image = source.data;
  36029. let texture;
  36030. if ( Array.isArray( image ) ) {
  36031. texture = new CubeTexture();
  36032. if ( image.length === 6 ) texture.needsUpdate = true;
  36033. } else {
  36034. if ( image && image.data ) {
  36035. texture = new DataTexture();
  36036. } else {
  36037. texture = new Texture();
  36038. }
  36039. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  36040. }
  36041. texture.source = source;
  36042. texture.uuid = data.uuid;
  36043. if ( data.name !== undefined ) texture.name = data.name;
  36044. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  36045. if ( data.channel !== undefined ) texture.channel = data.channel;
  36046. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  36047. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  36048. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  36049. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  36050. if ( data.wrap !== undefined ) {
  36051. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  36052. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  36053. }
  36054. if ( data.format !== undefined ) texture.format = data.format;
  36055. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  36056. if ( data.type !== undefined ) texture.type = data.type;
  36057. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  36058. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  36059. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  36060. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  36061. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  36062. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  36063. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  36064. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  36065. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  36066. if ( data.normalized !== undefined ) texture.normalized = data.normalized;
  36067. if ( data.userData !== undefined ) texture.userData = data.userData;
  36068. textures[ data.uuid ] = texture;
  36069. }
  36070. }
  36071. return textures;
  36072. }
  36073. parseObject( data, geometries, materials, textures, animations ) {
  36074. let object;
  36075. function getGeometry( name ) {
  36076. if ( geometries[ name ] === undefined ) {
  36077. warn( 'ObjectLoader: Undefined geometry', name );
  36078. }
  36079. return geometries[ name ];
  36080. }
  36081. function getMaterial( name ) {
  36082. if ( name === undefined ) return undefined;
  36083. if ( Array.isArray( name ) ) {
  36084. const array = [];
  36085. for ( let i = 0, l = name.length; i < l; i ++ ) {
  36086. const uuid = name[ i ];
  36087. if ( materials[ uuid ] === undefined ) {
  36088. warn( 'ObjectLoader: Undefined material', uuid );
  36089. }
  36090. array.push( materials[ uuid ] );
  36091. }
  36092. return array;
  36093. }
  36094. if ( materials[ name ] === undefined ) {
  36095. warn( 'ObjectLoader: Undefined material', name );
  36096. }
  36097. return materials[ name ];
  36098. }
  36099. function getTexture( uuid ) {
  36100. if ( textures[ uuid ] === undefined ) {
  36101. warn( 'ObjectLoader: Undefined texture', uuid );
  36102. }
  36103. return textures[ uuid ];
  36104. }
  36105. let geometry, material;
  36106. switch ( data.type ) {
  36107. case 'Scene':
  36108. object = new Scene();
  36109. if ( data.background !== undefined ) {
  36110. if ( Number.isInteger( data.background ) ) {
  36111. object.background = new Color( data.background );
  36112. } else {
  36113. object.background = getTexture( data.background );
  36114. }
  36115. }
  36116. if ( data.environment !== undefined ) {
  36117. object.environment = getTexture( data.environment );
  36118. }
  36119. if ( data.fog !== undefined ) {
  36120. if ( data.fog.type === 'Fog' ) {
  36121. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  36122. } else if ( data.fog.type === 'FogExp2' ) {
  36123. object.fog = new FogExp2( data.fog.color, data.fog.density );
  36124. }
  36125. if ( data.fog.name !== '' ) {
  36126. object.fog.name = data.fog.name;
  36127. }
  36128. }
  36129. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  36130. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  36131. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  36132. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  36133. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  36134. break;
  36135. case 'PerspectiveCamera':
  36136. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  36137. if ( data.focus !== undefined ) object.focus = data.focus;
  36138. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  36139. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  36140. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  36141. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  36142. break;
  36143. case 'OrthographicCamera':
  36144. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  36145. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  36146. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  36147. break;
  36148. case 'AmbientLight':
  36149. object = new AmbientLight( data.color, data.intensity );
  36150. break;
  36151. case 'DirectionalLight':
  36152. object = new DirectionalLight( data.color, data.intensity );
  36153. object.target = data.target || '';
  36154. break;
  36155. case 'PointLight':
  36156. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  36157. break;
  36158. case 'RectAreaLight':
  36159. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  36160. break;
  36161. case 'SpotLight':
  36162. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  36163. object.target = data.target || '';
  36164. break;
  36165. case 'HemisphereLight':
  36166. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  36167. break;
  36168. case 'LightProbe':
  36169. const sh = new SphericalHarmonics3().fromArray( data.sh );
  36170. object = new LightProbe( sh, data.intensity );
  36171. break;
  36172. case 'SkinnedMesh':
  36173. geometry = getGeometry( data.geometry );
  36174. material = getMaterial( data.material );
  36175. object = new SkinnedMesh( geometry, material );
  36176. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  36177. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  36178. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  36179. break;
  36180. case 'Mesh':
  36181. geometry = getGeometry( data.geometry );
  36182. material = getMaterial( data.material );
  36183. object = new Mesh( geometry, material );
  36184. break;
  36185. case 'InstancedMesh':
  36186. geometry = getGeometry( data.geometry );
  36187. material = getMaterial( data.material );
  36188. const count = data.count;
  36189. const instanceMatrix = data.instanceMatrix;
  36190. const instanceColor = data.instanceColor;
  36191. object = new InstancedMesh( geometry, material, count );
  36192. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  36193. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  36194. break;
  36195. case 'BatchedMesh':
  36196. geometry = getGeometry( data.geometry );
  36197. material = getMaterial( data.material );
  36198. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  36199. object.geometry = geometry;
  36200. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  36201. object.sortObjects = data.sortObjects;
  36202. object._drawRanges = data.drawRanges;
  36203. object._reservedRanges = data.reservedRanges;
  36204. object._geometryInfo = data.geometryInfo.map( info => {
  36205. let box = null;
  36206. let sphere = null;
  36207. if ( info.boundingBox !== undefined ) {
  36208. box = new Box3().fromJSON( info.boundingBox );
  36209. }
  36210. if ( info.boundingSphere !== undefined ) {
  36211. sphere = new Sphere().fromJSON( info.boundingSphere );
  36212. }
  36213. return {
  36214. ...info,
  36215. boundingBox: box,
  36216. boundingSphere: sphere
  36217. };
  36218. } );
  36219. object._instanceInfo = data.instanceInfo;
  36220. object._availableInstanceIds = data._availableInstanceIds;
  36221. object._availableGeometryIds = data._availableGeometryIds;
  36222. object._nextIndexStart = data.nextIndexStart;
  36223. object._nextVertexStart = data.nextVertexStart;
  36224. object._geometryCount = data.geometryCount;
  36225. object._maxInstanceCount = data.maxInstanceCount;
  36226. object._maxVertexCount = data.maxVertexCount;
  36227. object._maxIndexCount = data.maxIndexCount;
  36228. object._geometryInitialized = data.geometryInitialized;
  36229. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  36230. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  36231. if ( data.colorsTexture !== undefined ) {
  36232. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  36233. }
  36234. if ( data.boundingSphere !== undefined ) {
  36235. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  36236. }
  36237. if ( data.boundingBox !== undefined ) {
  36238. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  36239. }
  36240. break;
  36241. case 'LOD':
  36242. object = new LOD();
  36243. break;
  36244. case 'Line':
  36245. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  36246. break;
  36247. case 'LineLoop':
  36248. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  36249. break;
  36250. case 'LineSegments':
  36251. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  36252. break;
  36253. case 'PointCloud':
  36254. case 'Points':
  36255. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  36256. break;
  36257. case 'Sprite':
  36258. object = new Sprite( getMaterial( data.material ) );
  36259. break;
  36260. case 'Group':
  36261. object = new Group();
  36262. break;
  36263. case 'Bone':
  36264. object = new Bone();
  36265. break;
  36266. default:
  36267. object = new Object3D();
  36268. }
  36269. object.uuid = data.uuid;
  36270. if ( data.name !== undefined ) object.name = data.name;
  36271. if ( data.matrix !== undefined ) {
  36272. object.matrix.fromArray( data.matrix );
  36273. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  36274. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  36275. } else {
  36276. if ( data.position !== undefined ) object.position.fromArray( data.position );
  36277. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  36278. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  36279. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  36280. }
  36281. if ( data.up !== undefined ) object.up.fromArray( data.up );
  36282. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  36283. if ( data.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, data.morphTargetDictionary );
  36284. if ( data.morphTargetInfluences !== undefined ) object.morphTargetInfluences = data.morphTargetInfluences.slice();
  36285. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  36286. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  36287. if ( data.shadow ) {
  36288. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  36289. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  36290. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  36291. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  36292. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  36293. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  36294. }
  36295. if ( data.visible !== undefined ) object.visible = data.visible;
  36296. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  36297. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  36298. if ( data.static !== undefined ) object.static = data.static;
  36299. if ( data.userData !== undefined ) object.userData = data.userData;
  36300. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  36301. if ( data.children !== undefined ) {
  36302. const children = data.children;
  36303. for ( let i = 0; i < children.length; i ++ ) {
  36304. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  36305. }
  36306. }
  36307. if ( data.animations !== undefined ) {
  36308. const objectAnimations = data.animations;
  36309. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  36310. const uuid = objectAnimations[ i ];
  36311. object.animations.push( animations[ uuid ] );
  36312. }
  36313. }
  36314. if ( data.type === 'LOD' ) {
  36315. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  36316. const levels = data.levels;
  36317. for ( let l = 0; l < levels.length; l ++ ) {
  36318. const level = levels[ l ];
  36319. const child = object.getObjectByProperty( 'uuid', level.object );
  36320. if ( child !== undefined ) {
  36321. object.addLevel( child, level.distance, level.hysteresis );
  36322. }
  36323. }
  36324. }
  36325. return object;
  36326. }
  36327. bindSkeletons( object, skeletons ) {
  36328. if ( Object.keys( skeletons ).length === 0 ) return;
  36329. object.traverse( function ( child ) {
  36330. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  36331. const skeleton = skeletons[ child.skeleton ];
  36332. if ( skeleton === undefined ) {
  36333. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  36334. } else {
  36335. child.bind( skeleton, child.bindMatrix );
  36336. }
  36337. }
  36338. } );
  36339. }
  36340. bindLightTargets( object ) {
  36341. object.traverse( function ( child ) {
  36342. if ( child.isDirectionalLight || child.isSpotLight ) {
  36343. const uuid = child.target;
  36344. const target = object.getObjectByProperty( 'uuid', uuid );
  36345. if ( target !== undefined ) {
  36346. child.target = target;
  36347. } else {
  36348. child.target = new Object3D();
  36349. }
  36350. }
  36351. } );
  36352. }
  36353. }
  36354. const TEXTURE_MAPPING = {
  36355. UVMapping: UVMapping,
  36356. CubeReflectionMapping: CubeReflectionMapping,
  36357. CubeRefractionMapping: CubeRefractionMapping,
  36358. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  36359. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  36360. CubeUVReflectionMapping: CubeUVReflectionMapping
  36361. };
  36362. const TEXTURE_WRAPPING = {
  36363. RepeatWrapping: RepeatWrapping,
  36364. ClampToEdgeWrapping: ClampToEdgeWrapping,
  36365. MirroredRepeatWrapping: MirroredRepeatWrapping
  36366. };
  36367. const TEXTURE_FILTER = {
  36368. NearestFilter: NearestFilter,
  36369. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  36370. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  36371. LinearFilter: LinearFilter,
  36372. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  36373. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  36374. };
  36375. const _errorMap = new WeakMap();
  36376. /**
  36377. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  36378. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  36379. * textures for rendering.
  36380. *
  36381. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  36382. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  36383. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  36384. *
  36385. * To match the default behaviour of {@link Texture}, the following options are needed:
  36386. *
  36387. * ```js
  36388. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  36389. * ```
  36390. *
  36391. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  36392. *
  36393. * ```js
  36394. * const loader = new THREE.ImageBitmapLoader();
  36395. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  36396. * const imageBitmap = await loader.loadAsync( 'image.png' );
  36397. *
  36398. * const texture = new THREE.Texture( imageBitmap );
  36399. * texture.needsUpdate = true;
  36400. * ```
  36401. *
  36402. * @augments Loader
  36403. */
  36404. class ImageBitmapLoader extends Loader {
  36405. /**
  36406. * Constructs a new image bitmap loader.
  36407. *
  36408. * @param {LoadingManager} [manager] - The loading manager.
  36409. */
  36410. constructor( manager ) {
  36411. super( manager );
  36412. /**
  36413. * This flag can be used for type testing.
  36414. *
  36415. * @type {boolean}
  36416. * @readonly
  36417. * @default true
  36418. */
  36419. this.isImageBitmapLoader = true;
  36420. if ( typeof createImageBitmap === 'undefined' ) {
  36421. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  36422. }
  36423. if ( typeof fetch === 'undefined' ) {
  36424. warn( 'ImageBitmapLoader: fetch() not supported.' );
  36425. }
  36426. /**
  36427. * Represents the loader options.
  36428. *
  36429. * @type {Object}
  36430. * @default {premultiplyAlpha:'none'}
  36431. */
  36432. this.options = { premultiplyAlpha: 'none' };
  36433. /**
  36434. * Used for aborting requests.
  36435. *
  36436. * @private
  36437. * @type {AbortController}
  36438. */
  36439. this._abortController = new AbortController();
  36440. }
  36441. /**
  36442. * Sets the given loader options. The structure of the object must match the `options` parameter of
  36443. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  36444. *
  36445. * Note: When caching is enabled, the cache key is based on the URL only. Loading the same URL with
  36446. * different options will return the cached result of the first request.
  36447. *
  36448. * @param {Object} options - The loader options to set.
  36449. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  36450. */
  36451. setOptions( options ) {
  36452. this.options = options;
  36453. return this;
  36454. }
  36455. /**
  36456. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  36457. *
  36458. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36459. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  36460. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  36461. * @param {onErrorCallback} onError - Executed when errors occur.
  36462. */
  36463. load( url, onLoad, onProgress, onError ) {
  36464. if ( url === undefined ) url = '';
  36465. if ( this.path !== undefined ) url = this.path + url;
  36466. url = this.manager.resolveURL( url );
  36467. const scope = this;
  36468. const cached = Cache.get( `image-bitmap:${url}` );
  36469. if ( cached !== undefined ) {
  36470. scope.manager.itemStart( url );
  36471. // If cached is a promise, wait for it to resolve
  36472. if ( cached.then ) {
  36473. cached.then( imageBitmap => {
  36474. // check if there is an error for the cached promise
  36475. if ( _errorMap.has( cached ) === true ) {
  36476. if ( onError ) onError( _errorMap.get( cached ) );
  36477. scope.manager.itemError( url );
  36478. scope.manager.itemEnd( url );
  36479. } else {
  36480. if ( onLoad ) onLoad( imageBitmap );
  36481. scope.manager.itemEnd( url );
  36482. }
  36483. } );
  36484. return;
  36485. }
  36486. // If cached is not a promise (i.e., it's already an imageBitmap)
  36487. setTimeout( function () {
  36488. if ( onLoad ) onLoad( cached );
  36489. scope.manager.itemEnd( url );
  36490. }, 0 );
  36491. return;
  36492. }
  36493. const fetchOptions = {};
  36494. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36495. fetchOptions.headers = this.requestHeader;
  36496. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36497. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36498. return res.blob();
  36499. } ).then( function ( blob ) {
  36500. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36501. } ).then( function ( imageBitmap ) {
  36502. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36503. if ( onLoad ) onLoad( imageBitmap );
  36504. scope.manager.itemEnd( url );
  36505. } ).catch( function ( e ) {
  36506. if ( onError ) onError( e );
  36507. _errorMap.set( promise, e );
  36508. Cache.remove( `image-bitmap:${url}` );
  36509. scope.manager.itemError( url );
  36510. scope.manager.itemEnd( url );
  36511. } );
  36512. Cache.add( `image-bitmap:${url}`, promise );
  36513. scope.manager.itemStart( url );
  36514. }
  36515. /**
  36516. * Aborts ongoing fetch requests.
  36517. *
  36518. * @return {ImageBitmapLoader} A reference to this instance.
  36519. */
  36520. abort() {
  36521. this._abortController.abort();
  36522. this._abortController = new AbortController();
  36523. return this;
  36524. }
  36525. }
  36526. let _context;
  36527. /**
  36528. * Manages the global audio context in the engine.
  36529. *
  36530. * @hideconstructor
  36531. */
  36532. class AudioContext {
  36533. /**
  36534. * Returns the global native audio context.
  36535. *
  36536. * @return {Window.AudioContext} The native audio context.
  36537. */
  36538. static getContext() {
  36539. if ( _context === undefined ) {
  36540. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36541. }
  36542. return _context;
  36543. }
  36544. /**
  36545. * Allows to set the global native audio context from outside.
  36546. *
  36547. * @param {Window.AudioContext} value - The native context to set.
  36548. */
  36549. static setContext( value ) {
  36550. _context = value;
  36551. }
  36552. }
  36553. /**
  36554. * Class for loading audio buffers. Audios are internally
  36555. * loaded via {@link FileLoader}.
  36556. *
  36557. * ```js
  36558. * const audioListener = new THREE.AudioListener();
  36559. * const ambientSound = new THREE.Audio( audioListener );
  36560. *
  36561. * const loader = new THREE.AudioLoader();
  36562. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36563. *
  36564. * ambientSound.setBuffer( audioBuffer );
  36565. * ambientSound.play();
  36566. * ```
  36567. *
  36568. * @augments Loader
  36569. */
  36570. class AudioLoader extends Loader {
  36571. /**
  36572. * Constructs a new audio loader.
  36573. *
  36574. * @param {LoadingManager} [manager] - The loading manager.
  36575. */
  36576. constructor( manager ) {
  36577. super( manager );
  36578. }
  36579. /**
  36580. * Starts loading from the given URL and passes the loaded audio buffer
  36581. * to the `onLoad()` callback.
  36582. *
  36583. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36584. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36585. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36586. * @param {onErrorCallback} onError - Executed when errors occur.
  36587. */
  36588. load( url, onLoad, onProgress, onError ) {
  36589. const scope = this;
  36590. const loader = new FileLoader( this.manager );
  36591. loader.setResponseType( 'arraybuffer' );
  36592. loader.setPath( this.path );
  36593. loader.setRequestHeader( this.requestHeader );
  36594. loader.setWithCredentials( this.withCredentials );
  36595. loader.load( url, function ( buffer ) {
  36596. try {
  36597. // Create a copy of the buffer. The `decodeAudioData` method
  36598. // detaches the buffer when complete, preventing reuse.
  36599. const bufferCopy = buffer.slice( 0 );
  36600. const context = AudioContext.getContext();
  36601. const decodeUrl = url + '#decode';
  36602. scope.manager.itemStart( decodeUrl ); // prevent loading manager from completing too early, see #33378
  36603. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36604. onLoad( audioBuffer );
  36605. scope.manager.itemEnd( decodeUrl );
  36606. } ).catch( function ( e ) {
  36607. handleError( e );
  36608. scope.manager.itemEnd( decodeUrl );
  36609. } );
  36610. } catch ( e ) {
  36611. handleError( e );
  36612. }
  36613. }, onProgress, onError );
  36614. function handleError( e ) {
  36615. if ( onError ) {
  36616. onError( e );
  36617. } else {
  36618. error( e );
  36619. }
  36620. scope.manager.itemError( url );
  36621. }
  36622. }
  36623. }
  36624. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36625. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36626. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36627. /**
  36628. * A special type of camera that uses two perspective cameras with
  36629. * stereoscopic projection. Can be used for rendering stereo effects
  36630. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36631. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36632. */
  36633. class StereoCamera {
  36634. /**
  36635. * Constructs a new stereo camera.
  36636. */
  36637. constructor() {
  36638. /**
  36639. * The type property is used for detecting the object type
  36640. * in context of serialization/deserialization.
  36641. *
  36642. * @type {string}
  36643. * @readonly
  36644. */
  36645. this.type = 'StereoCamera';
  36646. /**
  36647. * The aspect.
  36648. *
  36649. * @type {number}
  36650. * @default 1
  36651. */
  36652. this.aspect = 1;
  36653. /**
  36654. * The eye separation which represents the distance
  36655. * between the left and right camera.
  36656. *
  36657. * @type {number}
  36658. * @default 0.064
  36659. */
  36660. this.eyeSep = 0.064;
  36661. /**
  36662. * The camera representing the left eye. This is added to layer `1` so objects to be
  36663. * rendered by the left camera must also be added to this layer.
  36664. *
  36665. * @type {PerspectiveCamera}
  36666. */
  36667. this.cameraL = new PerspectiveCamera();
  36668. this.cameraL.layers.enable( 1 );
  36669. this.cameraL.matrixAutoUpdate = false;
  36670. /**
  36671. * The camera representing the right eye. This is added to layer `2` so objects to be
  36672. * rendered by the right camera must also be added to this layer.
  36673. *
  36674. * @type {PerspectiveCamera}
  36675. */
  36676. this.cameraR = new PerspectiveCamera();
  36677. this.cameraR.layers.enable( 2 );
  36678. this.cameraR.matrixAutoUpdate = false;
  36679. this._cache = {
  36680. focus: null,
  36681. fov: null,
  36682. aspect: null,
  36683. near: null,
  36684. far: null,
  36685. zoom: null,
  36686. eyeSep: null
  36687. };
  36688. }
  36689. /**
  36690. * Updates the stereo camera based on the given perspective camera.
  36691. *
  36692. * @param {PerspectiveCamera} camera - The perspective camera.
  36693. */
  36694. update( camera ) {
  36695. const cache = this._cache;
  36696. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36697. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36698. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36699. if ( needsUpdate ) {
  36700. cache.focus = camera.focus;
  36701. cache.fov = camera.fov;
  36702. cache.aspect = camera.aspect * this.aspect;
  36703. cache.near = camera.near;
  36704. cache.far = camera.far;
  36705. cache.zoom = camera.zoom;
  36706. cache.eyeSep = this.eyeSep;
  36707. // Off-axis stereoscopic effect based on
  36708. // http://paulbourke.net/stereographics/stereorender/
  36709. _projectionMatrix.copy( camera.projectionMatrix );
  36710. const eyeSepHalf = cache.eyeSep / 2;
  36711. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36712. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36713. let xmin, xmax;
  36714. // translate xOffset
  36715. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36716. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36717. // for left eye
  36718. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36719. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36720. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36721. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36722. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36723. // for right eye
  36724. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36725. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36726. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36727. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36728. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36729. }
  36730. this.cameraL.matrix.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36731. this.cameraL.matrixWorldNeedsUpdate = true;
  36732. this.cameraR.matrix.copy( camera.matrixWorld ).multiply( _eyeRight );
  36733. this.cameraR.matrixWorldNeedsUpdate = true;
  36734. }
  36735. }
  36736. const fov = -90; // negative fov is not an error
  36737. const aspect = 1;
  36738. /**
  36739. * A special type of camera that is positioned in 3D space to render its surroundings into a
  36740. * cube render target. The render target can then be used as an environment map for rendering
  36741. * realtime reflections in your scene.
  36742. *
  36743. * ```js
  36744. * // Create cube render target
  36745. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  36746. *
  36747. * // Create cube camera
  36748. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  36749. * scene.add( cubeCamera );
  36750. *
  36751. * // Create car
  36752. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  36753. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  36754. * scene.add( car );
  36755. *
  36756. * // Update the render target cube
  36757. * car.visible = false;
  36758. * cubeCamera.position.copy( car.position );
  36759. * cubeCamera.update( renderer, scene );
  36760. *
  36761. * // Render the scene
  36762. * car.visible = true;
  36763. * renderer.render( scene, camera );
  36764. * ```
  36765. *
  36766. * @augments Object3D
  36767. */
  36768. class CubeCamera extends Object3D {
  36769. /**
  36770. * Constructs a new cube camera.
  36771. *
  36772. * @param {number} near - The camera's near plane.
  36773. * @param {number} far - The camera's far plane.
  36774. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  36775. */
  36776. constructor( near, far, renderTarget ) {
  36777. super();
  36778. this.type = 'CubeCamera';
  36779. /**
  36780. * A reference to the cube render target.
  36781. *
  36782. * @type {WebGLCubeRenderTarget}
  36783. */
  36784. this.renderTarget = renderTarget;
  36785. /**
  36786. * The current active coordinate system.
  36787. *
  36788. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  36789. * @default null
  36790. */
  36791. this.coordinateSystem = null;
  36792. /**
  36793. * The current active mipmap level
  36794. *
  36795. * @type {number}
  36796. * @default 0
  36797. */
  36798. this.activeMipmapLevel = 0;
  36799. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  36800. cameraPX.layers = this.layers;
  36801. this.add( cameraPX );
  36802. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  36803. cameraNX.layers = this.layers;
  36804. this.add( cameraNX );
  36805. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  36806. cameraPY.layers = this.layers;
  36807. this.add( cameraPY );
  36808. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  36809. cameraNY.layers = this.layers;
  36810. this.add( cameraNY );
  36811. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  36812. cameraPZ.layers = this.layers;
  36813. this.add( cameraPZ );
  36814. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  36815. cameraNZ.layers = this.layers;
  36816. this.add( cameraNZ );
  36817. }
  36818. /**
  36819. * Must be called when the coordinate system of the cube camera is changed.
  36820. */
  36821. updateCoordinateSystem() {
  36822. const coordinateSystem = this.coordinateSystem;
  36823. const cameras = this.children.concat();
  36824. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  36825. for ( const camera of cameras ) this.remove( camera );
  36826. if ( coordinateSystem === WebGLCoordinateSystem ) {
  36827. cameraPX.up.set( 0, 1, 0 );
  36828. cameraPX.lookAt( 1, 0, 0 );
  36829. cameraNX.up.set( 0, 1, 0 );
  36830. cameraNX.lookAt( -1, 0, 0 );
  36831. cameraPY.up.set( 0, 0, -1 );
  36832. cameraPY.lookAt( 0, 1, 0 );
  36833. cameraNY.up.set( 0, 0, 1 );
  36834. cameraNY.lookAt( 0, -1, 0 );
  36835. cameraPZ.up.set( 0, 1, 0 );
  36836. cameraPZ.lookAt( 0, 0, 1 );
  36837. cameraNZ.up.set( 0, 1, 0 );
  36838. cameraNZ.lookAt( 0, 0, -1 );
  36839. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  36840. cameraPX.up.set( 0, -1, 0 );
  36841. cameraPX.lookAt( -1, 0, 0 );
  36842. cameraNX.up.set( 0, -1, 0 );
  36843. cameraNX.lookAt( 1, 0, 0 );
  36844. cameraPY.up.set( 0, 0, 1 );
  36845. cameraPY.lookAt( 0, 1, 0 );
  36846. cameraNY.up.set( 0, 0, -1 );
  36847. cameraNY.lookAt( 0, -1, 0 );
  36848. cameraPZ.up.set( 0, -1, 0 );
  36849. cameraPZ.lookAt( 0, 0, 1 );
  36850. cameraNZ.up.set( 0, -1, 0 );
  36851. cameraNZ.lookAt( 0, 0, -1 );
  36852. } else {
  36853. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  36854. }
  36855. for ( const camera of cameras ) {
  36856. this.add( camera );
  36857. camera.updateMatrixWorld();
  36858. }
  36859. }
  36860. /**
  36861. * Calling this method will render the given scene with the given renderer
  36862. * into the cube render target of the camera.
  36863. *
  36864. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  36865. * @param {Scene} scene - The scene to render.
  36866. */
  36867. update( renderer, scene ) {
  36868. if ( this.parent === null ) this.updateMatrixWorld();
  36869. const { renderTarget, activeMipmapLevel } = this;
  36870. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  36871. this.coordinateSystem = renderer.coordinateSystem;
  36872. this.updateCoordinateSystem();
  36873. }
  36874. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  36875. const currentRenderTarget = renderer.getRenderTarget();
  36876. const currentActiveCubeFace = renderer.getActiveCubeFace();
  36877. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  36878. const currentXrEnabled = renderer.xr.enabled;
  36879. renderer.xr.enabled = false;
  36880. const generateMipmaps = renderTarget.texture.generateMipmaps;
  36881. renderTarget.texture.generateMipmaps = false;
  36882. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  36883. let reversedDepthBuffer = false;
  36884. if ( renderer.isWebGLRenderer === true ) {
  36885. reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  36886. } else {
  36887. reversedDepthBuffer = renderer.reversedDepthBuffer;
  36888. }
  36889. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  36890. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36891. renderer.render( scene, cameraPX );
  36892. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  36893. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36894. renderer.render( scene, cameraNX );
  36895. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  36896. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36897. renderer.render( scene, cameraPY );
  36898. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  36899. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36900. renderer.render( scene, cameraNY );
  36901. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  36902. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36903. renderer.render( scene, cameraPZ );
  36904. // mipmaps are generated during the last call of render()
  36905. // at this point, all sides of the cube render target are defined
  36906. renderTarget.texture.generateMipmaps = generateMipmaps;
  36907. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  36908. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36909. renderer.render( scene, cameraNZ );
  36910. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  36911. renderer.xr.enabled = currentXrEnabled;
  36912. renderTarget.texture.needsPMREMUpdate = true;
  36913. }
  36914. }
  36915. /**
  36916. * This type of camera can be used in order to efficiently render a scene with a
  36917. * predefined set of cameras. This is an important performance aspect for
  36918. * rendering VR scenes.
  36919. *
  36920. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36921. * to define for each sub camera the `viewport` property which determines the
  36922. * part of the viewport that is rendered with this camera.
  36923. *
  36924. * @augments PerspectiveCamera
  36925. */
  36926. class ArrayCamera extends PerspectiveCamera {
  36927. /**
  36928. * Constructs a new array camera.
  36929. *
  36930. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36931. */
  36932. constructor( array = [] ) {
  36933. super();
  36934. /**
  36935. * This flag can be used for type testing.
  36936. *
  36937. * @type {boolean}
  36938. * @readonly
  36939. * @default true
  36940. */
  36941. this.isArrayCamera = true;
  36942. /**
  36943. * Whether this camera is used with multiview rendering or not.
  36944. *
  36945. * @type {boolean}
  36946. * @readonly
  36947. * @default false
  36948. */
  36949. this.isMultiViewCamera = false;
  36950. /**
  36951. * An array of perspective sub cameras.
  36952. *
  36953. * @type {Array<PerspectiveCamera>}
  36954. */
  36955. this.cameras = array;
  36956. }
  36957. }
  36958. /**
  36959. * This class is an alternative to {@link Clock} with a different API design and behavior.
  36960. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  36961. *
  36962. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  36963. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  36964. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  36965. * is inactive (e.g. tab switched or browser hidden).
  36966. *
  36967. * ```js
  36968. * const timer = new Timer();
  36969. * timer.connect( document ); // use Page Visibility API
  36970. * ```
  36971. */
  36972. class Timer {
  36973. /**
  36974. * Constructs a new timer.
  36975. */
  36976. constructor() {
  36977. this._previousTime = 0;
  36978. this._currentTime = 0;
  36979. this._startTime = performance.now();
  36980. this._delta = 0;
  36981. this._elapsed = 0;
  36982. this._timescale = 1;
  36983. this._document = null;
  36984. this._pageVisibilityHandler = null;
  36985. }
  36986. /**
  36987. * Connect the timer to the given document.Calling this method is not mandatory to
  36988. * use the timer but enables the usage of the Page Visibility API to avoid large time
  36989. * delta values.
  36990. *
  36991. * @param {Document} document - The document.
  36992. */
  36993. connect( document ) {
  36994. this._document = document;
  36995. // use Page Visibility API to avoid large time delta values
  36996. if ( document.hidden !== undefined ) {
  36997. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  36998. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  36999. }
  37000. }
  37001. /**
  37002. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  37003. */
  37004. disconnect() {
  37005. if ( this._pageVisibilityHandler !== null ) {
  37006. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  37007. this._pageVisibilityHandler = null;
  37008. }
  37009. this._document = null;
  37010. }
  37011. /**
  37012. * Returns the time delta in seconds.
  37013. *
  37014. * @return {number} The time delta in second.
  37015. */
  37016. getDelta() {
  37017. return this._delta / 1000;
  37018. }
  37019. /**
  37020. * Returns the elapsed time in seconds.
  37021. *
  37022. * @return {number} The elapsed time in second.
  37023. */
  37024. getElapsed() {
  37025. return this._elapsed / 1000;
  37026. }
  37027. /**
  37028. * Returns the timescale.
  37029. *
  37030. * @return {number} The timescale.
  37031. */
  37032. getTimescale() {
  37033. return this._timescale;
  37034. }
  37035. /**
  37036. * Sets the given timescale which scale the time delta computation
  37037. * in `update()`.
  37038. *
  37039. * @param {number} timescale - The timescale to set.
  37040. * @return {Timer} A reference to this timer.
  37041. */
  37042. setTimescale( timescale ) {
  37043. this._timescale = timescale;
  37044. return this;
  37045. }
  37046. /**
  37047. * Resets the time computation for the current simulation step.
  37048. *
  37049. * @return {Timer} A reference to this timer.
  37050. */
  37051. reset() {
  37052. this._currentTime = performance.now() - this._startTime;
  37053. return this;
  37054. }
  37055. /**
  37056. * Can be used to free all internal resources. Usually called when
  37057. * the timer instance isn't required anymore.
  37058. */
  37059. dispose() {
  37060. this.disconnect();
  37061. }
  37062. /**
  37063. * Updates the internal state of the timer. This method should be called
  37064. * once per simulation step and before you perform queries against the timer
  37065. * (e.g. via `getDelta()`).
  37066. *
  37067. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  37068. * from the `requestAnimationFrame` callback argument. If not provided, the current
  37069. * time will be determined with `performance.now`.
  37070. * @return {Timer} A reference to this timer.
  37071. */
  37072. update( timestamp ) {
  37073. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  37074. this._delta = 0;
  37075. } else {
  37076. this._previousTime = this._currentTime;
  37077. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  37078. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  37079. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  37080. }
  37081. return this;
  37082. }
  37083. }
  37084. function handleVisibilityChange() {
  37085. if ( this._document.hidden === false ) this.reset();
  37086. }
  37087. const _position$1 = /*@__PURE__*/ new Vector3();
  37088. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  37089. const _scale$1 = /*@__PURE__*/ new Vector3();
  37090. const _forward = /*@__PURE__*/ new Vector3();
  37091. const _up = /*@__PURE__*/ new Vector3();
  37092. /**
  37093. * The class represents a virtual listener of the all positional and non-positional audio effects
  37094. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  37095. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  37096. *
  37097. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  37098. * camera represents the 3D transformation of the listener.
  37099. *
  37100. * @augments Object3D
  37101. */
  37102. class AudioListener extends Object3D {
  37103. /**
  37104. * Constructs a new audio listener.
  37105. */
  37106. constructor() {
  37107. super();
  37108. this.type = 'AudioListener';
  37109. /**
  37110. * The native audio context.
  37111. *
  37112. * @type {AudioContext}
  37113. * @readonly
  37114. */
  37115. this.context = AudioContext.getContext();
  37116. /**
  37117. * The gain node used for volume control.
  37118. *
  37119. * @type {GainNode}
  37120. * @readonly
  37121. */
  37122. this.gain = this.context.createGain();
  37123. this.gain.connect( this.context.destination );
  37124. /**
  37125. * An optional filter.
  37126. *
  37127. * Defined via {@link AudioListener#setFilter}.
  37128. *
  37129. * @type {?AudioNode}
  37130. * @default null
  37131. * @readonly
  37132. */
  37133. this.filter = null;
  37134. /**
  37135. * Time delta values required for `linearRampToValueAtTime()` usage.
  37136. *
  37137. * @type {number}
  37138. * @default 0
  37139. * @readonly
  37140. */
  37141. this.timeDelta = 0;
  37142. // private
  37143. this._timer = new Timer();
  37144. }
  37145. /**
  37146. * Returns the listener's input node.
  37147. *
  37148. * This method is used by other audio nodes to connect to this listener.
  37149. *
  37150. * @return {GainNode} The input node.
  37151. */
  37152. getInput() {
  37153. return this.gain;
  37154. }
  37155. /**
  37156. * Removes the current filter from this listener.
  37157. *
  37158. * @return {AudioListener} A reference to this listener.
  37159. */
  37160. removeFilter() {
  37161. if ( this.filter !== null ) {
  37162. this.gain.disconnect( this.filter );
  37163. this.filter.disconnect( this.context.destination );
  37164. this.gain.connect( this.context.destination );
  37165. this.filter = null;
  37166. }
  37167. return this;
  37168. }
  37169. /**
  37170. * Returns the current set filter.
  37171. *
  37172. * @return {?AudioNode} The filter.
  37173. */
  37174. getFilter() {
  37175. return this.filter;
  37176. }
  37177. /**
  37178. * Sets the given filter to this listener.
  37179. *
  37180. * @param {AudioNode} value - The filter to set.
  37181. * @return {AudioListener} A reference to this listener.
  37182. */
  37183. setFilter( value ) {
  37184. if ( this.filter !== null ) {
  37185. this.gain.disconnect( this.filter );
  37186. this.filter.disconnect( this.context.destination );
  37187. } else {
  37188. this.gain.disconnect( this.context.destination );
  37189. }
  37190. this.filter = value;
  37191. this.gain.connect( this.filter );
  37192. this.filter.connect( this.context.destination );
  37193. return this;
  37194. }
  37195. /**
  37196. * Returns the applications master volume.
  37197. *
  37198. * @return {number} The master volume.
  37199. */
  37200. getMasterVolume() {
  37201. return this.gain.gain.value;
  37202. }
  37203. /**
  37204. * Sets the applications master volume. This volume setting affects
  37205. * all audio nodes in the scene.
  37206. *
  37207. * @param {number} value - The master volume to set.
  37208. * @return {AudioListener} A reference to this listener.
  37209. */
  37210. setMasterVolume( value ) {
  37211. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37212. return this;
  37213. }
  37214. updateMatrixWorld( force ) {
  37215. super.updateMatrixWorld( force );
  37216. this._timer.update();
  37217. const listener = this.context.listener;
  37218. this.timeDelta = this._timer.getDelta();
  37219. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  37220. // the initial forward and up directions must be orthogonal
  37221. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  37222. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  37223. if ( listener.positionX ) {
  37224. // code path for Chrome (see #14393)
  37225. const endTime = this.context.currentTime + this.timeDelta;
  37226. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  37227. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  37228. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  37229. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  37230. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  37231. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  37232. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  37233. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  37234. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  37235. } else {
  37236. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  37237. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  37238. }
  37239. }
  37240. }
  37241. /**
  37242. * Represents a non-positional ( global ) audio object.
  37243. *
  37244. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  37245. *
  37246. * ```js
  37247. * // create an AudioListener and add it to the camera
  37248. * const listener = new THREE.AudioListener();
  37249. * camera.add( listener );
  37250. *
  37251. * // create a global audio source
  37252. * const sound = new THREE.Audio( listener );
  37253. *
  37254. * // load a sound and set it as the Audio object's buffer
  37255. * const audioLoader = new THREE.AudioLoader();
  37256. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37257. * sound.setBuffer( buffer );
  37258. * sound.setLoop( true );
  37259. * sound.setVolume( 0.5 );
  37260. * sound.play();
  37261. * });
  37262. * ```
  37263. *
  37264. * @augments Object3D
  37265. */
  37266. class Audio extends Object3D {
  37267. /**
  37268. * Constructs a new audio.
  37269. *
  37270. * @param {AudioListener} listener - The global audio listener.
  37271. */
  37272. constructor( listener ) {
  37273. super();
  37274. this.type = 'Audio';
  37275. /**
  37276. * The global audio listener.
  37277. *
  37278. * @type {AudioListener}
  37279. * @readonly
  37280. */
  37281. this.listener = listener;
  37282. /**
  37283. * The audio context.
  37284. *
  37285. * @type {AudioContext}
  37286. * @readonly
  37287. */
  37288. this.context = listener.context;
  37289. /**
  37290. * The gain node used for volume control.
  37291. *
  37292. * @type {GainNode}
  37293. * @readonly
  37294. */
  37295. this.gain = this.context.createGain();
  37296. this.gain.connect( listener.getInput() );
  37297. /**
  37298. * Whether to start playback automatically or not.
  37299. *
  37300. * @type {boolean}
  37301. * @default false
  37302. */
  37303. this.autoplay = false;
  37304. /**
  37305. * A reference to an audio buffer.
  37306. *
  37307. * Defined via {@link Audio#setBuffer}.
  37308. *
  37309. * @type {?AudioBuffer}
  37310. * @default null
  37311. * @readonly
  37312. */
  37313. this.buffer = null;
  37314. /**
  37315. * Modify pitch, measured in cents. +/- 100 is a semitone.
  37316. * +/- 1200 is an octave.
  37317. *
  37318. * Defined via {@link Audio#setDetune}.
  37319. *
  37320. * @type {number}
  37321. * @default 0
  37322. * @readonly
  37323. */
  37324. this.detune = 0;
  37325. /**
  37326. * Whether the audio should loop or not.
  37327. *
  37328. * Defined via {@link Audio#setLoop}.
  37329. *
  37330. * @type {boolean}
  37331. * @default false
  37332. * @readonly
  37333. */
  37334. this.loop = false;
  37335. /**
  37336. * Defines where in the audio buffer the replay should
  37337. * start, in seconds.
  37338. *
  37339. * @type {number}
  37340. * @default 0
  37341. */
  37342. this.loopStart = 0;
  37343. /**
  37344. * Defines where in the audio buffer the replay should
  37345. * stop, in seconds.
  37346. *
  37347. * @type {number}
  37348. * @default 0
  37349. */
  37350. this.loopEnd = 0;
  37351. /**
  37352. * An offset to the time within the audio buffer the playback
  37353. * should begin, in seconds.
  37354. *
  37355. * @type {number}
  37356. * @default 0
  37357. */
  37358. this.offset = 0;
  37359. /**
  37360. * Overrides the default duration of the audio.
  37361. *
  37362. * @type {undefined|number}
  37363. * @default undefined
  37364. */
  37365. this.duration = undefined;
  37366. /**
  37367. * The playback speed.
  37368. *
  37369. * Defined via {@link Audio#setPlaybackRate}.
  37370. *
  37371. * @type {number}
  37372. * @readonly
  37373. * @default 1
  37374. */
  37375. this.playbackRate = 1;
  37376. /**
  37377. * Indicates whether the audio is playing or not.
  37378. *
  37379. * This flag will be automatically set when using {@link Audio#play},
  37380. * {@link Audio#pause}, {@link Audio#stop}.
  37381. *
  37382. * @type {boolean}
  37383. * @readonly
  37384. * @default false
  37385. */
  37386. this.isPlaying = false;
  37387. /**
  37388. * Indicates whether the audio playback can be controlled
  37389. * with method like {@link Audio#play} or {@link Audio#pause}.
  37390. *
  37391. * This flag will be automatically set when audio sources are
  37392. * defined.
  37393. *
  37394. * @type {boolean}
  37395. * @readonly
  37396. * @default true
  37397. */
  37398. this.hasPlaybackControl = true;
  37399. /**
  37400. * Holds a reference to the current audio source.
  37401. *
  37402. * The property is automatically by one of the `set*()` methods.
  37403. *
  37404. * @type {?AudioNode}
  37405. * @readonly
  37406. * @default null
  37407. */
  37408. this.source = null;
  37409. /**
  37410. * Defines the source type.
  37411. *
  37412. * The property is automatically set by one of the `set*()` methods.
  37413. *
  37414. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  37415. * @readonly
  37416. * @default 'empty'
  37417. */
  37418. this.sourceType = 'empty';
  37419. this._startedAt = 0;
  37420. this._progress = 0;
  37421. this._connected = false;
  37422. /**
  37423. * Can be used to apply a variety of low-order filters to create
  37424. * more complex sound effects e.g. via `BiquadFilterNode`.
  37425. *
  37426. * The property is automatically set by {@link Audio#setFilters}.
  37427. *
  37428. * @type {Array<AudioNode>}
  37429. * @readonly
  37430. */
  37431. this.filters = [];
  37432. }
  37433. /**
  37434. * Returns the output audio node.
  37435. *
  37436. * @return {GainNode} The output node.
  37437. */
  37438. getOutput() {
  37439. return this.gain;
  37440. }
  37441. /**
  37442. * Sets the given audio node as the source of this instance.
  37443. *
  37444. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  37445. *
  37446. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  37447. * @return {Audio} A reference to this instance.
  37448. */
  37449. setNodeSource( audioNode ) {
  37450. this.hasPlaybackControl = false;
  37451. this.sourceType = 'audioNode';
  37452. this.source = audioNode;
  37453. this.connect();
  37454. return this;
  37455. }
  37456. /**
  37457. * Sets the given media element as the source of this instance.
  37458. *
  37459. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  37460. *
  37461. * @param {HTMLMediaElement} mediaElement - The media element.
  37462. * @return {Audio} A reference to this instance.
  37463. */
  37464. setMediaElementSource( mediaElement ) {
  37465. this.hasPlaybackControl = false;
  37466. this.sourceType = 'mediaNode';
  37467. this.source = this.context.createMediaElementSource( mediaElement );
  37468. this.connect();
  37469. return this;
  37470. }
  37471. /**
  37472. * Sets the given media stream as the source of this instance.
  37473. *
  37474. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  37475. *
  37476. * @param {MediaStream} mediaStream - The media stream.
  37477. * @return {Audio} A reference to this instance.
  37478. */
  37479. setMediaStreamSource( mediaStream ) {
  37480. this.hasPlaybackControl = false;
  37481. this.sourceType = 'mediaStreamNode';
  37482. this.source = this.context.createMediaStreamSource( mediaStream );
  37483. this.connect();
  37484. return this;
  37485. }
  37486. /**
  37487. * Sets the given audio buffer as the source of this instance.
  37488. *
  37489. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  37490. *
  37491. * @param {AudioBuffer} audioBuffer - The audio buffer.
  37492. * @return {Audio} A reference to this instance.
  37493. */
  37494. setBuffer( audioBuffer ) {
  37495. this.buffer = audioBuffer;
  37496. this.sourceType = 'buffer';
  37497. if ( this.autoplay ) this.play();
  37498. return this;
  37499. }
  37500. /**
  37501. * Starts the playback of the audio.
  37502. *
  37503. * Can only be used with compatible audio sources that allow playback control.
  37504. *
  37505. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  37506. * @return {Audio|undefined} A reference to this instance.
  37507. */
  37508. play( delay = 0 ) {
  37509. if ( this.isPlaying === true ) {
  37510. warn( 'Audio: Audio is already playing.' );
  37511. return;
  37512. }
  37513. if ( this.hasPlaybackControl === false ) {
  37514. warn( 'Audio: this Audio has no playback control.' );
  37515. return;
  37516. }
  37517. this._startedAt = this.context.currentTime + delay;
  37518. const source = this.context.createBufferSource();
  37519. source.buffer = this.buffer;
  37520. source.loop = this.loop;
  37521. source.loopStart = this.loopStart;
  37522. source.loopEnd = this.loopEnd;
  37523. source.onended = this.onEnded.bind( this );
  37524. source.start( this._startedAt, this._progress + this.offset, this.duration );
  37525. this.isPlaying = true;
  37526. this.source = source;
  37527. this.setDetune( this.detune );
  37528. this.setPlaybackRate( this.playbackRate );
  37529. return this.connect();
  37530. }
  37531. /**
  37532. * Pauses the playback of the audio.
  37533. *
  37534. * Can only be used with compatible audio sources that allow playback control.
  37535. *
  37536. * @return {Audio|undefined} A reference to this instance.
  37537. */
  37538. pause() {
  37539. if ( this.hasPlaybackControl === false ) {
  37540. warn( 'Audio: this Audio has no playback control.' );
  37541. return;
  37542. }
  37543. if ( this.isPlaying === true ) {
  37544. // update current progress
  37545. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  37546. if ( this.loop === true ) {
  37547. // ensure _progress does not exceed duration with looped audios
  37548. this._progress = this._progress % ( this.duration || this.buffer.duration );
  37549. }
  37550. this.source.stop();
  37551. this.source.onended = null;
  37552. this.isPlaying = false;
  37553. }
  37554. return this;
  37555. }
  37556. /**
  37557. * Stops the playback of the audio.
  37558. *
  37559. * Can only be used with compatible audio sources that allow playback control.
  37560. *
  37561. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  37562. * @return {Audio|undefined} A reference to this instance.
  37563. */
  37564. stop( delay = 0 ) {
  37565. if ( this.hasPlaybackControl === false ) {
  37566. warn( 'Audio: this Audio has no playback control.' );
  37567. return;
  37568. }
  37569. this._progress = 0;
  37570. if ( this.source !== null ) {
  37571. this.source.stop( this.context.currentTime + delay );
  37572. this.source.onended = null;
  37573. }
  37574. this.isPlaying = false;
  37575. return this;
  37576. }
  37577. /**
  37578. * Connects to the audio source. This is used internally on
  37579. * initialisation and when setting / removing filters.
  37580. *
  37581. * @return {Audio} A reference to this instance.
  37582. */
  37583. connect() {
  37584. if ( this.filters.length > 0 ) {
  37585. this.source.connect( this.filters[ 0 ] );
  37586. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37587. this.filters[ i - 1 ].connect( this.filters[ i ] );
  37588. }
  37589. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  37590. } else {
  37591. this.source.connect( this.getOutput() );
  37592. }
  37593. this._connected = true;
  37594. return this;
  37595. }
  37596. /**
  37597. * Disconnects to the audio source. This is used internally on
  37598. * initialisation and when setting / removing filters.
  37599. *
  37600. * @return {Audio|undefined} A reference to this instance.
  37601. */
  37602. disconnect() {
  37603. if ( this._connected === false ) {
  37604. return;
  37605. }
  37606. if ( this.filters.length > 0 ) {
  37607. this.source.disconnect( this.filters[ 0 ] );
  37608. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37609. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  37610. }
  37611. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  37612. } else {
  37613. this.source.disconnect( this.getOutput() );
  37614. }
  37615. this._connected = false;
  37616. return this;
  37617. }
  37618. /**
  37619. * Returns the current set filters.
  37620. *
  37621. * @return {Array<AudioNode>} The list of filters.
  37622. */
  37623. getFilters() {
  37624. return this.filters;
  37625. }
  37626. /**
  37627. * Sets an array of filters and connects them with the audio source.
  37628. *
  37629. * @param {Array<AudioNode>} [value] - A list of filters.
  37630. * @return {Audio} A reference to this instance.
  37631. */
  37632. setFilters( value ) {
  37633. if ( ! value ) value = [];
  37634. if ( this._connected === true ) {
  37635. this.disconnect();
  37636. this.filters = value.slice();
  37637. this.connect();
  37638. } else {
  37639. this.filters = value.slice();
  37640. }
  37641. return this;
  37642. }
  37643. /**
  37644. * Defines the detuning of oscillation in cents.
  37645. *
  37646. * @param {number} value - The detuning of oscillation in cents.
  37647. * @return {Audio} A reference to this instance.
  37648. */
  37649. setDetune( value ) {
  37650. this.detune = value;
  37651. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37652. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37653. }
  37654. return this;
  37655. }
  37656. /**
  37657. * Returns the detuning of oscillation in cents.
  37658. *
  37659. * @return {number} The detuning of oscillation in cents.
  37660. */
  37661. getDetune() {
  37662. return this.detune;
  37663. }
  37664. /**
  37665. * Returns the first filter in the list of filters.
  37666. *
  37667. * @return {AudioNode|undefined} The first filter in the list of filters.
  37668. */
  37669. getFilter() {
  37670. return this.getFilters()[ 0 ];
  37671. }
  37672. /**
  37673. * Applies a single filter node to the audio.
  37674. *
  37675. * @param {AudioNode} [filter] - The filter to set.
  37676. * @return {Audio} A reference to this instance.
  37677. */
  37678. setFilter( filter ) {
  37679. return this.setFilters( filter ? [ filter ] : [] );
  37680. }
  37681. /**
  37682. * Sets the playback rate.
  37683. *
  37684. * Can only be used with compatible audio sources that allow playback control.
  37685. *
  37686. * @param {number} [value] - The playback rate to set.
  37687. * @return {Audio|undefined} A reference to this instance.
  37688. */
  37689. setPlaybackRate( value ) {
  37690. if ( this.hasPlaybackControl === false ) {
  37691. warn( 'Audio: this Audio has no playback control.' );
  37692. return;
  37693. }
  37694. this.playbackRate = value;
  37695. if ( this.isPlaying === true ) {
  37696. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37697. }
  37698. return this;
  37699. }
  37700. /**
  37701. * Returns the current playback rate.
  37702. * @return {number} The playback rate.
  37703. */
  37704. getPlaybackRate() {
  37705. return this.playbackRate;
  37706. }
  37707. /**
  37708. * Automatically called when playback finished.
  37709. */
  37710. onEnded() {
  37711. this.isPlaying = false;
  37712. this._progress = 0;
  37713. }
  37714. /**
  37715. * Returns the loop flag.
  37716. *
  37717. * Can only be used with compatible audio sources that allow playback control.
  37718. *
  37719. * @return {boolean} Whether the audio should loop or not.
  37720. */
  37721. getLoop() {
  37722. if ( this.hasPlaybackControl === false ) {
  37723. warn( 'Audio: this Audio has no playback control.' );
  37724. return false;
  37725. }
  37726. return this.loop;
  37727. }
  37728. /**
  37729. * Sets the loop flag.
  37730. *
  37731. * Can only be used with compatible audio sources that allow playback control.
  37732. *
  37733. * @param {boolean} value - Whether the audio should loop or not.
  37734. * @return {Audio|undefined} A reference to this instance.
  37735. */
  37736. setLoop( value ) {
  37737. if ( this.hasPlaybackControl === false ) {
  37738. warn( 'Audio: this Audio has no playback control.' );
  37739. return;
  37740. }
  37741. this.loop = value;
  37742. if ( this.isPlaying === true ) {
  37743. this.source.loop = this.loop;
  37744. }
  37745. return this;
  37746. }
  37747. /**
  37748. * Sets the loop start value which defines where in the audio buffer the replay should
  37749. * start, in seconds.
  37750. *
  37751. * @param {number} value - The loop start value.
  37752. * @return {Audio} A reference to this instance.
  37753. */
  37754. setLoopStart( value ) {
  37755. this.loopStart = value;
  37756. return this;
  37757. }
  37758. /**
  37759. * Sets the loop end value which defines where in the audio buffer the replay should
  37760. * stop, in seconds.
  37761. *
  37762. * @param {number} value - The loop end value.
  37763. * @return {Audio} A reference to this instance.
  37764. */
  37765. setLoopEnd( value ) {
  37766. this.loopEnd = value;
  37767. return this;
  37768. }
  37769. /**
  37770. * Returns the volume.
  37771. *
  37772. * @return {number} The volume.
  37773. */
  37774. getVolume() {
  37775. return this.gain.gain.value;
  37776. }
  37777. /**
  37778. * Sets the volume.
  37779. *
  37780. * @param {number} value - The volume to set.
  37781. * @return {Audio} A reference to this instance.
  37782. */
  37783. setVolume( value ) {
  37784. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37785. return this;
  37786. }
  37787. copy( source, recursive ) {
  37788. super.copy( source, recursive );
  37789. if ( source.sourceType !== 'buffer' ) {
  37790. warn( 'Audio: Audio source type cannot be copied.' );
  37791. return this;
  37792. }
  37793. this.autoplay = source.autoplay;
  37794. this.buffer = source.buffer;
  37795. this.detune = source.detune;
  37796. this.loop = source.loop;
  37797. this.loopStart = source.loopStart;
  37798. this.loopEnd = source.loopEnd;
  37799. this.offset = source.offset;
  37800. this.duration = source.duration;
  37801. this.playbackRate = source.playbackRate;
  37802. this.hasPlaybackControl = source.hasPlaybackControl;
  37803. this.sourceType = source.sourceType;
  37804. this.filters = source.filters.slice();
  37805. return this;
  37806. }
  37807. clone( recursive ) {
  37808. return new this.constructor( this.listener ).copy( this, recursive );
  37809. }
  37810. }
  37811. const _position = /*@__PURE__*/ new Vector3();
  37812. const _quaternion = /*@__PURE__*/ new Quaternion();
  37813. const _scale = /*@__PURE__*/ new Vector3();
  37814. const _orientation = /*@__PURE__*/ new Vector3();
  37815. /**
  37816. * Represents a positional audio object.
  37817. *
  37818. * ```js
  37819. * // create an AudioListener and add it to the camera
  37820. * const listener = new THREE.AudioListener();
  37821. * camera.add( listener );
  37822. *
  37823. * // create the PositionalAudio object (passing in the listener)
  37824. * const sound = new THREE.PositionalAudio( listener );
  37825. *
  37826. * // load a sound and set it as the PositionalAudio object's buffer
  37827. * const audioLoader = new THREE.AudioLoader();
  37828. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37829. * sound.setBuffer( buffer );
  37830. * sound.setRefDistance( 20 );
  37831. * sound.play();
  37832. * });
  37833. *
  37834. * // create an object for the sound to play from
  37835. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37836. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37837. * const mesh = new THREE.Mesh( sphere, material );
  37838. * scene.add( mesh );
  37839. *
  37840. * // finally add the sound to the mesh
  37841. * mesh.add( sound );
  37842. *
  37843. * @augments Audio
  37844. */
  37845. class PositionalAudio extends Audio {
  37846. /**
  37847. * Constructs a positional audio.
  37848. *
  37849. * @param {AudioListener} listener - The global audio listener.
  37850. */
  37851. constructor( listener ) {
  37852. super( listener );
  37853. /**
  37854. * The panner node represents the location, direction, and behavior of an audio
  37855. * source in 3D space.
  37856. *
  37857. * @type {PannerNode}
  37858. * @readonly
  37859. */
  37860. this.panner = this.context.createPanner();
  37861. this.panner.panningModel = 'HRTF';
  37862. this.panner.connect( this.gain );
  37863. }
  37864. connect() {
  37865. super.connect();
  37866. this.panner.connect( this.gain );
  37867. return this;
  37868. }
  37869. disconnect() {
  37870. super.disconnect();
  37871. this.panner.disconnect( this.gain );
  37872. return this;
  37873. }
  37874. getOutput() {
  37875. return this.panner;
  37876. }
  37877. /**
  37878. * Returns the current reference distance.
  37879. *
  37880. * @return {number} The reference distance.
  37881. */
  37882. getRefDistance() {
  37883. return this.panner.refDistance;
  37884. }
  37885. /**
  37886. * Defines the reference distance for reducing volume as the audio source moves
  37887. * further from the listener – i.e. the distance at which the volume reduction
  37888. * starts taking effect.
  37889. *
  37890. * @param {number} value - The reference distance to set.
  37891. * @return {PositionalAudio} A reference to this instance.
  37892. */
  37893. setRefDistance( value ) {
  37894. this.panner.refDistance = value;
  37895. return this;
  37896. }
  37897. /**
  37898. * Returns the current rolloff factor.
  37899. *
  37900. * @return {number} The rolloff factor.
  37901. */
  37902. getRolloffFactor() {
  37903. return this.panner.rolloffFactor;
  37904. }
  37905. /**
  37906. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37907. *
  37908. * @param {number} value - The rolloff factor.
  37909. * @return {PositionalAudio} A reference to this instance.
  37910. */
  37911. setRolloffFactor( value ) {
  37912. this.panner.rolloffFactor = value;
  37913. return this;
  37914. }
  37915. /**
  37916. * Returns the current distance model.
  37917. *
  37918. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37919. */
  37920. getDistanceModel() {
  37921. return this.panner.distanceModel;
  37922. }
  37923. /**
  37924. * Defines which algorithm to use to reduce the volume of the audio source
  37925. * as it moves away from the listener.
  37926. *
  37927. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37928. * for more details.
  37929. *
  37930. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37931. * @return {PositionalAudio} A reference to this instance.
  37932. */
  37933. setDistanceModel( value ) {
  37934. this.panner.distanceModel = value;
  37935. return this;
  37936. }
  37937. /**
  37938. * Returns the current max distance.
  37939. *
  37940. * @return {number} The max distance.
  37941. */
  37942. getMaxDistance() {
  37943. return this.panner.maxDistance;
  37944. }
  37945. /**
  37946. * Defines the maximum distance between the audio source and the listener,
  37947. * after which the volume is not reduced any further.
  37948. *
  37949. * This value is used only by the `linear` distance model.
  37950. *
  37951. * @param {number} value - The max distance.
  37952. * @return {PositionalAudio} A reference to this instance.
  37953. */
  37954. setMaxDistance( value ) {
  37955. this.panner.maxDistance = value;
  37956. return this;
  37957. }
  37958. /**
  37959. * Sets the directional cone in which the audio can be listened.
  37960. *
  37961. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37962. * @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.
  37963. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37964. * @return {PositionalAudio} A reference to this instance.
  37965. */
  37966. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37967. this.panner.coneInnerAngle = coneInnerAngle;
  37968. this.panner.coneOuterAngle = coneOuterAngle;
  37969. this.panner.coneOuterGain = coneOuterGain;
  37970. return this;
  37971. }
  37972. updateMatrixWorld( force ) {
  37973. super.updateMatrixWorld( force );
  37974. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37975. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37976. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37977. const panner = this.panner;
  37978. if ( panner.positionX ) {
  37979. // code path for Chrome and Firefox (see #14393)
  37980. const endTime = this.context.currentTime + this.listener.timeDelta;
  37981. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37982. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37983. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37984. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37985. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37986. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37987. } else {
  37988. panner.setPosition( _position.x, _position.y, _position.z );
  37989. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37990. }
  37991. }
  37992. }
  37993. /**
  37994. * This class can be used to analyse audio data.
  37995. *
  37996. * ```js
  37997. * // create an AudioListener and add it to the camera
  37998. * const listener = new THREE.AudioListener();
  37999. * camera.add( listener );
  38000. *
  38001. * // create an Audio source
  38002. * const sound = new THREE.Audio( listener );
  38003. *
  38004. * // load a sound and set it as the Audio object's buffer
  38005. * const audioLoader = new THREE.AudioLoader();
  38006. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  38007. * sound.setBuffer( buffer );
  38008. * sound.setLoop(true);
  38009. * sound.setVolume(0.5);
  38010. * sound.play();
  38011. * });
  38012. *
  38013. * // create an AudioAnalyser, passing in the sound and desired fftSize
  38014. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  38015. *
  38016. * // get the average frequency of the sound
  38017. * const data = analyser.getAverageFrequency();
  38018. * ```
  38019. */
  38020. class AudioAnalyser {
  38021. /**
  38022. * Constructs a new audio analyzer.
  38023. *
  38024. * @param {Audio} audio - The audio to analyze.
  38025. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  38026. */
  38027. constructor( audio, fftSize = 2048 ) {
  38028. /**
  38029. * The global audio listener.
  38030. *
  38031. * @type {AnalyserNode}
  38032. */
  38033. this.analyser = audio.context.createAnalyser();
  38034. this.analyser.fftSize = fftSize;
  38035. /**
  38036. * Holds the analyzed data.
  38037. *
  38038. * @type {Uint8Array}
  38039. */
  38040. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  38041. audio.getOutput().connect( this.analyser );
  38042. }
  38043. /**
  38044. * Returns an array with frequency data of the audio.
  38045. *
  38046. * Each item in the array represents the decibel value for a specific frequency.
  38047. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  38048. * For example, for 48000 sample rate, the last item of the array will represent
  38049. * the decibel value for 24000 Hz.
  38050. *
  38051. * @return {Uint8Array} The frequency data.
  38052. */
  38053. getFrequencyData() {
  38054. this.analyser.getByteFrequencyData( this.data );
  38055. return this.data;
  38056. }
  38057. /**
  38058. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  38059. *
  38060. * @return {number} The average frequency.
  38061. */
  38062. getAverageFrequency() {
  38063. let value = 0;
  38064. const data = this.getFrequencyData();
  38065. for ( let i = 0; i < data.length; i ++ ) {
  38066. value += data[ i ];
  38067. }
  38068. return value / data.length;
  38069. }
  38070. }
  38071. /**
  38072. * Buffered scene graph property that allows weighted accumulation; used internally.
  38073. */
  38074. class PropertyMixer {
  38075. /**
  38076. * Constructs a new property mixer.
  38077. *
  38078. * @param {PropertyBinding} binding - The property binding.
  38079. * @param {string} typeName - The keyframe track type name.
  38080. * @param {number} valueSize - The keyframe track value size.
  38081. */
  38082. constructor( binding, typeName, valueSize ) {
  38083. /**
  38084. * The property binding.
  38085. *
  38086. * @type {PropertyBinding}
  38087. */
  38088. this.binding = binding;
  38089. /**
  38090. * The keyframe track value size.
  38091. *
  38092. * @type {number}
  38093. */
  38094. this.valueSize = valueSize;
  38095. let mixFunction,
  38096. mixFunctionAdditive,
  38097. setIdentity;
  38098. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  38099. //
  38100. // interpolators can use .buffer as their .result
  38101. // the data then goes to 'incoming'
  38102. //
  38103. // 'accu0' and 'accu1' are used frame-interleaved for
  38104. // the cumulative result and are compared to detect
  38105. // changes
  38106. //
  38107. // 'orig' stores the original state of the property
  38108. //
  38109. // 'add' is used for additive cumulative results
  38110. //
  38111. // 'work' is optional and is only present for quaternion types. It is used
  38112. // to store intermediate quaternion multiplication results
  38113. switch ( typeName ) {
  38114. case 'quaternion':
  38115. mixFunction = this._slerp;
  38116. mixFunctionAdditive = this._slerpAdditive;
  38117. setIdentity = this._setAdditiveIdentityQuaternion;
  38118. this.buffer = new Float64Array( valueSize * 6 );
  38119. this._workIndex = 5;
  38120. break;
  38121. case 'string':
  38122. case 'bool':
  38123. mixFunction = this._select;
  38124. // Use the regular mix function and for additive on these types,
  38125. // additive is not relevant for non-numeric types
  38126. mixFunctionAdditive = this._select;
  38127. setIdentity = this._setAdditiveIdentityOther;
  38128. this.buffer = new Array( valueSize * 5 );
  38129. break;
  38130. default:
  38131. mixFunction = this._lerp;
  38132. mixFunctionAdditive = this._lerpAdditive;
  38133. setIdentity = this._setAdditiveIdentityNumeric;
  38134. this.buffer = new Float64Array( valueSize * 5 );
  38135. }
  38136. this._mixBufferRegion = mixFunction;
  38137. this._mixBufferRegionAdditive = mixFunctionAdditive;
  38138. this._setIdentity = setIdentity;
  38139. this._origIndex = 3;
  38140. this._addIndex = 4;
  38141. /**
  38142. * Accumulated weight of the property binding.
  38143. *
  38144. * @type {number}
  38145. * @default 0
  38146. */
  38147. this.cumulativeWeight = 0;
  38148. /**
  38149. * Accumulated additive weight of the property binding.
  38150. *
  38151. * @type {number}
  38152. * @default 0
  38153. */
  38154. this.cumulativeWeightAdditive = 0;
  38155. /**
  38156. * Number of active keyframe tracks currently using this property binding.
  38157. *
  38158. * @type {number}
  38159. * @default 0
  38160. */
  38161. this.useCount = 0;
  38162. /**
  38163. * Number of keyframe tracks referencing this property binding.
  38164. *
  38165. * @type {number}
  38166. * @default 0
  38167. */
  38168. this.referenceCount = 0;
  38169. }
  38170. /**
  38171. * Accumulates data in the `incoming` region into `accu<i>`.
  38172. *
  38173. * @param {number} accuIndex - The accumulation index.
  38174. * @param {number} weight - The weight.
  38175. */
  38176. accumulate( accuIndex, weight ) {
  38177. // note: happily accumulating nothing when weight = 0, the caller knows
  38178. // the weight and shouldn't have made the call in the first place
  38179. const buffer = this.buffer,
  38180. stride = this.valueSize,
  38181. offset = accuIndex * stride + stride;
  38182. let currentWeight = this.cumulativeWeight;
  38183. if ( currentWeight === 0 ) {
  38184. // accuN := incoming * weight
  38185. for ( let i = 0; i !== stride; ++ i ) {
  38186. buffer[ offset + i ] = buffer[ i ];
  38187. }
  38188. currentWeight = weight;
  38189. } else {
  38190. // accuN := accuN + incoming * weight
  38191. currentWeight += weight;
  38192. const mix = weight / currentWeight;
  38193. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  38194. }
  38195. this.cumulativeWeight = currentWeight;
  38196. }
  38197. /**
  38198. * Accumulates data in the `incoming` region into `add`.
  38199. *
  38200. * @param {number} weight - The weight.
  38201. */
  38202. accumulateAdditive( weight ) {
  38203. const buffer = this.buffer,
  38204. stride = this.valueSize,
  38205. offset = stride * this._addIndex;
  38206. if ( this.cumulativeWeightAdditive === 0 ) {
  38207. // add = identity
  38208. this._setIdentity();
  38209. }
  38210. // add := add + incoming * weight
  38211. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  38212. this.cumulativeWeightAdditive += weight;
  38213. }
  38214. /**
  38215. * Applies the state of `accu<i>` to the binding when accus differ.
  38216. *
  38217. * @param {number} accuIndex - The accumulation index.
  38218. */
  38219. apply( accuIndex ) {
  38220. const stride = this.valueSize,
  38221. buffer = this.buffer,
  38222. offset = accuIndex * stride + stride,
  38223. weight = this.cumulativeWeight,
  38224. weightAdditive = this.cumulativeWeightAdditive,
  38225. binding = this.binding;
  38226. this.cumulativeWeight = 0;
  38227. this.cumulativeWeightAdditive = 0;
  38228. if ( weight < 1 ) {
  38229. // accuN := accuN + original * ( 1 - cumulativeWeight )
  38230. const originalValueOffset = stride * this._origIndex;
  38231. this._mixBufferRegion(
  38232. buffer, offset, originalValueOffset, 1 - weight, stride );
  38233. }
  38234. if ( weightAdditive > 0 ) {
  38235. // accuN := accuN + additive accuN
  38236. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  38237. }
  38238. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  38239. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  38240. // value has changed -> update scene graph
  38241. binding.setValue( buffer, offset );
  38242. break;
  38243. }
  38244. }
  38245. }
  38246. /**
  38247. * Remembers the state of the bound property and copy it to both accus.
  38248. */
  38249. saveOriginalState() {
  38250. const binding = this.binding;
  38251. const buffer = this.buffer,
  38252. stride = this.valueSize,
  38253. originalValueOffset = stride * this._origIndex;
  38254. binding.getValue( buffer, originalValueOffset );
  38255. // accu[0..1] := orig -- initially detect changes against the original
  38256. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  38257. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  38258. }
  38259. // Add to identity for additive
  38260. this._setIdentity();
  38261. this.cumulativeWeight = 0;
  38262. this.cumulativeWeightAdditive = 0;
  38263. }
  38264. /**
  38265. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  38266. */
  38267. restoreOriginalState() {
  38268. const originalValueOffset = this.valueSize * 3;
  38269. this.binding.setValue( this.buffer, originalValueOffset );
  38270. }
  38271. // internals
  38272. _setAdditiveIdentityNumeric() {
  38273. const startIndex = this._addIndex * this.valueSize;
  38274. const endIndex = startIndex + this.valueSize;
  38275. for ( let i = startIndex; i < endIndex; i ++ ) {
  38276. this.buffer[ i ] = 0;
  38277. }
  38278. }
  38279. _setAdditiveIdentityQuaternion() {
  38280. this._setAdditiveIdentityNumeric();
  38281. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  38282. }
  38283. _setAdditiveIdentityOther() {
  38284. const startIndex = this._origIndex * this.valueSize;
  38285. const targetIndex = this._addIndex * this.valueSize;
  38286. for ( let i = 0; i < this.valueSize; i ++ ) {
  38287. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  38288. }
  38289. }
  38290. // mix functions
  38291. _select( buffer, dstOffset, srcOffset, t, stride ) {
  38292. if ( t >= 0.5 ) {
  38293. for ( let i = 0; i !== stride; ++ i ) {
  38294. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  38295. }
  38296. }
  38297. }
  38298. _slerp( buffer, dstOffset, srcOffset, t ) {
  38299. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  38300. }
  38301. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  38302. const workOffset = this._workIndex * stride;
  38303. // Store result in intermediate buffer offset
  38304. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  38305. // Slerp to the intermediate result
  38306. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  38307. }
  38308. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  38309. const s = 1 - t;
  38310. for ( let i = 0; i !== stride; ++ i ) {
  38311. const j = dstOffset + i;
  38312. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  38313. }
  38314. }
  38315. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  38316. for ( let i = 0; i !== stride; ++ i ) {
  38317. const j = dstOffset + i;
  38318. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  38319. }
  38320. }
  38321. }
  38322. // Characters [].:/ are reserved for track binding syntax.
  38323. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  38324. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  38325. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  38326. // only latin characters, and the unicode \p{L} is not yet supported. So
  38327. // instead, we exclude reserved characters and match everything else.
  38328. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  38329. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  38330. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  38331. // be matched to parse the rest of the track name.
  38332. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  38333. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  38334. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  38335. // Object on target node, and accessor. May not contain reserved
  38336. // characters. Accessor may contain any character except closing bracket.
  38337. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  38338. // Property and accessor. May not contain reserved characters. Accessor may
  38339. // contain any non-bracket characters.
  38340. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  38341. const _trackRe = new RegExp( ''
  38342. + '^'
  38343. + _directoryRe
  38344. + _nodeRe
  38345. + _objectRe
  38346. + _propertyRe
  38347. + '$'
  38348. );
  38349. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  38350. class Composite {
  38351. constructor( targetGroup, path, optionalParsedPath ) {
  38352. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  38353. this._targetGroup = targetGroup;
  38354. this._bindings = targetGroup.subscribe_( path, parsedPath );
  38355. }
  38356. getValue( array, offset ) {
  38357. this.bind(); // bind all binding
  38358. const firstValidIndex = this._targetGroup.nCachedObjects_,
  38359. binding = this._bindings[ firstValidIndex ];
  38360. // and only call .getValue on the first
  38361. if ( binding !== undefined ) binding.getValue( array, offset );
  38362. }
  38363. setValue( array, offset ) {
  38364. const bindings = this._bindings;
  38365. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38366. bindings[ i ].setValue( array, offset );
  38367. }
  38368. }
  38369. bind() {
  38370. const bindings = this._bindings;
  38371. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38372. bindings[ i ].bind();
  38373. }
  38374. }
  38375. unbind() {
  38376. const bindings = this._bindings;
  38377. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38378. bindings[ i ].unbind();
  38379. }
  38380. }
  38381. }
  38382. // Note: This class uses a State pattern on a per-method basis:
  38383. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  38384. // prototype version of these methods with one that represents
  38385. // the bound state. When the property is not found, the methods
  38386. // become no-ops.
  38387. /**
  38388. * This holds a reference to a real property in the scene graph; used internally.
  38389. */
  38390. class PropertyBinding {
  38391. /**
  38392. * Constructs a new property binding.
  38393. *
  38394. * @param {Object} rootNode - The root node.
  38395. * @param {string} path - The path.
  38396. * @param {?Object} [parsedPath] - The parsed path.
  38397. */
  38398. constructor( rootNode, path, parsedPath ) {
  38399. /**
  38400. * The object path to the animated property.
  38401. *
  38402. * @type {string}
  38403. */
  38404. this.path = path;
  38405. /**
  38406. * An object holding information about the path.
  38407. *
  38408. * @type {Object}
  38409. */
  38410. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  38411. /**
  38412. * The object owns the animated property.
  38413. *
  38414. * @type {?Object}
  38415. */
  38416. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  38417. /**
  38418. * The root node.
  38419. *
  38420. * @type {Object3D|Skeleton}
  38421. */
  38422. this.rootNode = rootNode;
  38423. // initial state of these methods that calls 'bind'
  38424. this.getValue = this._getValue_unbound;
  38425. this.setValue = this._setValue_unbound;
  38426. }
  38427. /**
  38428. * Factory method for creating a property binding from the given parameters.
  38429. *
  38430. * @static
  38431. * @param {Object} root - The root node.
  38432. * @param {string} path - The path.
  38433. * @param {?Object} [parsedPath] - The parsed path.
  38434. * @return {PropertyBinding|Composite} The created property binding or composite.
  38435. */
  38436. static create( root, path, parsedPath ) {
  38437. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  38438. return new PropertyBinding( root, path, parsedPath );
  38439. } else {
  38440. return new PropertyBinding.Composite( root, path, parsedPath );
  38441. }
  38442. }
  38443. /**
  38444. * Replaces spaces with underscores and removes unsupported characters from
  38445. * node names, to ensure compatibility with parseTrackName().
  38446. *
  38447. * @param {string} name - Node name to be sanitized.
  38448. * @return {string} The sanitized node name.
  38449. */
  38450. static sanitizeNodeName( name ) {
  38451. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  38452. }
  38453. /**
  38454. * Parses the given track name (an object path to an animated property) and
  38455. * returns an object with information about the path. Matches strings in the following forms:
  38456. *
  38457. * - nodeName.property
  38458. * - nodeName.property[accessor]
  38459. * - nodeName.material.property[accessor]
  38460. * - uuid.property[accessor]
  38461. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  38462. * - parentName/nodeName.property
  38463. * - parentName/parentName/nodeName.property[index]
  38464. * - .bone[Armature.DEF_cog].position
  38465. * - scene:helium_balloon_model:helium_balloon_model.position
  38466. *
  38467. * @static
  38468. * @param {string} trackName - The track name to parse.
  38469. * @return {Object} The parsed track name as an object.
  38470. */
  38471. static parseTrackName( trackName ) {
  38472. const matches = _trackRe.exec( trackName );
  38473. if ( matches === null ) {
  38474. throw new Error( 'THREE.PropertyBinding: Cannot parse trackName: ' + trackName );
  38475. }
  38476. const results = {
  38477. // directoryName: matches[ 1 ], // (tschw) currently unused
  38478. nodeName: matches[ 2 ],
  38479. objectName: matches[ 3 ],
  38480. objectIndex: matches[ 4 ],
  38481. propertyName: matches[ 5 ], // required
  38482. propertyIndex: matches[ 6 ]
  38483. };
  38484. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  38485. if ( lastDot !== undefined && lastDot !== -1 ) {
  38486. const objectName = results.nodeName.substring( lastDot + 1 );
  38487. // Object names must be checked against an allowlist. Otherwise, there
  38488. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  38489. // 'bar' could be the objectName, or part of a nodeName (which can
  38490. // include '.' characters).
  38491. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  38492. results.nodeName = results.nodeName.substring( 0, lastDot );
  38493. results.objectName = objectName;
  38494. }
  38495. }
  38496. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  38497. throw new Error( 'THREE.PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  38498. }
  38499. return results;
  38500. }
  38501. /**
  38502. * Searches for a node in the hierarchy of the given root object by the given
  38503. * node name.
  38504. *
  38505. * @static
  38506. * @param {Object} root - The root object.
  38507. * @param {string|number} nodeName - The name of the node.
  38508. * @return {?Object} The found node. Returns `null` if no object was found.
  38509. */
  38510. static findNode( root, nodeName ) {
  38511. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  38512. return root;
  38513. }
  38514. // search into skeleton bones.
  38515. if ( root.skeleton ) {
  38516. const bone = root.skeleton.getBoneByName( nodeName );
  38517. if ( bone !== undefined ) {
  38518. return bone;
  38519. }
  38520. }
  38521. // search into node subtree.
  38522. if ( root.children ) {
  38523. const searchNodeSubtree = function ( children ) {
  38524. for ( let i = 0; i < children.length; i ++ ) {
  38525. const childNode = children[ i ];
  38526. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  38527. return childNode;
  38528. }
  38529. const result = searchNodeSubtree( childNode.children );
  38530. if ( result ) return result;
  38531. }
  38532. return null;
  38533. };
  38534. const subTreeNode = searchNodeSubtree( root.children );
  38535. if ( subTreeNode ) {
  38536. return subTreeNode;
  38537. }
  38538. }
  38539. return null;
  38540. }
  38541. // these are used to "bind" a nonexistent property
  38542. _getValue_unavailable() {}
  38543. _setValue_unavailable() {}
  38544. // Getters
  38545. _getValue_direct( buffer, offset ) {
  38546. buffer[ offset ] = this.targetObject[ this.propertyName ];
  38547. }
  38548. _getValue_array( buffer, offset ) {
  38549. const source = this.resolvedProperty;
  38550. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  38551. buffer[ offset ++ ] = source[ i ];
  38552. }
  38553. }
  38554. _getValue_arrayElement( buffer, offset ) {
  38555. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  38556. }
  38557. _getValue_toArray( buffer, offset ) {
  38558. this.resolvedProperty.toArray( buffer, offset );
  38559. }
  38560. // Direct
  38561. _setValue_direct( buffer, offset ) {
  38562. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38563. }
  38564. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  38565. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38566. this.targetObject.needsUpdate = true;
  38567. }
  38568. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38569. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38570. this.targetObject.matrixWorldNeedsUpdate = true;
  38571. }
  38572. // EntireArray
  38573. _setValue_array( buffer, offset ) {
  38574. const dest = this.resolvedProperty;
  38575. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38576. dest[ i ] = buffer[ offset ++ ];
  38577. }
  38578. }
  38579. _setValue_array_setNeedsUpdate( buffer, offset ) {
  38580. const dest = this.resolvedProperty;
  38581. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38582. dest[ i ] = buffer[ offset ++ ];
  38583. }
  38584. this.targetObject.needsUpdate = true;
  38585. }
  38586. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38587. const dest = this.resolvedProperty;
  38588. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38589. dest[ i ] = buffer[ offset ++ ];
  38590. }
  38591. this.targetObject.matrixWorldNeedsUpdate = true;
  38592. }
  38593. // ArrayElement
  38594. _setValue_arrayElement( buffer, offset ) {
  38595. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38596. }
  38597. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  38598. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38599. this.targetObject.needsUpdate = true;
  38600. }
  38601. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38602. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38603. this.targetObject.matrixWorldNeedsUpdate = true;
  38604. }
  38605. // HasToFromArray
  38606. _setValue_fromArray( buffer, offset ) {
  38607. this.resolvedProperty.fromArray( buffer, offset );
  38608. }
  38609. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  38610. this.resolvedProperty.fromArray( buffer, offset );
  38611. this.targetObject.needsUpdate = true;
  38612. }
  38613. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38614. this.resolvedProperty.fromArray( buffer, offset );
  38615. this.targetObject.matrixWorldNeedsUpdate = true;
  38616. }
  38617. _getValue_unbound( targetArray, offset ) {
  38618. this.bind();
  38619. this.getValue( targetArray, offset );
  38620. }
  38621. _setValue_unbound( sourceArray, offset ) {
  38622. this.bind();
  38623. this.setValue( sourceArray, offset );
  38624. }
  38625. /**
  38626. * Creates a getter / setter pair for the property tracked by this binding.
  38627. */
  38628. bind() {
  38629. let targetObject = this.node;
  38630. const parsedPath = this.parsedPath;
  38631. const objectName = parsedPath.objectName;
  38632. const propertyName = parsedPath.propertyName;
  38633. let propertyIndex = parsedPath.propertyIndex;
  38634. if ( ! targetObject ) {
  38635. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38636. this.node = targetObject;
  38637. }
  38638. // set fail state so we can just 'return' on error
  38639. this.getValue = this._getValue_unavailable;
  38640. this.setValue = this._setValue_unavailable;
  38641. // ensure there is a value node
  38642. if ( ! targetObject ) {
  38643. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38644. return;
  38645. }
  38646. if ( objectName ) {
  38647. let objectIndex = parsedPath.objectIndex;
  38648. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38649. switch ( objectName ) {
  38650. case 'materials':
  38651. if ( ! targetObject.material ) {
  38652. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38653. return;
  38654. }
  38655. if ( ! targetObject.material.materials ) {
  38656. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38657. return;
  38658. }
  38659. targetObject = targetObject.material.materials;
  38660. break;
  38661. case 'bones':
  38662. if ( ! targetObject.skeleton ) {
  38663. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38664. return;
  38665. }
  38666. // potential future optimization: skip this if propertyIndex is already an integer
  38667. // and convert the integer string to a true integer.
  38668. targetObject = targetObject.skeleton.bones;
  38669. // support resolving morphTarget names into indices.
  38670. for ( let i = 0; i < targetObject.length; i ++ ) {
  38671. if ( targetObject[ i ].name === objectIndex ) {
  38672. objectIndex = i;
  38673. break;
  38674. }
  38675. }
  38676. break;
  38677. case 'map':
  38678. if ( 'map' in targetObject ) {
  38679. targetObject = targetObject.map;
  38680. break;
  38681. }
  38682. if ( ! targetObject.material ) {
  38683. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38684. return;
  38685. }
  38686. if ( ! targetObject.material.map ) {
  38687. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38688. return;
  38689. }
  38690. targetObject = targetObject.material.map;
  38691. break;
  38692. default:
  38693. if ( targetObject[ objectName ] === undefined ) {
  38694. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38695. return;
  38696. }
  38697. targetObject = targetObject[ objectName ];
  38698. }
  38699. if ( objectIndex !== undefined ) {
  38700. if ( targetObject[ objectIndex ] === undefined ) {
  38701. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38702. return;
  38703. }
  38704. targetObject = targetObject[ objectIndex ];
  38705. }
  38706. }
  38707. // resolve property
  38708. const nodeProperty = targetObject[ propertyName ];
  38709. if ( nodeProperty === undefined ) {
  38710. const nodeName = parsedPath.nodeName;
  38711. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38712. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38713. return;
  38714. }
  38715. // determine versioning scheme
  38716. let versioning = this.Versioning.None;
  38717. this.targetObject = targetObject;
  38718. if ( targetObject.isMaterial === true ) {
  38719. versioning = this.Versioning.NeedsUpdate;
  38720. } else if ( targetObject.isObject3D === true ) {
  38721. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38722. }
  38723. // determine how the property gets bound
  38724. let bindingType = this.BindingType.Direct;
  38725. if ( propertyIndex !== undefined ) {
  38726. // access a sub element of the property array (only primitives are supported right now)
  38727. if ( propertyName === 'morphTargetInfluences' ) {
  38728. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38729. // support resolving morphTarget names into indices.
  38730. if ( ! targetObject.geometry ) {
  38731. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38732. return;
  38733. }
  38734. if ( ! targetObject.geometry.morphAttributes ) {
  38735. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38736. return;
  38737. }
  38738. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38739. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38740. }
  38741. }
  38742. bindingType = this.BindingType.ArrayElement;
  38743. this.resolvedProperty = nodeProperty;
  38744. this.propertyIndex = propertyIndex;
  38745. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38746. // must use copy for Object3D.Euler/Quaternion
  38747. bindingType = this.BindingType.HasFromToArray;
  38748. this.resolvedProperty = nodeProperty;
  38749. } else if ( Array.isArray( nodeProperty ) ) {
  38750. bindingType = this.BindingType.EntireArray;
  38751. this.resolvedProperty = nodeProperty;
  38752. } else {
  38753. this.propertyName = propertyName;
  38754. }
  38755. // select getter / setter
  38756. this.getValue = this.GetterByBindingType[ bindingType ];
  38757. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38758. }
  38759. /**
  38760. * Unbinds the property.
  38761. */
  38762. unbind() {
  38763. this.node = null;
  38764. // back to the prototype version of getValue / setValue
  38765. // note: avoiding to mutate the shape of 'this' via 'delete'
  38766. this.getValue = this._getValue_unbound;
  38767. this.setValue = this._setValue_unbound;
  38768. }
  38769. }
  38770. PropertyBinding.Composite = Composite;
  38771. PropertyBinding.prototype.BindingType = {
  38772. Direct: 0,
  38773. EntireArray: 1,
  38774. ArrayElement: 2,
  38775. HasFromToArray: 3
  38776. };
  38777. PropertyBinding.prototype.Versioning = {
  38778. None: 0,
  38779. NeedsUpdate: 1,
  38780. MatrixWorldNeedsUpdate: 2
  38781. };
  38782. PropertyBinding.prototype.GetterByBindingType = [
  38783. PropertyBinding.prototype._getValue_direct,
  38784. PropertyBinding.prototype._getValue_array,
  38785. PropertyBinding.prototype._getValue_arrayElement,
  38786. PropertyBinding.prototype._getValue_toArray,
  38787. ];
  38788. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38789. [
  38790. // Direct
  38791. PropertyBinding.prototype._setValue_direct,
  38792. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38793. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38794. ], [
  38795. // EntireArray
  38796. PropertyBinding.prototype._setValue_array,
  38797. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38798. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38799. ], [
  38800. // ArrayElement
  38801. PropertyBinding.prototype._setValue_arrayElement,
  38802. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38803. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38804. ], [
  38805. // HasToFromArray
  38806. PropertyBinding.prototype._setValue_fromArray,
  38807. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38808. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38809. ]
  38810. ];
  38811. /**
  38812. * A group of objects that receives a shared animation state.
  38813. *
  38814. * Usage:
  38815. *
  38816. * - Add objects you would otherwise pass as 'root' to the
  38817. * constructor or the .clipAction method of AnimationMixer.
  38818. * - Instead pass this object as 'root'.
  38819. * - You can also add and remove objects later when the mixer is running.
  38820. *
  38821. * Note:
  38822. *
  38823. * - Objects of this class appear as one object to the mixer,
  38824. * so cache control of the individual objects must be done on the group.
  38825. *
  38826. * Limitation:
  38827. *
  38828. * - The animated properties must be compatible among the all objects in the group.
  38829. * - A single property can either be controlled through a target group or directly, but not both.
  38830. */
  38831. class AnimationObjectGroup {
  38832. /**
  38833. * Constructs a new animation group.
  38834. *
  38835. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38836. */
  38837. constructor() {
  38838. /**
  38839. * This flag can be used for type testing.
  38840. *
  38841. * @type {boolean}
  38842. * @readonly
  38843. * @default true
  38844. */
  38845. this.isAnimationObjectGroup = true;
  38846. /**
  38847. * The UUID of the 3D object.
  38848. *
  38849. * @type {string}
  38850. * @readonly
  38851. */
  38852. this.uuid = generateUUID();
  38853. // cached objects followed by the active ones
  38854. this._objects = Array.prototype.slice.call( arguments );
  38855. this.nCachedObjects_ = 0; // threshold
  38856. // note: read by PropertyBinding.Composite
  38857. const indices = {};
  38858. this._indicesByUUID = indices; // for bookkeeping
  38859. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38860. indices[ arguments[ i ].uuid ] = i;
  38861. }
  38862. this._paths = []; // inside: string
  38863. this._parsedPaths = []; // inside: { we don't care, here }
  38864. this._bindings = []; // inside: Array< PropertyBinding >
  38865. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38866. const scope = this;
  38867. this.stats = {
  38868. objects: {
  38869. get total() {
  38870. return scope._objects.length;
  38871. },
  38872. get inUse() {
  38873. return this.total - scope.nCachedObjects_;
  38874. }
  38875. },
  38876. get bindingsPerObject() {
  38877. return scope._bindings.length;
  38878. }
  38879. };
  38880. }
  38881. /**
  38882. * Adds an arbitrary number of objects to this animation group.
  38883. *
  38884. * @param {...Object3D} arguments - The 3D objects to add.
  38885. */
  38886. add() {
  38887. const objects = this._objects,
  38888. indicesByUUID = this._indicesByUUID,
  38889. paths = this._paths,
  38890. parsedPaths = this._parsedPaths,
  38891. bindings = this._bindings,
  38892. nBindings = bindings.length;
  38893. let knownObject = undefined,
  38894. nObjects = objects.length,
  38895. nCachedObjects = this.nCachedObjects_;
  38896. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38897. const object = arguments[ i ],
  38898. uuid = object.uuid;
  38899. let index = indicesByUUID[ uuid ];
  38900. if ( index === undefined ) {
  38901. // unknown object -> add it to the ACTIVE region
  38902. index = nObjects ++;
  38903. indicesByUUID[ uuid ] = index;
  38904. objects.push( object );
  38905. // accounting is done, now do the same for all bindings
  38906. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38907. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38908. }
  38909. } else if ( index < nCachedObjects ) {
  38910. knownObject = objects[ index ];
  38911. // move existing object to the ACTIVE region
  38912. const firstActiveIndex = -- nCachedObjects,
  38913. lastCachedObject = objects[ firstActiveIndex ];
  38914. indicesByUUID[ lastCachedObject.uuid ] = index;
  38915. objects[ index ] = lastCachedObject;
  38916. indicesByUUID[ uuid ] = firstActiveIndex;
  38917. objects[ firstActiveIndex ] = object;
  38918. // accounting is done, now do the same for all bindings
  38919. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38920. const bindingsForPath = bindings[ j ],
  38921. lastCached = bindingsForPath[ firstActiveIndex ];
  38922. let binding = bindingsForPath[ index ];
  38923. bindingsForPath[ index ] = lastCached;
  38924. if ( binding === undefined ) {
  38925. // since we do not bother to create new bindings
  38926. // for objects that are cached, the binding may
  38927. // or may not exist
  38928. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38929. }
  38930. bindingsForPath[ firstActiveIndex ] = binding;
  38931. }
  38932. } else if ( objects[ index ] !== knownObject ) {
  38933. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38934. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38935. } // else the object is already where we want it to be
  38936. } // for arguments
  38937. this.nCachedObjects_ = nCachedObjects;
  38938. }
  38939. /**
  38940. * Removes an arbitrary number of objects to this animation group
  38941. *
  38942. * @param {...Object3D} arguments - The 3D objects to remove.
  38943. */
  38944. remove() {
  38945. const objects = this._objects,
  38946. indicesByUUID = this._indicesByUUID,
  38947. bindings = this._bindings,
  38948. nBindings = bindings.length;
  38949. let nCachedObjects = this.nCachedObjects_;
  38950. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38951. const object = arguments[ i ],
  38952. uuid = object.uuid,
  38953. index = indicesByUUID[ uuid ];
  38954. if ( index !== undefined && index >= nCachedObjects ) {
  38955. // move existing object into the CACHED region
  38956. const lastCachedIndex = nCachedObjects ++,
  38957. firstActiveObject = objects[ lastCachedIndex ];
  38958. indicesByUUID[ firstActiveObject.uuid ] = index;
  38959. objects[ index ] = firstActiveObject;
  38960. indicesByUUID[ uuid ] = lastCachedIndex;
  38961. objects[ lastCachedIndex ] = object;
  38962. // accounting is done, now do the same for all bindings
  38963. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38964. const bindingsForPath = bindings[ j ],
  38965. firstActive = bindingsForPath[ lastCachedIndex ],
  38966. binding = bindingsForPath[ index ];
  38967. bindingsForPath[ index ] = firstActive;
  38968. bindingsForPath[ lastCachedIndex ] = binding;
  38969. }
  38970. }
  38971. } // for arguments
  38972. this.nCachedObjects_ = nCachedObjects;
  38973. }
  38974. /**
  38975. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38976. *
  38977. * @param {...Object3D} arguments - The 3D objects to uncache.
  38978. */
  38979. uncache() {
  38980. const objects = this._objects,
  38981. indicesByUUID = this._indicesByUUID,
  38982. bindings = this._bindings,
  38983. nBindings = bindings.length;
  38984. let nCachedObjects = this.nCachedObjects_,
  38985. nObjects = objects.length;
  38986. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38987. const object = arguments[ i ],
  38988. uuid = object.uuid,
  38989. index = indicesByUUID[ uuid ];
  38990. if ( index !== undefined ) {
  38991. delete indicesByUUID[ uuid ];
  38992. if ( index < nCachedObjects ) {
  38993. // object is cached, shrink the CACHED region
  38994. const firstActiveIndex = -- nCachedObjects,
  38995. lastCachedObject = objects[ firstActiveIndex ],
  38996. lastIndex = -- nObjects,
  38997. lastObject = objects[ lastIndex ];
  38998. // last cached object takes this object's place
  38999. indicesByUUID[ lastCachedObject.uuid ] = index;
  39000. objects[ index ] = lastCachedObject;
  39001. // last object goes to the activated slot and pop
  39002. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  39003. objects[ firstActiveIndex ] = lastObject;
  39004. objects.pop();
  39005. // accounting is done, now do the same for all bindings
  39006. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  39007. const bindingsForPath = bindings[ j ],
  39008. lastCached = bindingsForPath[ firstActiveIndex ],
  39009. last = bindingsForPath[ lastIndex ];
  39010. bindingsForPath[ index ] = lastCached;
  39011. bindingsForPath[ firstActiveIndex ] = last;
  39012. bindingsForPath.pop();
  39013. }
  39014. } else {
  39015. // object is active, just swap with the last and pop
  39016. const lastIndex = -- nObjects,
  39017. lastObject = objects[ lastIndex ];
  39018. if ( lastIndex > 0 ) {
  39019. indicesByUUID[ lastObject.uuid ] = index;
  39020. }
  39021. objects[ index ] = lastObject;
  39022. objects.pop();
  39023. // accounting is done, now do the same for all bindings
  39024. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  39025. const bindingsForPath = bindings[ j ];
  39026. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  39027. bindingsForPath.pop();
  39028. }
  39029. } // cached or active
  39030. } // if object is known
  39031. } // for arguments
  39032. this.nCachedObjects_ = nCachedObjects;
  39033. }
  39034. // Internal interface used by befriended PropertyBinding.Composite:
  39035. subscribe_( path, parsedPath ) {
  39036. // returns an array of bindings for the given path that is changed
  39037. // according to the contained objects in the group
  39038. const indicesByPath = this._bindingsIndicesByPath;
  39039. let index = indicesByPath[ path ];
  39040. const bindings = this._bindings;
  39041. if ( index !== undefined ) return bindings[ index ];
  39042. const paths = this._paths,
  39043. parsedPaths = this._parsedPaths,
  39044. objects = this._objects,
  39045. nObjects = objects.length,
  39046. nCachedObjects = this.nCachedObjects_,
  39047. bindingsForPath = new Array( nObjects );
  39048. index = bindings.length;
  39049. indicesByPath[ path ] = index;
  39050. paths.push( path );
  39051. parsedPaths.push( parsedPath );
  39052. bindings.push( bindingsForPath );
  39053. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  39054. const object = objects[ i ];
  39055. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  39056. }
  39057. return bindingsForPath;
  39058. }
  39059. unsubscribe_( path ) {
  39060. // tells the group to forget about a property path and no longer
  39061. // update the array previously obtained with 'subscribe_'
  39062. const indicesByPath = this._bindingsIndicesByPath,
  39063. index = indicesByPath[ path ];
  39064. if ( index !== undefined ) {
  39065. const paths = this._paths,
  39066. parsedPaths = this._parsedPaths,
  39067. bindings = this._bindings,
  39068. lastBindingsIndex = bindings.length - 1,
  39069. lastBindings = bindings[ lastBindingsIndex ],
  39070. lastBindingsPath = path[ lastBindingsIndex ];
  39071. indicesByPath[ lastBindingsPath ] = index;
  39072. bindings[ index ] = lastBindings;
  39073. bindings.pop();
  39074. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  39075. parsedPaths.pop();
  39076. paths[ index ] = paths[ lastBindingsIndex ];
  39077. paths.pop();
  39078. }
  39079. }
  39080. }
  39081. /**
  39082. * An instance of `AnimationAction` schedules the playback of an animation which is
  39083. * stored in {@link AnimationClip}.
  39084. */
  39085. class AnimationAction {
  39086. /**
  39087. * Constructs a new animation action.
  39088. *
  39089. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  39090. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  39091. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  39092. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39093. */
  39094. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  39095. this._mixer = mixer;
  39096. this._clip = clip;
  39097. this._localRoot = localRoot;
  39098. /**
  39099. * Defines how the animation is blended/combined when two or more animations
  39100. * are simultaneously played.
  39101. *
  39102. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  39103. */
  39104. this.blendMode = blendMode;
  39105. const tracks = clip.tracks,
  39106. nTracks = tracks.length,
  39107. interpolants = new Array( nTracks );
  39108. const interpolantSettings = {
  39109. endingStart: ZeroCurvatureEnding,
  39110. endingEnd: ZeroCurvatureEnding
  39111. };
  39112. for ( let i = 0; i !== nTracks; ++ i ) {
  39113. const interpolant = tracks[ i ].createInterpolant( null );
  39114. interpolants[ i ] = interpolant;
  39115. interpolant.settings = interpolantSettings;
  39116. }
  39117. this._interpolantSettings = interpolantSettings;
  39118. this._interpolants = interpolants; // bound by the mixer
  39119. // inside: PropertyMixer (managed by the mixer)
  39120. this._propertyBindings = new Array( nTracks );
  39121. this._cacheIndex = null; // for the memory manager
  39122. this._byClipCacheIndex = null; // for the memory manager
  39123. this._timeScaleInterpolant = null;
  39124. this._restoreTimeScale = null;
  39125. this._weightInterpolant = null;
  39126. /**
  39127. * The loop mode, set via {@link AnimationAction#setLoop}.
  39128. *
  39129. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  39130. * @default LoopRepeat
  39131. */
  39132. this.loop = LoopRepeat;
  39133. this._loopCount = -1;
  39134. // global mixer time when the action is to be started
  39135. // it's set back to 'null' upon start of the action
  39136. this._startTime = null;
  39137. /**
  39138. * The local time of this action (in seconds, starting with `0`).
  39139. *
  39140. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  39141. * loop state).
  39142. *
  39143. * @type {number}
  39144. * @default Infinity
  39145. */
  39146. this.time = 0;
  39147. /**
  39148. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  39149. * animation to pause. Negative values cause the animation to play backwards.
  39150. *
  39151. * @type {number}
  39152. * @default 1
  39153. */
  39154. this.timeScale = 1;
  39155. this._effectiveTimeScale = 1;
  39156. /**
  39157. * The degree of influence of this action (in the interval `[0, 1]`). Values
  39158. * between `0` (no impact) and `1` (full impact) can be used to blend between
  39159. * several actions.
  39160. *
  39161. * @type {number}
  39162. * @default 1
  39163. */
  39164. this.weight = 1;
  39165. this._effectiveWeight = 1;
  39166. /**
  39167. * The number of repetitions of the performed clip over the course of this action.
  39168. * Can be set via {@link AnimationAction#setLoop}.
  39169. *
  39170. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  39171. * `THREE:LoopOnce`.
  39172. *
  39173. * @type {number}
  39174. * @default Infinity
  39175. */
  39176. this.repetitions = Infinity;
  39177. /**
  39178. * If set to `true`, the playback of the action is paused.
  39179. *
  39180. * @type {boolean}
  39181. * @default false
  39182. */
  39183. this.paused = false;
  39184. /**
  39185. * If set to `false`, the action is disabled so it has no impact.
  39186. *
  39187. * When the action is re-enabled, the animation continues from its current
  39188. * time (setting `enabled` to `false` doesn't reset the action).
  39189. *
  39190. * @type {boolean}
  39191. * @default true
  39192. */
  39193. this.enabled = true;
  39194. /**
  39195. * If set to true the animation will automatically be paused on its last frame.
  39196. *
  39197. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  39198. * to `false` when the last loop of the action has finished, so that this action has
  39199. * no further impact.
  39200. *
  39201. * Note: This member has no impact if the action is interrupted (it
  39202. * has only an effect if its last loop has really finished).
  39203. *
  39204. * @type {boolean}
  39205. * @default false
  39206. */
  39207. this.clampWhenFinished = false;
  39208. /**
  39209. * Enables smooth interpolation without separate clips for start, loop and end.
  39210. *
  39211. * @type {boolean}
  39212. * @default true
  39213. */
  39214. this.zeroSlopeAtStart = true;
  39215. /**
  39216. * Enables smooth interpolation without separate clips for start, loop and end.
  39217. *
  39218. * @type {boolean}
  39219. * @default true
  39220. */
  39221. this.zeroSlopeAtEnd = true;
  39222. }
  39223. /**
  39224. * Starts the playback of the animation.
  39225. *
  39226. * @return {AnimationAction} A reference to this animation action.
  39227. */
  39228. play() {
  39229. this._mixer._activateAction( this );
  39230. return this;
  39231. }
  39232. /**
  39233. * Stops the playback of the animation.
  39234. *
  39235. * @return {AnimationAction} A reference to this animation action.
  39236. */
  39237. stop() {
  39238. this._mixer._deactivateAction( this );
  39239. return this.reset();
  39240. }
  39241. /**
  39242. * Resets the playback of the animation.
  39243. *
  39244. * @return {AnimationAction} A reference to this animation action.
  39245. */
  39246. reset() {
  39247. this.paused = false;
  39248. this.enabled = true;
  39249. this.time = 0; // restart clip
  39250. this._loopCount = -1;// forget previous loops
  39251. this._startTime = null;// forget scheduling
  39252. return this.stopFading().stopWarping();
  39253. }
  39254. /**
  39255. * Returns `true` if the animation is running.
  39256. *
  39257. * @return {boolean} Whether the animation is running or not.
  39258. */
  39259. isRunning() {
  39260. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  39261. this._startTime === null && this._mixer._isActiveAction( this );
  39262. }
  39263. /**
  39264. * Returns `true` when {@link AnimationAction#play} has been called.
  39265. *
  39266. * @return {boolean} Whether the animation is scheduled or not.
  39267. */
  39268. isScheduled() {
  39269. return this._mixer._isActiveAction( this );
  39270. }
  39271. /**
  39272. * Defines the time when the animation should start.
  39273. *
  39274. * @param {number} time - The start time in seconds.
  39275. * @return {AnimationAction} A reference to this animation action.
  39276. */
  39277. startAt( time ) {
  39278. this._startTime = time;
  39279. return this;
  39280. }
  39281. /**
  39282. * Configures the loop settings for this action.
  39283. *
  39284. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  39285. * @param {number} repetitions - The number of repetitions.
  39286. * @return {AnimationAction} A reference to this animation action.
  39287. */
  39288. setLoop( mode, repetitions ) {
  39289. this.loop = mode;
  39290. this.repetitions = repetitions;
  39291. return this;
  39292. }
  39293. /**
  39294. * Sets the effective weight of this action.
  39295. *
  39296. * An action has no effect and thus an effective weight of zero when the
  39297. * action is disabled.
  39298. *
  39299. * @param {number} weight - The weight to set.
  39300. * @return {AnimationAction} A reference to this animation action.
  39301. */
  39302. setEffectiveWeight( weight ) {
  39303. this.weight = weight;
  39304. // note: same logic as when updated at runtime
  39305. this._effectiveWeight = this.enabled ? weight : 0;
  39306. return this.stopFading();
  39307. }
  39308. /**
  39309. * Returns the effective weight of this action.
  39310. *
  39311. * @return {number} The effective weight.
  39312. */
  39313. getEffectiveWeight() {
  39314. return this._effectiveWeight;
  39315. }
  39316. /**
  39317. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  39318. * within the passed time interval.
  39319. *
  39320. * @param {number} duration - The duration of the fade.
  39321. * @return {AnimationAction} A reference to this animation action.
  39322. */
  39323. fadeIn( duration ) {
  39324. return this._scheduleFading( duration, 0, 1 );
  39325. }
  39326. /**
  39327. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  39328. * within the passed time interval.
  39329. *
  39330. * @param {number} duration - The duration of the fade.
  39331. * @return {AnimationAction} A reference to this animation action.
  39332. */
  39333. fadeOut( duration ) {
  39334. return this._scheduleFading( duration, 1, 0 );
  39335. }
  39336. /**
  39337. * Causes this action to fade in and the given action to fade out,
  39338. * within the passed time interval.
  39339. *
  39340. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  39341. * @param {number} duration - The duration of the fade.
  39342. * @param {boolean} [warp=false] - Whether warping should be used or not.
  39343. * @return {AnimationAction} A reference to this animation action.
  39344. */
  39345. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  39346. fadeOutAction.fadeOut( duration );
  39347. this.fadeIn( duration );
  39348. if ( warp === true ) {
  39349. const fadeInDuration = this._clip.duration,
  39350. fadeOutDuration = fadeOutAction._clip.duration,
  39351. startEndRatio = fadeOutDuration / fadeInDuration,
  39352. endStartRatio = fadeInDuration / fadeOutDuration;
  39353. fadeOutAction._restoreTimeScale = fadeOutAction.timeScale;
  39354. this._restoreTimeScale = this.timeScale;
  39355. fadeOutAction.warp( 1.0, startEndRatio, duration );
  39356. this.warp( endStartRatio, 1.0, duration );
  39357. }
  39358. return this;
  39359. }
  39360. /**
  39361. * Causes this action to fade out and the given action to fade in,
  39362. * within the passed time interval.
  39363. *
  39364. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  39365. * @param {number} duration - The duration of the fade.
  39366. * @param {boolean} [warp=false] - Whether warping should be used or not.
  39367. * @return {AnimationAction} A reference to this animation action.
  39368. */
  39369. crossFadeTo( fadeInAction, duration, warp = false ) {
  39370. return fadeInAction.crossFadeFrom( this, duration, warp );
  39371. }
  39372. /**
  39373. * Stops any fading which is applied to this action.
  39374. *
  39375. * @return {AnimationAction} A reference to this animation action.
  39376. */
  39377. stopFading() {
  39378. const weightInterpolant = this._weightInterpolant;
  39379. if ( weightInterpolant !== null ) {
  39380. this._weightInterpolant = null;
  39381. this._mixer._takeBackControlInterpolant( weightInterpolant );
  39382. }
  39383. return this;
  39384. }
  39385. /**
  39386. * Sets the effective time scale of this action.
  39387. *
  39388. * An action has no effect and thus an effective time scale of zero when the
  39389. * action is paused.
  39390. *
  39391. * @param {number} timeScale - The time scale to set.
  39392. * @return {AnimationAction} A reference to this animation action.
  39393. */
  39394. setEffectiveTimeScale( timeScale ) {
  39395. this.timeScale = timeScale;
  39396. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  39397. return this.stopWarping();
  39398. }
  39399. /**
  39400. * Returns the effective time scale of this action.
  39401. *
  39402. * @return {number} The effective time scale.
  39403. */
  39404. getEffectiveTimeScale() {
  39405. return this._effectiveTimeScale;
  39406. }
  39407. /**
  39408. * Sets the duration for a single loop of this action.
  39409. *
  39410. * @param {number} duration - The duration to set.
  39411. * @return {AnimationAction} A reference to this animation action.
  39412. */
  39413. setDuration( duration ) {
  39414. this.timeScale = this._clip.duration / duration;
  39415. return this.stopWarping();
  39416. }
  39417. /**
  39418. * Synchronizes this action with the passed other action.
  39419. *
  39420. * @param {AnimationAction} action - The action to sync with.
  39421. * @return {AnimationAction} A reference to this animation action.
  39422. */
  39423. syncWith( action ) {
  39424. this.time = action.time;
  39425. this.timeScale = action.timeScale;
  39426. return this.stopWarping();
  39427. }
  39428. /**
  39429. * Decelerates this animation's speed to `0` within the passed time interval.
  39430. *
  39431. * @param {number} duration - The duration.
  39432. * @return {AnimationAction} A reference to this animation action.
  39433. */
  39434. halt( duration ) {
  39435. return this.warp( this._effectiveTimeScale, 0, duration );
  39436. }
  39437. /**
  39438. * Changes the playback speed, within the passed time interval, by modifying
  39439. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  39440. * `endTimeScale`.
  39441. *
  39442. * @param {number} startTimeScale - The start time scale.
  39443. * @param {number} endTimeScale - The end time scale.
  39444. * @param {number} duration - The duration.
  39445. * @return {AnimationAction} A reference to this animation action.
  39446. */
  39447. warp( startTimeScale, endTimeScale, duration ) {
  39448. const mixer = this._mixer,
  39449. now = mixer.time,
  39450. timeScale = this.timeScale;
  39451. let interpolant = this._timeScaleInterpolant;
  39452. if ( interpolant === null ) {
  39453. interpolant = mixer._lendControlInterpolant();
  39454. this._timeScaleInterpolant = interpolant;
  39455. }
  39456. const times = interpolant.parameterPositions,
  39457. values = interpolant.sampleValues;
  39458. times[ 0 ] = now;
  39459. times[ 1 ] = now + duration;
  39460. values[ 0 ] = startTimeScale / timeScale;
  39461. values[ 1 ] = endTimeScale / timeScale;
  39462. return this;
  39463. }
  39464. /**
  39465. * Stops any scheduled warping which is applied to this action.
  39466. *
  39467. * @return {AnimationAction} A reference to this animation action.
  39468. */
  39469. stopWarping() {
  39470. const timeScaleInterpolant = this._timeScaleInterpolant;
  39471. if ( timeScaleInterpolant !== null ) {
  39472. this._timeScaleInterpolant = null;
  39473. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  39474. }
  39475. this._restoreTimeScale = null;
  39476. return this;
  39477. }
  39478. /**
  39479. * Returns the animation mixer of this animation action.
  39480. *
  39481. * @return {AnimationMixer} The animation mixer.
  39482. */
  39483. getMixer() {
  39484. return this._mixer;
  39485. }
  39486. /**
  39487. * Returns the animation clip of this animation action.
  39488. *
  39489. * @return {AnimationClip} The animation clip.
  39490. */
  39491. getClip() {
  39492. return this._clip;
  39493. }
  39494. /**
  39495. * Returns the root object of this animation action.
  39496. *
  39497. * @return {Object3D} The root object.
  39498. */
  39499. getRoot() {
  39500. return this._localRoot || this._mixer._root;
  39501. }
  39502. // Internal
  39503. _update( time, deltaTime, timeDirection, accuIndex ) {
  39504. // called by the mixer
  39505. if ( ! this.enabled ) {
  39506. // call ._updateWeight() to update ._effectiveWeight
  39507. this._updateWeight( time );
  39508. return;
  39509. }
  39510. const startTime = this._startTime;
  39511. if ( startTime !== null ) {
  39512. // check for scheduled start of action
  39513. const timeRunning = ( time - startTime ) * timeDirection;
  39514. if ( timeRunning < 0 || timeDirection === 0 ) {
  39515. deltaTime = 0;
  39516. } else {
  39517. this._startTime = null; // unschedule
  39518. deltaTime = timeDirection * timeRunning;
  39519. }
  39520. }
  39521. // apply time scale and advance time
  39522. deltaTime *= this._updateTimeScale( time );
  39523. const clipTime = this._updateTime( deltaTime );
  39524. // note: _updateTime may disable the action resulting in
  39525. // an effective weight of 0
  39526. const weight = this._updateWeight( time );
  39527. if ( weight > 0 ) {
  39528. const interpolants = this._interpolants;
  39529. const propertyMixers = this._propertyBindings;
  39530. switch ( this.blendMode ) {
  39531. case AdditiveAnimationBlendMode:
  39532. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39533. interpolants[ j ].evaluate( clipTime );
  39534. propertyMixers[ j ].accumulateAdditive( weight );
  39535. }
  39536. break;
  39537. case NormalAnimationBlendMode:
  39538. default:
  39539. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39540. interpolants[ j ].evaluate( clipTime );
  39541. propertyMixers[ j ].accumulate( accuIndex, weight );
  39542. }
  39543. }
  39544. }
  39545. }
  39546. _updateWeight( time ) {
  39547. let weight = 0;
  39548. if ( this.enabled ) {
  39549. weight = this.weight;
  39550. const interpolant = this._weightInterpolant;
  39551. if ( interpolant !== null ) {
  39552. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39553. weight *= interpolantValue;
  39554. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39555. this.stopFading();
  39556. if ( interpolantValue === 0 ) {
  39557. // faded out, disable
  39558. this.enabled = false;
  39559. }
  39560. }
  39561. }
  39562. }
  39563. this._effectiveWeight = weight;
  39564. return weight;
  39565. }
  39566. _updateTimeScale( time ) {
  39567. let timeScale = 0;
  39568. if ( ! this.paused ) {
  39569. timeScale = this.timeScale;
  39570. const interpolant = this._timeScaleInterpolant;
  39571. if ( interpolant !== null ) {
  39572. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39573. timeScale *= interpolantValue;
  39574. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39575. if ( timeScale === 0 ) {
  39576. // motion has halted, pause
  39577. this.paused = true;
  39578. } else {
  39579. if ( this._restoreTimeScale !== null ) {
  39580. timeScale = this._restoreTimeScale;
  39581. }
  39582. // warp done - apply final time scale
  39583. this.timeScale = timeScale;
  39584. }
  39585. this.stopWarping();
  39586. }
  39587. }
  39588. }
  39589. this._effectiveTimeScale = timeScale;
  39590. return timeScale;
  39591. }
  39592. _updateTime( deltaTime ) {
  39593. const duration = this._clip.duration;
  39594. const loop = this.loop;
  39595. let time = this.time + deltaTime;
  39596. let loopCount = this._loopCount;
  39597. const pingPong = ( loop === LoopPingPong );
  39598. if ( deltaTime === 0 ) {
  39599. if ( loopCount === -1 ) return time;
  39600. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  39601. }
  39602. if ( loop === LoopOnce ) {
  39603. if ( loopCount === -1 ) {
  39604. // just started
  39605. this._loopCount = 0;
  39606. this._setEndings( true, true, false );
  39607. }
  39608. handle_stop: {
  39609. if ( time >= duration ) {
  39610. time = duration;
  39611. } else if ( time < 0 ) {
  39612. time = 0;
  39613. } else {
  39614. this.time = time;
  39615. break handle_stop;
  39616. }
  39617. if ( this.clampWhenFinished ) this.paused = true;
  39618. else this.enabled = false;
  39619. this.time = time;
  39620. this._mixer.dispatchEvent( {
  39621. type: 'finished', action: this,
  39622. direction: deltaTime < 0 ? -1 : 1
  39623. } );
  39624. }
  39625. } else { // repetitive Repeat or PingPong
  39626. if ( loopCount === -1 ) {
  39627. // just started
  39628. if ( deltaTime >= 0 ) {
  39629. loopCount = 0;
  39630. this._setEndings( true, this.repetitions === 0, pingPong );
  39631. } else {
  39632. // when looping in reverse direction, the initial
  39633. // transition through zero counts as a repetition,
  39634. // so leave loopCount at -1
  39635. this._setEndings( this.repetitions === 0, true, pingPong );
  39636. }
  39637. }
  39638. if ( time >= duration || time < 0 ) {
  39639. // wrap around
  39640. const loopDelta = Math.floor( time / duration ); // signed
  39641. time -= duration * loopDelta;
  39642. loopCount += Math.abs( loopDelta );
  39643. const pending = this.repetitions - loopCount;
  39644. if ( pending <= 0 ) {
  39645. // have to stop (switch state, clamp time, fire event)
  39646. if ( this.clampWhenFinished ) this.paused = true;
  39647. else this.enabled = false;
  39648. time = deltaTime > 0 ? duration : 0;
  39649. this.time = time;
  39650. this._mixer.dispatchEvent( {
  39651. type: 'finished', action: this,
  39652. direction: deltaTime > 0 ? 1 : -1
  39653. } );
  39654. } else {
  39655. // keep running
  39656. if ( pending === 1 ) {
  39657. // entering the last round
  39658. const atStart = deltaTime < 0;
  39659. this._setEndings( atStart, ! atStart, pingPong );
  39660. } else {
  39661. this._setEndings( false, false, pingPong );
  39662. }
  39663. this._loopCount = loopCount;
  39664. this.time = time;
  39665. this._mixer.dispatchEvent( {
  39666. type: 'loop', action: this, loopDelta: loopDelta
  39667. } );
  39668. }
  39669. } else {
  39670. this._loopCount = loopCount;
  39671. this.time = time;
  39672. }
  39673. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39674. // invert time for the "pong round"
  39675. return duration - time;
  39676. }
  39677. }
  39678. return time;
  39679. }
  39680. _setEndings( atStart, atEnd, pingPong ) {
  39681. const settings = this._interpolantSettings;
  39682. if ( pingPong ) {
  39683. settings.endingStart = ZeroSlopeEnding;
  39684. settings.endingEnd = ZeroSlopeEnding;
  39685. } else {
  39686. // assuming for LoopOnce atStart == atEnd == true
  39687. if ( atStart ) {
  39688. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39689. } else {
  39690. settings.endingStart = WrapAroundEnding;
  39691. }
  39692. if ( atEnd ) {
  39693. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39694. } else {
  39695. settings.endingEnd = WrapAroundEnding;
  39696. }
  39697. }
  39698. }
  39699. _scheduleFading( duration, weightNow, weightThen ) {
  39700. const mixer = this._mixer, now = mixer.time;
  39701. let interpolant = this._weightInterpolant;
  39702. if ( interpolant === null ) {
  39703. interpolant = mixer._lendControlInterpolant();
  39704. this._weightInterpolant = interpolant;
  39705. }
  39706. const times = interpolant.parameterPositions,
  39707. values = interpolant.sampleValues;
  39708. times[ 0 ] = now;
  39709. values[ 0 ] = weightNow;
  39710. times[ 1 ] = now + duration;
  39711. values[ 1 ] = weightThen;
  39712. return this;
  39713. }
  39714. }
  39715. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39716. /**
  39717. * `AnimationMixer` is a player for animations on a particular object in
  39718. * the scene. When multiple objects in the scene are animated independently,
  39719. * one `AnimationMixer` may be used for each object.
  39720. */
  39721. class AnimationMixer extends EventDispatcher {
  39722. /**
  39723. * Constructs a new animation mixer.
  39724. *
  39725. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39726. */
  39727. constructor( root ) {
  39728. super();
  39729. this._root = root;
  39730. this._initMemoryManager();
  39731. this._accuIndex = 0;
  39732. /**
  39733. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39734. *
  39735. * @type {number}
  39736. * @default 0
  39737. */
  39738. this.time = 0;
  39739. /**
  39740. * A scaling factor for the global time.
  39741. *
  39742. * Note: Setting this member to `0` and later back to `1` is a
  39743. * possibility to pause/unpause all actions that are controlled by this
  39744. * mixer.
  39745. *
  39746. * @type {number}
  39747. * @default 1
  39748. */
  39749. this.timeScale = 1.0;
  39750. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39751. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39752. }
  39753. }
  39754. _bindAction( action, prototypeAction ) {
  39755. const root = action._localRoot || this._root,
  39756. tracks = action._clip.tracks,
  39757. nTracks = tracks.length,
  39758. bindings = action._propertyBindings,
  39759. interpolants = action._interpolants,
  39760. rootUuid = root.uuid,
  39761. bindingsByRoot = this._bindingsByRootAndName;
  39762. let bindingsByName = bindingsByRoot[ rootUuid ];
  39763. if ( bindingsByName === undefined ) {
  39764. bindingsByName = {};
  39765. bindingsByRoot[ rootUuid ] = bindingsByName;
  39766. }
  39767. for ( let i = 0; i !== nTracks; ++ i ) {
  39768. const track = tracks[ i ],
  39769. trackName = track.name;
  39770. let binding = bindingsByName[ trackName ];
  39771. if ( binding !== undefined ) {
  39772. ++ binding.referenceCount;
  39773. bindings[ i ] = binding;
  39774. } else {
  39775. binding = bindings[ i ];
  39776. if ( binding !== undefined ) {
  39777. // existing binding, make sure the cache knows
  39778. if ( binding._cacheIndex === null ) {
  39779. ++ binding.referenceCount;
  39780. this._addInactiveBinding( binding, rootUuid, trackName );
  39781. }
  39782. continue;
  39783. }
  39784. const path = prototypeAction && prototypeAction.
  39785. _propertyBindings[ i ].binding.parsedPath;
  39786. binding = new PropertyMixer(
  39787. PropertyBinding.create( root, trackName, path ),
  39788. track.ValueTypeName, track.getValueSize() );
  39789. ++ binding.referenceCount;
  39790. this._addInactiveBinding( binding, rootUuid, trackName );
  39791. bindings[ i ] = binding;
  39792. }
  39793. interpolants[ i ].resultBuffer = binding.buffer;
  39794. }
  39795. }
  39796. _activateAction( action ) {
  39797. if ( ! this._isActiveAction( action ) ) {
  39798. if ( action._cacheIndex === null ) {
  39799. // this action has been forgotten by the cache, but the user
  39800. // appears to be still using it -> rebind
  39801. const rootUuid = ( action._localRoot || this._root ).uuid,
  39802. clipUuid = action._clip.uuid,
  39803. actionsForClip = this._actionsByClip[ clipUuid ];
  39804. this._bindAction( action,
  39805. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39806. this._addInactiveAction( action, clipUuid, rootUuid );
  39807. }
  39808. const bindings = action._propertyBindings;
  39809. // increment reference counts / sort out state
  39810. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39811. const binding = bindings[ i ];
  39812. if ( binding.useCount ++ === 0 ) {
  39813. this._lendBinding( binding );
  39814. binding.saveOriginalState();
  39815. }
  39816. }
  39817. this._lendAction( action );
  39818. }
  39819. }
  39820. _deactivateAction( action ) {
  39821. if ( this._isActiveAction( action ) ) {
  39822. const bindings = action._propertyBindings;
  39823. // decrement reference counts / sort out state
  39824. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39825. const binding = bindings[ i ];
  39826. if ( -- binding.useCount === 0 ) {
  39827. binding.restoreOriginalState();
  39828. this._takeBackBinding( binding );
  39829. }
  39830. }
  39831. this._takeBackAction( action );
  39832. }
  39833. }
  39834. // Memory manager
  39835. _initMemoryManager() {
  39836. this._actions = []; // 'nActiveActions' followed by inactive ones
  39837. this._nActiveActions = 0;
  39838. this._actionsByClip = {};
  39839. // inside:
  39840. // {
  39841. // knownActions: Array< AnimationAction > - used as prototypes
  39842. // actionByRoot: AnimationAction - lookup
  39843. // }
  39844. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39845. this._nActiveBindings = 0;
  39846. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39847. this._controlInterpolants = []; // same game as above
  39848. this._nActiveControlInterpolants = 0;
  39849. const scope = this;
  39850. this.stats = {
  39851. actions: {
  39852. get total() {
  39853. return scope._actions.length;
  39854. },
  39855. get inUse() {
  39856. return scope._nActiveActions;
  39857. }
  39858. },
  39859. bindings: {
  39860. get total() {
  39861. return scope._bindings.length;
  39862. },
  39863. get inUse() {
  39864. return scope._nActiveBindings;
  39865. }
  39866. },
  39867. controlInterpolants: {
  39868. get total() {
  39869. return scope._controlInterpolants.length;
  39870. },
  39871. get inUse() {
  39872. return scope._nActiveControlInterpolants;
  39873. }
  39874. }
  39875. };
  39876. }
  39877. // Memory management for AnimationAction objects
  39878. _isActiveAction( action ) {
  39879. const index = action._cacheIndex;
  39880. return index !== null && index < this._nActiveActions;
  39881. }
  39882. _addInactiveAction( action, clipUuid, rootUuid ) {
  39883. const actions = this._actions,
  39884. actionsByClip = this._actionsByClip;
  39885. let actionsForClip = actionsByClip[ clipUuid ];
  39886. if ( actionsForClip === undefined ) {
  39887. actionsForClip = {
  39888. knownActions: [ action ],
  39889. actionByRoot: {}
  39890. };
  39891. action._byClipCacheIndex = 0;
  39892. actionsByClip[ clipUuid ] = actionsForClip;
  39893. } else {
  39894. const knownActions = actionsForClip.knownActions;
  39895. action._byClipCacheIndex = knownActions.length;
  39896. knownActions.push( action );
  39897. }
  39898. action._cacheIndex = actions.length;
  39899. actions.push( action );
  39900. actionsForClip.actionByRoot[ rootUuid ] = action;
  39901. }
  39902. _removeInactiveAction( action ) {
  39903. const actions = this._actions,
  39904. lastInactiveAction = actions[ actions.length - 1 ],
  39905. cacheIndex = action._cacheIndex;
  39906. lastInactiveAction._cacheIndex = cacheIndex;
  39907. actions[ cacheIndex ] = lastInactiveAction;
  39908. actions.pop();
  39909. action._cacheIndex = null;
  39910. const clipUuid = action._clip.uuid,
  39911. actionsByClip = this._actionsByClip,
  39912. actionsForClip = actionsByClip[ clipUuid ],
  39913. knownActionsForClip = actionsForClip.knownActions,
  39914. lastKnownAction =
  39915. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39916. byClipCacheIndex = action._byClipCacheIndex;
  39917. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39918. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39919. knownActionsForClip.pop();
  39920. action._byClipCacheIndex = null;
  39921. const actionByRoot = actionsForClip.actionByRoot,
  39922. rootUuid = ( action._localRoot || this._root ).uuid;
  39923. delete actionByRoot[ rootUuid ];
  39924. if ( knownActionsForClip.length === 0 ) {
  39925. delete actionsByClip[ clipUuid ];
  39926. }
  39927. this._removeInactiveBindingsForAction( action );
  39928. }
  39929. _removeInactiveBindingsForAction( action ) {
  39930. const bindings = action._propertyBindings;
  39931. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39932. const binding = bindings[ i ];
  39933. if ( -- binding.referenceCount === 0 ) {
  39934. this._removeInactiveBinding( binding );
  39935. }
  39936. }
  39937. }
  39938. _lendAction( action ) {
  39939. // [ active actions | inactive actions ]
  39940. // [ active actions >| inactive actions ]
  39941. // s a
  39942. // <-swap->
  39943. // a s
  39944. const actions = this._actions,
  39945. prevIndex = action._cacheIndex,
  39946. lastActiveIndex = this._nActiveActions ++,
  39947. firstInactiveAction = actions[ lastActiveIndex ];
  39948. action._cacheIndex = lastActiveIndex;
  39949. actions[ lastActiveIndex ] = action;
  39950. firstInactiveAction._cacheIndex = prevIndex;
  39951. actions[ prevIndex ] = firstInactiveAction;
  39952. }
  39953. _takeBackAction( action ) {
  39954. // [ active actions | inactive actions ]
  39955. // [ active actions |< inactive actions ]
  39956. // a s
  39957. // <-swap->
  39958. // s a
  39959. const actions = this._actions,
  39960. prevIndex = action._cacheIndex,
  39961. firstInactiveIndex = -- this._nActiveActions,
  39962. lastActiveAction = actions[ firstInactiveIndex ];
  39963. action._cacheIndex = firstInactiveIndex;
  39964. actions[ firstInactiveIndex ] = action;
  39965. lastActiveAction._cacheIndex = prevIndex;
  39966. actions[ prevIndex ] = lastActiveAction;
  39967. }
  39968. // Memory management for PropertyMixer objects
  39969. _addInactiveBinding( binding, rootUuid, trackName ) {
  39970. const bindingsByRoot = this._bindingsByRootAndName,
  39971. bindings = this._bindings;
  39972. let bindingByName = bindingsByRoot[ rootUuid ];
  39973. if ( bindingByName === undefined ) {
  39974. bindingByName = {};
  39975. bindingsByRoot[ rootUuid ] = bindingByName;
  39976. }
  39977. bindingByName[ trackName ] = binding;
  39978. binding._cacheIndex = bindings.length;
  39979. bindings.push( binding );
  39980. }
  39981. _removeInactiveBinding( binding ) {
  39982. const bindings = this._bindings,
  39983. propBinding = binding.binding,
  39984. rootUuid = propBinding.rootNode.uuid,
  39985. trackName = propBinding.path,
  39986. bindingsByRoot = this._bindingsByRootAndName,
  39987. bindingByName = bindingsByRoot[ rootUuid ],
  39988. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39989. cacheIndex = binding._cacheIndex;
  39990. lastInactiveBinding._cacheIndex = cacheIndex;
  39991. bindings[ cacheIndex ] = lastInactiveBinding;
  39992. bindings.pop();
  39993. delete bindingByName[ trackName ];
  39994. if ( Object.keys( bindingByName ).length === 0 ) {
  39995. delete bindingsByRoot[ rootUuid ];
  39996. }
  39997. }
  39998. _lendBinding( binding ) {
  39999. const bindings = this._bindings,
  40000. prevIndex = binding._cacheIndex,
  40001. lastActiveIndex = this._nActiveBindings ++,
  40002. firstInactiveBinding = bindings[ lastActiveIndex ];
  40003. binding._cacheIndex = lastActiveIndex;
  40004. bindings[ lastActiveIndex ] = binding;
  40005. firstInactiveBinding._cacheIndex = prevIndex;
  40006. bindings[ prevIndex ] = firstInactiveBinding;
  40007. }
  40008. _takeBackBinding( binding ) {
  40009. const bindings = this._bindings,
  40010. prevIndex = binding._cacheIndex,
  40011. firstInactiveIndex = -- this._nActiveBindings,
  40012. lastActiveBinding = bindings[ firstInactiveIndex ];
  40013. binding._cacheIndex = firstInactiveIndex;
  40014. bindings[ firstInactiveIndex ] = binding;
  40015. lastActiveBinding._cacheIndex = prevIndex;
  40016. bindings[ prevIndex ] = lastActiveBinding;
  40017. }
  40018. // Memory management of Interpolants for weight and time scale
  40019. _lendControlInterpolant() {
  40020. const interpolants = this._controlInterpolants,
  40021. lastActiveIndex = this._nActiveControlInterpolants ++;
  40022. let interpolant = interpolants[ lastActiveIndex ];
  40023. if ( interpolant === undefined ) {
  40024. interpolant = new LinearInterpolant(
  40025. new Float32Array( 2 ), new Float32Array( 2 ),
  40026. 1, _controlInterpolantsResultBuffer );
  40027. interpolant.__cacheIndex = lastActiveIndex;
  40028. interpolants[ lastActiveIndex ] = interpolant;
  40029. }
  40030. return interpolant;
  40031. }
  40032. _takeBackControlInterpolant( interpolant ) {
  40033. const interpolants = this._controlInterpolants,
  40034. prevIndex = interpolant.__cacheIndex,
  40035. firstInactiveIndex = -- this._nActiveControlInterpolants,
  40036. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  40037. interpolant.__cacheIndex = firstInactiveIndex;
  40038. interpolants[ firstInactiveIndex ] = interpolant;
  40039. lastActiveInterpolant.__cacheIndex = prevIndex;
  40040. interpolants[ prevIndex ] = lastActiveInterpolant;
  40041. }
  40042. /**
  40043. * Returns an instance of {@link AnimationAction} for the passed clip.
  40044. *
  40045. * If an action fitting the clip and root parameters doesn't yet exist, it
  40046. * will be created by this method. Calling this method several times with the
  40047. * same clip and root parameters always returns the same action.
  40048. *
  40049. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  40050. * @param {Object3D} [optionalRoot] - An alternative root object.
  40051. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  40052. * @return {?AnimationAction} The animation action.
  40053. */
  40054. clipAction( clip, optionalRoot, blendMode ) {
  40055. const root = optionalRoot || this._root,
  40056. rootUuid = root.uuid;
  40057. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  40058. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  40059. const actionsForClip = this._actionsByClip[ clipUuid ];
  40060. let prototypeAction = null;
  40061. if ( blendMode === undefined ) {
  40062. if ( clipObject !== null ) {
  40063. blendMode = clipObject.blendMode;
  40064. } else {
  40065. blendMode = NormalAnimationBlendMode;
  40066. }
  40067. }
  40068. if ( actionsForClip !== undefined ) {
  40069. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  40070. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  40071. return existingAction;
  40072. }
  40073. // we know the clip, so we don't have to parse all
  40074. // the bindings again but can just copy
  40075. prototypeAction = actionsForClip.knownActions[ 0 ];
  40076. // also, take the clip from the prototype action
  40077. if ( clipObject === null )
  40078. clipObject = prototypeAction._clip;
  40079. }
  40080. // clip must be known when specified via string
  40081. if ( clipObject === null ) return null;
  40082. // allocate all resources required to run it
  40083. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  40084. this._bindAction( newAction, prototypeAction );
  40085. // and make the action known to the memory manager
  40086. this._addInactiveAction( newAction, clipUuid, rootUuid );
  40087. return newAction;
  40088. }
  40089. /**
  40090. * Returns an existing animation action for the passed clip.
  40091. *
  40092. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  40093. * @param {Object3D} [optionalRoot] - An alternative root object.
  40094. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  40095. */
  40096. existingAction( clip, optionalRoot ) {
  40097. const root = optionalRoot || this._root,
  40098. rootUuid = root.uuid,
  40099. clipObject = typeof clip === 'string' ?
  40100. AnimationClip.findByName( root, clip ) : clip,
  40101. clipUuid = clipObject ? clipObject.uuid : clip,
  40102. actionsForClip = this._actionsByClip[ clipUuid ];
  40103. if ( actionsForClip !== undefined ) {
  40104. return actionsForClip.actionByRoot[ rootUuid ] || null;
  40105. }
  40106. return null;
  40107. }
  40108. /**
  40109. * Deactivates all previously scheduled actions on this mixer.
  40110. *
  40111. * @return {AnimationMixer} A reference to this animation mixer.
  40112. */
  40113. stopAllAction() {
  40114. const actions = this._actions,
  40115. nActions = this._nActiveActions;
  40116. for ( let i = nActions - 1; i >= 0; -- i ) {
  40117. actions[ i ].stop();
  40118. }
  40119. return this;
  40120. }
  40121. /**
  40122. * Advances the global mixer time and updates the animation.
  40123. *
  40124. * This is usually done in the render loop by passing the delta
  40125. * time from {@link Clock} or {@link Timer}.
  40126. *
  40127. * @param {number} deltaTime - The delta time in seconds.
  40128. * @return {AnimationMixer} A reference to this animation mixer.
  40129. */
  40130. update( deltaTime ) {
  40131. deltaTime *= this.timeScale;
  40132. const actions = this._actions,
  40133. nActions = this._nActiveActions,
  40134. time = this.time += deltaTime,
  40135. timeDirection = Math.sign( deltaTime ),
  40136. accuIndex = this._accuIndex ^= 1;
  40137. // run active actions
  40138. for ( let i = 0; i !== nActions; ++ i ) {
  40139. const action = actions[ i ];
  40140. action._update( time, deltaTime, timeDirection, accuIndex );
  40141. }
  40142. // update scene graph
  40143. const bindings = this._bindings,
  40144. nBindings = this._nActiveBindings;
  40145. for ( let i = 0; i !== nBindings; ++ i ) {
  40146. bindings[ i ].apply( accuIndex );
  40147. }
  40148. return this;
  40149. }
  40150. /**
  40151. * Sets the global mixer to a specific time and updates the animation accordingly.
  40152. *
  40153. * This is useful when you need to jump to an exact time in an animation. The
  40154. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  40155. *
  40156. * @param {number} time - The time to set in seconds.
  40157. * @return {AnimationMixer} A reference to this animation mixer.
  40158. */
  40159. setTime( time ) {
  40160. this.time = 0; // Zero out time attribute for AnimationMixer object;
  40161. for ( let i = 0; i < this._actions.length; i ++ ) {
  40162. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  40163. }
  40164. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  40165. }
  40166. /**
  40167. * Returns this mixer's root object.
  40168. *
  40169. * @return {Object3D} The mixer's root object.
  40170. */
  40171. getRoot() {
  40172. return this._root;
  40173. }
  40174. /**
  40175. * Deallocates all memory resources for a clip. Before using this method make
  40176. * sure to call {@link AnimationAction#stop} for all related actions.
  40177. *
  40178. * @param {AnimationClip} clip - The clip to uncache.
  40179. */
  40180. uncacheClip( clip ) {
  40181. const actions = this._actions,
  40182. clipUuid = clip.uuid,
  40183. actionsByClip = this._actionsByClip,
  40184. actionsForClip = actionsByClip[ clipUuid ];
  40185. if ( actionsForClip !== undefined ) {
  40186. // note: just calling _removeInactiveAction would mess up the
  40187. // iteration state and also require updating the state we can
  40188. // just throw away
  40189. const actionsToRemove = actionsForClip.knownActions;
  40190. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  40191. const action = actionsToRemove[ i ];
  40192. this._deactivateAction( action );
  40193. const cacheIndex = action._cacheIndex,
  40194. lastInactiveAction = actions[ actions.length - 1 ];
  40195. action._cacheIndex = null;
  40196. action._byClipCacheIndex = null;
  40197. lastInactiveAction._cacheIndex = cacheIndex;
  40198. actions[ cacheIndex ] = lastInactiveAction;
  40199. actions.pop();
  40200. this._removeInactiveBindingsForAction( action );
  40201. }
  40202. delete actionsByClip[ clipUuid ];
  40203. }
  40204. }
  40205. /**
  40206. * Deallocates all memory resources for a root object. Before using this
  40207. * method make sure to call {@link AnimationAction#stop} for all related
  40208. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  40209. * mixer operates on a single root.
  40210. *
  40211. * @param {Object3D} root - The root object to uncache.
  40212. */
  40213. uncacheRoot( root ) {
  40214. const rootUuid = root.uuid,
  40215. actionsByClip = this._actionsByClip;
  40216. for ( const clipUuid in actionsByClip ) {
  40217. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  40218. action = actionByRoot[ rootUuid ];
  40219. if ( action !== undefined ) {
  40220. this._deactivateAction( action );
  40221. this._removeInactiveAction( action );
  40222. }
  40223. }
  40224. const bindingsByRoot = this._bindingsByRootAndName,
  40225. bindingByName = bindingsByRoot[ rootUuid ];
  40226. if ( bindingByName !== undefined ) {
  40227. for ( const trackName in bindingByName ) {
  40228. const binding = bindingByName[ trackName ];
  40229. binding.restoreOriginalState();
  40230. this._removeInactiveBinding( binding );
  40231. }
  40232. }
  40233. }
  40234. /**
  40235. * Deallocates all memory resources for an action. The action is identified by the
  40236. * given clip and an optional root object. Before using this method make
  40237. * sure to call {@link AnimationAction#stop} to deactivate the action.
  40238. *
  40239. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  40240. * @param {Object3D} [optionalRoot] - An alternative root object.
  40241. */
  40242. uncacheAction( clip, optionalRoot ) {
  40243. const action = this.existingAction( clip, optionalRoot );
  40244. if ( action !== null ) {
  40245. this._deactivateAction( action );
  40246. this._removeInactiveAction( action );
  40247. }
  40248. }
  40249. }
  40250. /**
  40251. * Represents a 3D render target.
  40252. *
  40253. * @augments RenderTarget
  40254. */
  40255. class RenderTarget3D extends RenderTarget {
  40256. /**
  40257. * Constructs a new 3D render target.
  40258. *
  40259. * @param {number} [width=1] - The width of the render target.
  40260. * @param {number} [height=1] - The height of the render target.
  40261. * @param {number} [depth=1] - The height of the render target.
  40262. * @param {RenderTarget~Options} [options] - The configuration object.
  40263. */
  40264. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  40265. super( width, height, options );
  40266. /**
  40267. * This flag can be used for type testing.
  40268. *
  40269. * @type {boolean}
  40270. * @readonly
  40271. * @default true
  40272. */
  40273. this.isRenderTarget3D = true;
  40274. this.depth = depth;
  40275. /**
  40276. * Overwritten with a different texture type.
  40277. *
  40278. * @type {Data3DTexture}
  40279. */
  40280. this.texture = new Data3DTexture( null, width, height, depth );
  40281. this._setTextureOptions( options );
  40282. this.texture.isRenderTargetTexture = true;
  40283. }
  40284. }
  40285. /**
  40286. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  40287. *
  40288. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  40289. * ```js
  40290. * uniforms: {
  40291. * time: { value: 1.0 },
  40292. * resolution: new Uniform( new Vector2() )
  40293. * };
  40294. * ```
  40295. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  40296. * in {@link WebGLRenderer}.
  40297. */
  40298. class Uniform {
  40299. /**
  40300. * Constructs a new uniform.
  40301. *
  40302. * @param {any} value - The uniform value.
  40303. */
  40304. constructor( value ) {
  40305. /**
  40306. * The uniform value.
  40307. *
  40308. * @type {any}
  40309. */
  40310. this.value = value;
  40311. }
  40312. /**
  40313. * Returns a new uniform with copied values from this instance.
  40314. * If the value has a `clone()` method, the value is cloned as well.
  40315. *
  40316. * @return {Uniform} A clone of this instance.
  40317. */
  40318. clone() {
  40319. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  40320. }
  40321. }
  40322. let _id = 0;
  40323. /**
  40324. * A class for managing multiple uniforms in a single group. The renderer will process
  40325. * such a definition as a single UBO.
  40326. *
  40327. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  40328. * in {@link WebGLRenderer}.
  40329. *
  40330. * @augments EventDispatcher
  40331. */
  40332. class UniformsGroup extends EventDispatcher {
  40333. /**
  40334. * Constructs a new uniforms group.
  40335. */
  40336. constructor() {
  40337. super();
  40338. /**
  40339. * This flag can be used for type testing.
  40340. *
  40341. * @type {boolean}
  40342. * @readonly
  40343. * @default true
  40344. */
  40345. this.isUniformsGroup = true;
  40346. /**
  40347. * The ID of the 3D object.
  40348. *
  40349. * @name UniformsGroup#id
  40350. * @type {number}
  40351. * @readonly
  40352. */
  40353. Object.defineProperty( this, 'id', { value: _id ++ } );
  40354. /**
  40355. * The name of the uniforms group.
  40356. *
  40357. * @type {string}
  40358. */
  40359. this.name = '';
  40360. /**
  40361. * The buffer usage.
  40362. *
  40363. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  40364. * @default StaticDrawUsage
  40365. */
  40366. this.usage = StaticDrawUsage;
  40367. /**
  40368. * An array holding the uniforms.
  40369. *
  40370. * @type {Array<Uniform>}
  40371. */
  40372. this.uniforms = [];
  40373. }
  40374. /**
  40375. * Adds the given uniform to this uniforms group.
  40376. *
  40377. * @param {Uniform} uniform - The uniform to add.
  40378. * @return {UniformsGroup} A reference to this uniforms group.
  40379. */
  40380. add( uniform ) {
  40381. this.uniforms.push( uniform );
  40382. return this;
  40383. }
  40384. /**
  40385. * Removes the given uniform from this uniforms group.
  40386. *
  40387. * @param {Uniform} uniform - The uniform to remove.
  40388. * @return {UniformsGroup} A reference to this uniforms group.
  40389. */
  40390. remove( uniform ) {
  40391. const index = this.uniforms.indexOf( uniform );
  40392. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  40393. return this;
  40394. }
  40395. /**
  40396. * Sets the name of this uniforms group.
  40397. *
  40398. * @param {string} name - The name to set.
  40399. * @return {UniformsGroup} A reference to this uniforms group.
  40400. */
  40401. setName( name ) {
  40402. this.name = name;
  40403. return this;
  40404. }
  40405. /**
  40406. * Sets the usage of this uniforms group.
  40407. *
  40408. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  40409. * @return {UniformsGroup} A reference to this uniforms group.
  40410. */
  40411. setUsage( value ) {
  40412. this.usage = value;
  40413. return this;
  40414. }
  40415. /**
  40416. * Frees the GPU-related resources allocated by this instance. Call this
  40417. * method whenever this instance is no longer used in your app.
  40418. *
  40419. * @fires Texture#dispose
  40420. */
  40421. dispose() {
  40422. this.dispatchEvent( { type: 'dispose' } );
  40423. }
  40424. /**
  40425. * Copies the values of the given uniforms group to this instance.
  40426. *
  40427. * @param {UniformsGroup} source - The uniforms group to copy.
  40428. * @return {UniformsGroup} A reference to this uniforms group.
  40429. */
  40430. copy( source ) {
  40431. this.name = source.name;
  40432. this.usage = source.usage;
  40433. const uniformsSource = source.uniforms;
  40434. this.uniforms.length = 0;
  40435. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  40436. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  40437. for ( let j = 0; j < uniforms.length; j ++ ) {
  40438. this.uniforms.push( uniforms[ j ].clone() );
  40439. }
  40440. }
  40441. return this;
  40442. }
  40443. /**
  40444. * Returns a new uniforms group with copied values from this instance.
  40445. *
  40446. * @return {UniformsGroup} A clone of this instance.
  40447. */
  40448. clone() {
  40449. return new this.constructor().copy( this );
  40450. }
  40451. }
  40452. /**
  40453. * An instanced version of an interleaved buffer.
  40454. *
  40455. * @augments InterleavedBuffer
  40456. */
  40457. class InstancedInterleavedBuffer extends InterleavedBuffer {
  40458. /**
  40459. * Constructs a new instanced interleaved buffer.
  40460. *
  40461. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  40462. * @param {number} stride - The number of typed-array elements per vertex.
  40463. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  40464. */
  40465. constructor( array, stride, meshPerAttribute = 1 ) {
  40466. super( array, stride );
  40467. /**
  40468. * This flag can be used for type testing.
  40469. *
  40470. * @type {boolean}
  40471. * @readonly
  40472. * @default true
  40473. */
  40474. this.isInstancedInterleavedBuffer = true;
  40475. /**
  40476. * Defines how often a value of this buffer attribute should be repeated,
  40477. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  40478. *
  40479. * @type {number}
  40480. * @default 1
  40481. */
  40482. this.meshPerAttribute = meshPerAttribute;
  40483. }
  40484. copy( source ) {
  40485. super.copy( source );
  40486. this.meshPerAttribute = source.meshPerAttribute;
  40487. return this;
  40488. }
  40489. clone( data ) {
  40490. const ib = super.clone( data );
  40491. ib.meshPerAttribute = this.meshPerAttribute;
  40492. return ib;
  40493. }
  40494. toJSON( data ) {
  40495. const json = super.toJSON( data );
  40496. json.isInstancedInterleavedBuffer = true;
  40497. json.meshPerAttribute = this.meshPerAttribute;
  40498. return json;
  40499. }
  40500. }
  40501. /**
  40502. * An alternative version of a buffer attribute with more control over the VBO.
  40503. *
  40504. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  40505. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  40506. *
  40507. * The most common use case for this class is when some kind of GPGPU calculation interferes
  40508. * or even produces the VBOs in question.
  40509. *
  40510. * Notice that this class can only be used with {@link WebGLRenderer}.
  40511. */
  40512. class GLBufferAttribute {
  40513. /**
  40514. * Constructs a new GL buffer attribute.
  40515. *
  40516. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  40517. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40518. * @param {number} itemSize - The item size.
  40519. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40520. * @param {number} count - The expected number of vertices in VBO.
  40521. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  40522. */
  40523. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  40524. /**
  40525. * This flag can be used for type testing.
  40526. *
  40527. * @type {boolean}
  40528. * @readonly
  40529. * @default true
  40530. */
  40531. this.isGLBufferAttribute = true;
  40532. /**
  40533. * The name of the buffer attribute.
  40534. *
  40535. * @type {string}
  40536. */
  40537. this.name = '';
  40538. /**
  40539. * The native WebGL buffer.
  40540. *
  40541. * @type {WebGLBuffer}
  40542. */
  40543. this.buffer = buffer;
  40544. /**
  40545. * The native data type.
  40546. *
  40547. * @type {number}
  40548. */
  40549. this.type = type;
  40550. /**
  40551. * The item size, see {@link BufferAttribute#itemSize}.
  40552. *
  40553. * @type {number}
  40554. */
  40555. this.itemSize = itemSize;
  40556. /**
  40557. * The corresponding size (in bytes) for the given `type` parameter.
  40558. *
  40559. * @type {number}
  40560. */
  40561. this.elementSize = elementSize;
  40562. /**
  40563. * The expected number of vertices in VBO.
  40564. *
  40565. * @type {number}
  40566. */
  40567. this.count = count;
  40568. /**
  40569. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  40570. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  40571. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  40572. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  40573. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  40574. *
  40575. * @type {boolean}
  40576. */
  40577. this.normalized = normalized;
  40578. /**
  40579. * A version number, incremented every time the `needsUpdate` is set to `true`.
  40580. *
  40581. * @type {number}
  40582. */
  40583. this.version = 0;
  40584. }
  40585. /**
  40586. * Flag to indicate that this attribute has changed and should be re-sent to
  40587. * the GPU. Set this to `true` when you modify the value of the array.
  40588. *
  40589. * @type {number}
  40590. * @default false
  40591. * @param {boolean} value
  40592. */
  40593. set needsUpdate( value ) {
  40594. if ( value === true ) this.version ++;
  40595. }
  40596. /**
  40597. * Sets the given native WebGL buffer.
  40598. *
  40599. * @param {WebGLBuffer} buffer - The buffer to set.
  40600. * @return {BufferAttribute} A reference to this instance.
  40601. */
  40602. setBuffer( buffer ) {
  40603. this.buffer = buffer;
  40604. return this;
  40605. }
  40606. /**
  40607. * Sets the given native data type and element size.
  40608. *
  40609. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40610. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40611. * @return {BufferAttribute} A reference to this instance.
  40612. */
  40613. setType( type, elementSize ) {
  40614. this.type = type;
  40615. this.elementSize = elementSize;
  40616. return this;
  40617. }
  40618. /**
  40619. * Sets the item size.
  40620. *
  40621. * @param {number} itemSize - The item size.
  40622. * @return {BufferAttribute} A reference to this instance.
  40623. */
  40624. setItemSize( itemSize ) {
  40625. this.itemSize = itemSize;
  40626. return this;
  40627. }
  40628. /**
  40629. * Sets the count (the expected number of vertices in VBO).
  40630. *
  40631. * @param {number} count - The count.
  40632. * @return {BufferAttribute} A reference to this instance.
  40633. */
  40634. setCount( count ) {
  40635. this.count = count;
  40636. return this;
  40637. }
  40638. }
  40639. const _matrix = /*@__PURE__*/ new Matrix4();
  40640. /**
  40641. * This class is designed to assist with raycasting. Raycasting is used for
  40642. * mouse picking (working out what objects in the 3d space the mouse is over)
  40643. * amongst other things.
  40644. */
  40645. class Raycaster {
  40646. /**
  40647. * Constructs a new raycaster.
  40648. *
  40649. * @param {Vector3} origin - The origin vector where the ray casts from.
  40650. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40651. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40652. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40653. */
  40654. constructor( origin, direction, near = 0, far = Infinity ) {
  40655. /**
  40656. * The ray used for raycasting.
  40657. *
  40658. * @type {Ray}
  40659. */
  40660. this.ray = new Ray( origin, direction );
  40661. /**
  40662. * All results returned are further away than near. Near can't be negative.
  40663. *
  40664. * @type {number}
  40665. * @default 0
  40666. */
  40667. this.near = near;
  40668. /**
  40669. * All results returned are closer than far. Far can't be lower than near.
  40670. *
  40671. * @type {number}
  40672. * @default Infinity
  40673. */
  40674. this.far = far;
  40675. /**
  40676. * The camera to use when raycasting against view-dependent objects such as
  40677. * billboarded objects like sprites. This field can be set manually or
  40678. * is set when calling `setFromCamera()`.
  40679. *
  40680. * @type {?Camera}
  40681. * @default null
  40682. */
  40683. this.camera = null;
  40684. /**
  40685. * Allows to selectively ignore 3D objects when performing intersection tests.
  40686. * The following code example ensures that only 3D objects on layer `1` will be
  40687. * honored by raycaster.
  40688. * ```js
  40689. * raycaster.layers.set( 1 );
  40690. * object.layers.enable( 1 );
  40691. * ```
  40692. *
  40693. * @type {Layers}
  40694. */
  40695. this.layers = new Layers();
  40696. /**
  40697. * A parameter object that configures the raycasting. It has the structure:
  40698. *
  40699. * ```
  40700. * {
  40701. * Mesh: {},
  40702. * Line: { threshold: 1 },
  40703. * LOD: {},
  40704. * Points: { threshold: 1 },
  40705. * Sprite: {}
  40706. * }
  40707. * ```
  40708. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40709. *
  40710. * @type {Object}
  40711. */
  40712. this.params = {
  40713. Mesh: {},
  40714. Line: { threshold: 1 },
  40715. LOD: {},
  40716. Points: { threshold: 1 },
  40717. Sprite: {}
  40718. };
  40719. }
  40720. /**
  40721. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40722. *
  40723. * @param {Vector3} origin - The origin vector where the ray casts from.
  40724. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40725. */
  40726. set( origin, direction ) {
  40727. // direction is assumed to be normalized (for accurate distance calculations)
  40728. this.ray.set( origin, direction );
  40729. }
  40730. /**
  40731. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40732. *
  40733. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40734. * X and Y components should be between `-1` and `1`.
  40735. * @param {Camera} camera - The camera from which the ray should originate.
  40736. */
  40737. setFromCamera( coords, camera ) {
  40738. if ( camera.isPerspectiveCamera ) {
  40739. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40740. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40741. this.camera = camera;
  40742. } else if ( camera.isOrthographicCamera ) {
  40743. this.ray.origin.set( coords.x, coords.y, camera.projectionMatrix.elements[ 14 ] ).unproject( camera ); // set origin in plane of camera
  40744. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40745. this.camera = camera;
  40746. } else {
  40747. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40748. }
  40749. }
  40750. /**
  40751. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40752. *
  40753. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40754. * @return {Raycaster} A reference to this raycaster.
  40755. */
  40756. setFromXRController( controller ) {
  40757. _matrix.identity().extractRotation( controller.matrixWorld );
  40758. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40759. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40760. return this;
  40761. }
  40762. /**
  40763. * The intersection point of a raycaster intersection test.
  40764. * @typedef {Object} Raycaster~Intersection
  40765. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40766. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40767. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40768. * @property {Vector3} point - The intersection point, in world coordinates.
  40769. * @property {Object} face - The face that has been intersected.
  40770. * @property {number} faceIndex - The face index.
  40771. * @property {Object3D} object - The 3D object that has been intersected.
  40772. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40773. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40774. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40775. * @property {number} instanceId - The index number of the instance where the ray
  40776. * intersects the {@link InstancedMesh}.
  40777. */
  40778. /**
  40779. * Checks all intersection between the ray and the object with or without the
  40780. * descendants. Intersections are returned sorted by distance, closest first.
  40781. *
  40782. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40783. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40784. * differently to ray casting than lines or points.
  40785. *
  40786. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40787. * to be detected; intersections of the ray passing through the back of a face will not
  40788. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40789. * to `THREE.DoubleSide`.
  40790. *
  40791. * Note that a ray hitting a triangle mesh exactly along an edge shared by two faces may be
  40792. * reported by both faces, resulting in two coincident intersections (identical point and
  40793. * distance) in the returned array.
  40794. *
  40795. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40796. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40797. * Otherwise it only checks intersection with the object.
  40798. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40799. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40800. */
  40801. intersectObject( object, recursive = true, intersects = [] ) {
  40802. intersect( object, this, intersects, recursive );
  40803. intersects.sort( ascSort );
  40804. return intersects;
  40805. }
  40806. /**
  40807. * Checks all intersection between the ray and the objects with or without
  40808. * the descendants. Intersections are returned sorted by distance, closest first.
  40809. *
  40810. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40811. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40812. * Otherwise it only checks intersection with the object.
  40813. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40814. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40815. */
  40816. intersectObjects( objects, recursive = true, intersects = [] ) {
  40817. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40818. intersect( objects[ i ], this, intersects, recursive );
  40819. }
  40820. intersects.sort( ascSort );
  40821. return intersects;
  40822. }
  40823. }
  40824. function ascSort( a, b ) {
  40825. return a.distance - b.distance;
  40826. }
  40827. function intersect( object, raycaster, intersects, recursive ) {
  40828. let propagate = true;
  40829. if ( object.layers.test( raycaster.layers ) ) {
  40830. const result = object.raycast( raycaster, intersects );
  40831. if ( result === false ) propagate = false;
  40832. }
  40833. if ( propagate === true && recursive === true ) {
  40834. const children = object.children;
  40835. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40836. intersect( children[ i ], raycaster, intersects, true );
  40837. }
  40838. }
  40839. }
  40840. /**
  40841. * Class for keeping track of time.
  40842. *
  40843. * @deprecated since r183.
  40844. */
  40845. class Clock {
  40846. /**
  40847. * Constructs a new clock.
  40848. *
  40849. * @deprecated since 183.
  40850. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  40851. * `getDelta()` is called for the first time.
  40852. */
  40853. constructor( autoStart = true ) {
  40854. /**
  40855. * If set to `true`, the clock starts automatically when `getDelta()` is called
  40856. * for the first time.
  40857. *
  40858. * @type {boolean}
  40859. * @default true
  40860. */
  40861. this.autoStart = autoStart;
  40862. /**
  40863. * Holds the time at which the clock's `start()` method was last called.
  40864. *
  40865. * @type {number}
  40866. * @default 0
  40867. */
  40868. this.startTime = 0;
  40869. /**
  40870. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  40871. * `getDelta()` methods were last called.
  40872. *
  40873. * @type {number}
  40874. * @default 0
  40875. */
  40876. this.oldTime = 0;
  40877. /**
  40878. * Keeps track of the total time that the clock has been running.
  40879. *
  40880. * @type {number}
  40881. * @default 0
  40882. */
  40883. this.elapsedTime = 0;
  40884. /**
  40885. * Whether the clock is running or not.
  40886. *
  40887. * @type {boolean}
  40888. * @default true
  40889. */
  40890. this.running = false;
  40891. warn( 'Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183
  40892. }
  40893. /**
  40894. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  40895. * called by the class.
  40896. */
  40897. start() {
  40898. this.startTime = performance.now();
  40899. this.oldTime = this.startTime;
  40900. this.elapsedTime = 0;
  40901. this.running = true;
  40902. }
  40903. /**
  40904. * Stops the clock.
  40905. */
  40906. stop() {
  40907. this.getElapsedTime();
  40908. this.running = false;
  40909. this.autoStart = false;
  40910. }
  40911. /**
  40912. * Returns the elapsed time in seconds.
  40913. *
  40914. * @return {number} The elapsed time.
  40915. */
  40916. getElapsedTime() {
  40917. this.getDelta();
  40918. return this.elapsedTime;
  40919. }
  40920. /**
  40921. * Returns the delta time in seconds.
  40922. *
  40923. * @return {number} The delta time.
  40924. */
  40925. getDelta() {
  40926. let diff = 0;
  40927. if ( this.autoStart && ! this.running ) {
  40928. this.start();
  40929. return 0;
  40930. }
  40931. if ( this.running ) {
  40932. const newTime = performance.now();
  40933. diff = ( newTime - this.oldTime ) / 1000;
  40934. this.oldTime = newTime;
  40935. this.elapsedTime += diff;
  40936. }
  40937. return diff;
  40938. }
  40939. }
  40940. /**
  40941. * This class can be used to represent points in 3D space as
  40942. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40943. */
  40944. class Spherical {
  40945. /**
  40946. * Constructs a new spherical.
  40947. *
  40948. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40949. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40950. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40951. */
  40952. constructor( radius = 1, phi = 0, theta = 0 ) {
  40953. /**
  40954. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40955. *
  40956. * @type {number}
  40957. * @default 1
  40958. */
  40959. this.radius = radius;
  40960. /**
  40961. * The polar angle in radians from the y (up) axis.
  40962. *
  40963. * @type {number}
  40964. * @default 0
  40965. */
  40966. this.phi = phi;
  40967. /**
  40968. * The equator/azimuthal angle in radians around the y (up) axis.
  40969. *
  40970. * @type {number}
  40971. * @default 0
  40972. */
  40973. this.theta = theta;
  40974. }
  40975. /**
  40976. * Sets the spherical components by copying the given values.
  40977. *
  40978. * @param {number} radius - The radius.
  40979. * @param {number} phi - The polar angle.
  40980. * @param {number} theta - The azimuthal angle.
  40981. * @return {Spherical} A reference to this spherical.
  40982. */
  40983. set( radius, phi, theta ) {
  40984. this.radius = radius;
  40985. this.phi = phi;
  40986. this.theta = theta;
  40987. return this;
  40988. }
  40989. /**
  40990. * Copies the values of the given spherical to this instance.
  40991. *
  40992. * @param {Spherical} other - The spherical to copy.
  40993. * @return {Spherical} A reference to this spherical.
  40994. */
  40995. copy( other ) {
  40996. this.radius = other.radius;
  40997. this.phi = other.phi;
  40998. this.theta = other.theta;
  40999. return this;
  41000. }
  41001. /**
  41002. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  41003. * `0.000001`.
  41004. *
  41005. * @return {Spherical} A reference to this spherical.
  41006. */
  41007. makeSafe() {
  41008. const EPS = 0.000001;
  41009. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  41010. return this;
  41011. }
  41012. /**
  41013. * Sets the spherical components from the given vector which is assumed to hold
  41014. * Cartesian coordinates.
  41015. *
  41016. * @param {Vector3} v - The vector to set.
  41017. * @return {Spherical} A reference to this spherical.
  41018. */
  41019. setFromVector3( v ) {
  41020. return this.setFromCartesianCoords( v.x, v.y, v.z );
  41021. }
  41022. /**
  41023. * Sets the spherical components from the given Cartesian coordinates.
  41024. *
  41025. * @param {number} x - The x value.
  41026. * @param {number} y - The y value.
  41027. * @param {number} z - The z value.
  41028. * @return {Spherical} A reference to this spherical.
  41029. */
  41030. setFromCartesianCoords( x, y, z ) {
  41031. this.radius = Math.sqrt( x * x + y * y + z * z );
  41032. if ( this.radius === 0 ) {
  41033. this.theta = 0;
  41034. this.phi = 0;
  41035. } else {
  41036. this.theta = Math.atan2( x, z );
  41037. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  41038. }
  41039. return this;
  41040. }
  41041. /**
  41042. * Returns a new spherical with copied values from this instance.
  41043. *
  41044. * @return {Spherical} A clone of this instance.
  41045. */
  41046. clone() {
  41047. return new this.constructor().copy( this );
  41048. }
  41049. }
  41050. /**
  41051. * This class can be used to represent points in 3D space as
  41052. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  41053. */
  41054. class Cylindrical {
  41055. /**
  41056. * Constructs a new cylindrical.
  41057. *
  41058. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  41059. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  41060. * @param {number} [y=0] - The height above the x-z plane.
  41061. */
  41062. constructor( radius = 1, theta = 0, y = 0 ) {
  41063. /**
  41064. * The distance from the origin to a point in the x-z plane.
  41065. *
  41066. * @type {number}
  41067. * @default 1
  41068. */
  41069. this.radius = radius;
  41070. /**
  41071. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  41072. *
  41073. * @type {number}
  41074. * @default 0
  41075. */
  41076. this.theta = theta;
  41077. /**
  41078. * The height above the x-z plane.
  41079. *
  41080. * @type {number}
  41081. * @default 0
  41082. */
  41083. this.y = y;
  41084. }
  41085. /**
  41086. * Sets the cylindrical components by copying the given values.
  41087. *
  41088. * @param {number} radius - The radius.
  41089. * @param {number} theta - The theta angle.
  41090. * @param {number} y - The height value.
  41091. * @return {Cylindrical} A reference to this cylindrical.
  41092. */
  41093. set( radius, theta, y ) {
  41094. this.radius = radius;
  41095. this.theta = theta;
  41096. this.y = y;
  41097. return this;
  41098. }
  41099. /**
  41100. * Copies the values of the given cylindrical to this instance.
  41101. *
  41102. * @param {Cylindrical} other - The cylindrical to copy.
  41103. * @return {Cylindrical} A reference to this cylindrical.
  41104. */
  41105. copy( other ) {
  41106. this.radius = other.radius;
  41107. this.theta = other.theta;
  41108. this.y = other.y;
  41109. return this;
  41110. }
  41111. /**
  41112. * Sets the cylindrical components from the given vector which is assumed to hold
  41113. * Cartesian coordinates.
  41114. *
  41115. * @param {Vector3} v - The vector to set.
  41116. * @return {Cylindrical} A reference to this cylindrical.
  41117. */
  41118. setFromVector3( v ) {
  41119. return this.setFromCartesianCoords( v.x, v.y, v.z );
  41120. }
  41121. /**
  41122. * Sets the cylindrical components from the given Cartesian coordinates.
  41123. *
  41124. * @param {number} x - The x value.
  41125. * @param {number} y - The x value.
  41126. * @param {number} z - The x value.
  41127. * @return {Cylindrical} A reference to this cylindrical.
  41128. */
  41129. setFromCartesianCoords( x, y, z ) {
  41130. this.radius = Math.sqrt( x * x + z * z );
  41131. this.theta = Math.atan2( x, z );
  41132. this.y = y;
  41133. return this;
  41134. }
  41135. /**
  41136. * Returns a new cylindrical with copied values from this instance.
  41137. *
  41138. * @return {Cylindrical} A clone of this instance.
  41139. */
  41140. clone() {
  41141. return new this.constructor().copy( this );
  41142. }
  41143. }
  41144. /**
  41145. * Represents a 2x2 matrix.
  41146. *
  41147. * A Note on Row-Major and Column-Major Ordering:
  41148. *
  41149. * The constructor and {@link Matrix2#set} method take arguments in
  41150. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  41151. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  41152. * This means that calling:
  41153. * ```js
  41154. * const m = new THREE.Matrix2();
  41155. * m.set( 11, 12,
  41156. * 21, 22 );
  41157. * ```
  41158. * will result in the elements array containing:
  41159. * ```js
  41160. * m.elements = [ 11, 21,
  41161. * 12, 22 ];
  41162. * ```
  41163. * and internally all calculations are performed using column-major ordering.
  41164. * However, as the actual ordering makes no difference mathematically and
  41165. * most people are used to thinking about matrices in row-major order, the
  41166. * three.js documentation shows matrices in row-major order. Just bear in
  41167. * mind that if you are reading the source code, you'll have to take the
  41168. * transpose of any matrices outlined here to make sense of the calculations.
  41169. */
  41170. class Matrix2 {
  41171. static {
  41172. /**
  41173. * This flag can be used for type testing.
  41174. *
  41175. * @type {boolean}
  41176. * @readonly
  41177. * @default true
  41178. */
  41179. Matrix2.prototype.isMatrix2 = true;
  41180. }
  41181. /**
  41182. * Constructs a new 2x2 matrix. The arguments are supposed to be
  41183. * in row-major order. If no arguments are provided, the constructor
  41184. * initializes the matrix as an identity matrix.
  41185. *
  41186. * @param {number} [n11] - 1-1 matrix element.
  41187. * @param {number} [n12] - 1-2 matrix element.
  41188. * @param {number} [n21] - 2-1 matrix element.
  41189. * @param {number} [n22] - 2-2 matrix element.
  41190. */
  41191. constructor( n11, n12, n21, n22 ) {
  41192. /**
  41193. * A column-major list of matrix values.
  41194. *
  41195. * @type {Array<number>}
  41196. */
  41197. this.elements = [
  41198. 1, 0,
  41199. 0, 1,
  41200. ];
  41201. if ( n11 !== undefined ) {
  41202. this.set( n11, n12, n21, n22 );
  41203. }
  41204. }
  41205. /**
  41206. * Sets this matrix to the 2x2 identity matrix.
  41207. *
  41208. * @return {Matrix2} A reference to this matrix.
  41209. */
  41210. identity() {
  41211. this.set(
  41212. 1, 0,
  41213. 0, 1,
  41214. );
  41215. return this;
  41216. }
  41217. /**
  41218. * Sets the elements of the matrix from the given array.
  41219. *
  41220. * @param {Array<number>} array - The matrix elements in column-major order.
  41221. * @param {number} [offset=0] - Index of the first element in the array.
  41222. * @return {Matrix2} A reference to this matrix.
  41223. */
  41224. fromArray( array, offset = 0 ) {
  41225. for ( let i = 0; i < 4; i ++ ) {
  41226. this.elements[ i ] = array[ i + offset ];
  41227. }
  41228. return this;
  41229. }
  41230. /**
  41231. * Sets the elements of the matrix.The arguments are supposed to be
  41232. * in row-major order.
  41233. *
  41234. * @param {number} n11 - 1-1 matrix element.
  41235. * @param {number} n12 - 1-2 matrix element.
  41236. * @param {number} n21 - 2-1 matrix element.
  41237. * @param {number} n22 - 2-2 matrix element.
  41238. * @return {Matrix2} A reference to this matrix.
  41239. */
  41240. set( n11, n12, n21, n22 ) {
  41241. const te = this.elements;
  41242. te[ 0 ] = n11; te[ 2 ] = n12;
  41243. te[ 1 ] = n21; te[ 3 ] = n22;
  41244. return this;
  41245. }
  41246. }
  41247. const _vector$4 = /*@__PURE__*/ new Vector2();
  41248. /**
  41249. * Represents an axis-aligned bounding box (AABB) in 2D space.
  41250. */
  41251. class Box2 {
  41252. /**
  41253. * Constructs a new bounding box.
  41254. *
  41255. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  41256. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  41257. */
  41258. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  41259. /**
  41260. * This flag can be used for type testing.
  41261. *
  41262. * @type {boolean}
  41263. * @readonly
  41264. * @default true
  41265. */
  41266. this.isBox2 = true;
  41267. /**
  41268. * The lower boundary of the box.
  41269. *
  41270. * @type {Vector2}
  41271. */
  41272. this.min = min;
  41273. /**
  41274. * The upper boundary of the box.
  41275. *
  41276. * @type {Vector2}
  41277. */
  41278. this.max = max;
  41279. }
  41280. /**
  41281. * Sets the lower and upper boundaries of this box.
  41282. * Please note that this method only copies the values from the given objects.
  41283. *
  41284. * @param {Vector2} min - The lower boundary of the box.
  41285. * @param {Vector2} max - The upper boundary of the box.
  41286. * @return {Box2} A reference to this bounding box.
  41287. */
  41288. set( min, max ) {
  41289. this.min.copy( min );
  41290. this.max.copy( max );
  41291. return this;
  41292. }
  41293. /**
  41294. * Sets the upper and lower bounds of this box so it encloses the position data
  41295. * in the given array.
  41296. *
  41297. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  41298. * @return {Box2} A reference to this bounding box.
  41299. */
  41300. setFromPoints( points ) {
  41301. this.makeEmpty();
  41302. for ( let i = 0, il = points.length; i < il; i ++ ) {
  41303. this.expandByPoint( points[ i ] );
  41304. }
  41305. return this;
  41306. }
  41307. /**
  41308. * Centers this box on the given center vector and sets this box's width, height and
  41309. * depth to the given size values.
  41310. *
  41311. * @param {Vector2} center - The center of the box.
  41312. * @param {Vector2} size - The x and y dimensions of the box.
  41313. * @return {Box2} A reference to this bounding box.
  41314. */
  41315. setFromCenterAndSize( center, size ) {
  41316. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  41317. this.min.copy( center ).sub( halfSize );
  41318. this.max.copy( center ).add( halfSize );
  41319. return this;
  41320. }
  41321. /**
  41322. * Returns a new box with copied values from this instance.
  41323. *
  41324. * @return {Box2} A clone of this instance.
  41325. */
  41326. clone() {
  41327. return new this.constructor().copy( this );
  41328. }
  41329. /**
  41330. * Copies the values of the given box to this instance.
  41331. *
  41332. * @param {Box2} box - The box to copy.
  41333. * @return {Box2} A reference to this bounding box.
  41334. */
  41335. copy( box ) {
  41336. this.min.copy( box.min );
  41337. this.max.copy( box.max );
  41338. return this;
  41339. }
  41340. /**
  41341. * Makes this box empty which means in encloses a zero space in 2D.
  41342. *
  41343. * @return {Box2} A reference to this bounding box.
  41344. */
  41345. makeEmpty() {
  41346. this.min.x = this.min.y = + Infinity;
  41347. this.max.x = this.max.y = - Infinity;
  41348. return this;
  41349. }
  41350. /**
  41351. * Returns true if this box includes zero points within its bounds.
  41352. * Note that a box with equal lower and upper bounds still includes one
  41353. * point, the one both bounds share.
  41354. *
  41355. * @return {boolean} Whether this box is empty or not.
  41356. */
  41357. isEmpty() {
  41358. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  41359. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  41360. }
  41361. /**
  41362. * Returns the center point of this box.
  41363. *
  41364. * @param {Vector2} target - The target vector that is used to store the method's result.
  41365. * @return {Vector2} The center point.
  41366. */
  41367. getCenter( target ) {
  41368. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  41369. }
  41370. /**
  41371. * Returns the dimensions of this box.
  41372. *
  41373. * @param {Vector2} target - The target vector that is used to store the method's result.
  41374. * @return {Vector2} The size.
  41375. */
  41376. getSize( target ) {
  41377. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  41378. }
  41379. /**
  41380. * Expands the boundaries of this box to include the given point.
  41381. *
  41382. * @param {Vector2} point - The point that should be included by the bounding box.
  41383. * @return {Box2} A reference to this bounding box.
  41384. */
  41385. expandByPoint( point ) {
  41386. this.min.min( point );
  41387. this.max.max( point );
  41388. return this;
  41389. }
  41390. /**
  41391. * Expands this box equilaterally by the given vector. The width of this
  41392. * box will be expanded by the x component of the vector in both
  41393. * directions. The height of this box will be expanded by the y component of
  41394. * the vector in both directions.
  41395. *
  41396. * @param {Vector2} vector - The vector that should expand the bounding box.
  41397. * @return {Box2} A reference to this bounding box.
  41398. */
  41399. expandByVector( vector ) {
  41400. this.min.sub( vector );
  41401. this.max.add( vector );
  41402. return this;
  41403. }
  41404. /**
  41405. * Expands each dimension of the box by the given scalar. If negative, the
  41406. * dimensions of the box will be contracted.
  41407. *
  41408. * @param {number} scalar - The scalar value that should expand the bounding box.
  41409. * @return {Box2} A reference to this bounding box.
  41410. */
  41411. expandByScalar( scalar ) {
  41412. this.min.addScalar( - scalar );
  41413. this.max.addScalar( scalar );
  41414. return this;
  41415. }
  41416. /**
  41417. * Returns `true` if the given point lies within or on the boundaries of this box.
  41418. *
  41419. * @param {Vector2} point - The point to test.
  41420. * @return {boolean} Whether the bounding box contains the given point or not.
  41421. */
  41422. containsPoint( point ) {
  41423. return point.x >= this.min.x && point.x <= this.max.x &&
  41424. point.y >= this.min.y && point.y <= this.max.y;
  41425. }
  41426. /**
  41427. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  41428. * If this box and the given one are identical, this function also returns `true`.
  41429. *
  41430. * @param {Box2} box - The bounding box to test.
  41431. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  41432. */
  41433. containsBox( box ) {
  41434. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  41435. this.min.y <= box.min.y && box.max.y <= this.max.y;
  41436. }
  41437. /**
  41438. * Returns a point as a proportion of this box's width and height.
  41439. *
  41440. * @param {Vector2} point - A point in 2D space.
  41441. * @param {Vector2} target - The target vector that is used to store the method's result.
  41442. * @return {Vector2} A point as a proportion of this box's width and height.
  41443. */
  41444. getParameter( point, target ) {
  41445. // This can potentially have a divide by zero if the box
  41446. // has a size dimension of 0.
  41447. return target.set(
  41448. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  41449. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  41450. );
  41451. }
  41452. /**
  41453. * Returns `true` if the given bounding box intersects with this bounding box.
  41454. *
  41455. * @param {Box2} box - The bounding box to test.
  41456. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  41457. */
  41458. intersectsBox( box ) {
  41459. // using 4 splitting planes to rule out intersections
  41460. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  41461. box.max.y >= this.min.y && box.min.y <= this.max.y;
  41462. }
  41463. /**
  41464. * Clamps the given point within the bounds of this box.
  41465. *
  41466. * @param {Vector2} point - The point to clamp.
  41467. * @param {Vector2} target - The target vector that is used to store the method's result.
  41468. * @return {Vector2} The clamped point.
  41469. */
  41470. clampPoint( point, target ) {
  41471. return target.copy( point ).clamp( this.min, this.max );
  41472. }
  41473. /**
  41474. * Returns the euclidean distance from any edge of this box to the specified point. If
  41475. * the given point lies inside of this box, the distance will be `0`.
  41476. *
  41477. * @param {Vector2} point - The point to compute the distance to.
  41478. * @return {number} The euclidean distance.
  41479. */
  41480. distanceToPoint( point ) {
  41481. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  41482. }
  41483. /**
  41484. * Computes the intersection of this bounding box and the given one, setting the upper
  41485. * bound of this box to the lesser of the two boxes' upper bounds and the
  41486. * lower bound of this box to the greater of the two boxes' lower bounds. If
  41487. * there's no overlap, makes this box empty.
  41488. *
  41489. * @param {Box2} box - The bounding box to intersect with.
  41490. * @return {Box2} A reference to this bounding box.
  41491. */
  41492. intersect( box ) {
  41493. this.min.max( box.min );
  41494. this.max.min( box.max );
  41495. if ( this.isEmpty() ) this.makeEmpty();
  41496. return this;
  41497. }
  41498. /**
  41499. * Computes the union of this box and another and the given one, setting the upper
  41500. * bound of this box to the greater of the two boxes' upper bounds and the
  41501. * lower bound of this box to the lesser of the two boxes' lower bounds.
  41502. *
  41503. * @param {Box2} box - The bounding box that will be unioned with this instance.
  41504. * @return {Box2} A reference to this bounding box.
  41505. */
  41506. union( box ) {
  41507. this.min.min( box.min );
  41508. this.max.max( box.max );
  41509. return this;
  41510. }
  41511. /**
  41512. * Adds the given offset to both the upper and lower bounds of this bounding box,
  41513. * effectively moving it in 2D space.
  41514. *
  41515. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  41516. * @return {Box2} A reference to this bounding box.
  41517. */
  41518. translate( offset ) {
  41519. this.min.add( offset );
  41520. this.max.add( offset );
  41521. return this;
  41522. }
  41523. /**
  41524. * Returns `true` if this bounding box is equal with the given one.
  41525. *
  41526. * @param {Box2} box - The box to test for equality.
  41527. * @return {boolean} Whether this bounding box is equal with the given one.
  41528. */
  41529. equals( box ) {
  41530. return box.min.equals( this.min ) && box.max.equals( this.max );
  41531. }
  41532. }
  41533. const _startP = /*@__PURE__*/ new Vector3();
  41534. const _startEnd = /*@__PURE__*/ new Vector3();
  41535. const _d1 = /*@__PURE__*/ new Vector3();
  41536. const _d2 = /*@__PURE__*/ new Vector3();
  41537. const _r = /*@__PURE__*/ new Vector3();
  41538. const _c1 = /*@__PURE__*/ new Vector3();
  41539. const _c2 = /*@__PURE__*/ new Vector3();
  41540. /**
  41541. * An analytical line segment in 3D space represented by a start and end point.
  41542. */
  41543. class Line3 {
  41544. /**
  41545. * Constructs a new line segment.
  41546. *
  41547. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  41548. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  41549. */
  41550. constructor( start = new Vector3(), end = new Vector3() ) {
  41551. /**
  41552. * Start of the line segment.
  41553. *
  41554. * @type {Vector3}
  41555. */
  41556. this.start = start;
  41557. /**
  41558. * End of the line segment.
  41559. *
  41560. * @type {Vector3}
  41561. */
  41562. this.end = end;
  41563. }
  41564. /**
  41565. * Sets the start and end values by copying the given vectors.
  41566. *
  41567. * @param {Vector3} start - The start point.
  41568. * @param {Vector3} end - The end point.
  41569. * @return {Line3} A reference to this line segment.
  41570. */
  41571. set( start, end ) {
  41572. this.start.copy( start );
  41573. this.end.copy( end );
  41574. return this;
  41575. }
  41576. /**
  41577. * Copies the values of the given line segment to this instance.
  41578. *
  41579. * @param {Line3} line - The line segment to copy.
  41580. * @return {Line3} A reference to this line segment.
  41581. */
  41582. copy( line ) {
  41583. this.start.copy( line.start );
  41584. this.end.copy( line.end );
  41585. return this;
  41586. }
  41587. /**
  41588. * Returns the center of the line segment.
  41589. *
  41590. * @param {Vector3} target - The target vector that is used to store the method's result.
  41591. * @return {Vector3} The center point.
  41592. */
  41593. getCenter( target ) {
  41594. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  41595. }
  41596. /**
  41597. * Returns the delta vector of the line segment's start and end point.
  41598. *
  41599. * @param {Vector3} target - The target vector that is used to store the method's result.
  41600. * @return {Vector3} The delta vector.
  41601. */
  41602. delta( target ) {
  41603. return target.subVectors( this.end, this.start );
  41604. }
  41605. /**
  41606. * Returns the squared Euclidean distance between the line' start and end point.
  41607. *
  41608. * @return {number} The squared Euclidean distance.
  41609. */
  41610. distanceSq() {
  41611. return this.start.distanceToSquared( this.end );
  41612. }
  41613. /**
  41614. * Returns the Euclidean distance between the line' start and end point.
  41615. *
  41616. * @return {number} The Euclidean distance.
  41617. */
  41618. distance() {
  41619. return this.start.distanceTo( this.end );
  41620. }
  41621. /**
  41622. * Returns a vector at a certain position along the line segment.
  41623. *
  41624. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41625. * @param {Vector3} target - The target vector that is used to store the method's result.
  41626. * @return {Vector3} The delta vector.
  41627. */
  41628. at( t, target ) {
  41629. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41630. }
  41631. /**
  41632. * Returns a point parameter based on the closest point as projected on the line segment.
  41633. *
  41634. * @param {Vector3} point - The point for which to return a point parameter.
  41635. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41636. * @return {number} The point parameter.
  41637. */
  41638. closestPointToPointParameter( point, clampToLine ) {
  41639. _startP.subVectors( point, this.start );
  41640. _startEnd.subVectors( this.end, this.start );
  41641. const startEnd2 = _startEnd.dot( _startEnd );
  41642. if ( startEnd2 === 0 ) return 0;
  41643. const startEnd_startP = _startEnd.dot( _startP );
  41644. let t = startEnd_startP / startEnd2;
  41645. if ( clampToLine ) {
  41646. t = clamp( t, 0, 1 );
  41647. }
  41648. return t;
  41649. }
  41650. /**
  41651. * Returns the closest point on the line for a given point.
  41652. *
  41653. * @param {Vector3} point - The point to compute the closest point on the line for.
  41654. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41655. * @param {Vector3} target - The target vector that is used to store the method's result.
  41656. * @return {Vector3} The closest point on the line.
  41657. */
  41658. closestPointToPoint( point, clampToLine, target ) {
  41659. const t = this.closestPointToPointParameter( point, clampToLine );
  41660. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41661. }
  41662. /**
  41663. * Returns the closest squared distance between this line segment and the given one.
  41664. *
  41665. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41666. * @param {Vector3} [c1] - The closest point on this line segment.
  41667. * @param {Vector3} [c2] - The closest point on the given line segment.
  41668. * @return {number} The squared distance between this line segment and the given one.
  41669. */
  41670. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41671. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41672. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41673. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41674. // distance between between S1(s) and S2(t)
  41675. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41676. let s, t;
  41677. const p1 = this.start;
  41678. const p2 = line.start;
  41679. const q1 = this.end;
  41680. const q2 = line.end;
  41681. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41682. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41683. _r.subVectors( p1, p2 );
  41684. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41685. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41686. const f = _d2.dot( _r );
  41687. // Check if either or both segments degenerate into points
  41688. if ( a <= EPSILON && e <= EPSILON ) {
  41689. // Both segments degenerate into points
  41690. c1.copy( p1 );
  41691. c2.copy( p2 );
  41692. c1.sub( c2 );
  41693. return c1.dot( c1 );
  41694. }
  41695. if ( a <= EPSILON ) {
  41696. // First segment degenerates into a point
  41697. s = 0;
  41698. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41699. t = clamp( t, 0, 1 );
  41700. } else {
  41701. const c = _d1.dot( _r );
  41702. if ( e <= EPSILON ) {
  41703. // Second segment degenerates into a point
  41704. t = 0;
  41705. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41706. } else {
  41707. // The general nondegenerate case starts here
  41708. const b = _d1.dot( _d2 );
  41709. const denom = a * e - b * b; // Always nonnegative
  41710. // If segments not parallel, compute closest point on L1 to L2 and
  41711. // clamp to segment S1. Else pick arbitrary s (here 0)
  41712. if ( denom !== 0 ) {
  41713. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41714. } else {
  41715. s = 0;
  41716. }
  41717. // Compute point on L2 closest to S1(s) using
  41718. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41719. t = ( b * s + f ) / e;
  41720. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41721. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41722. // and clamp s to [0, 1]
  41723. if ( t < 0 ) {
  41724. t = 0.;
  41725. s = clamp( - c / a, 0, 1 );
  41726. } else if ( t > 1 ) {
  41727. t = 1;
  41728. s = clamp( ( b - c ) / a, 0, 1 );
  41729. }
  41730. }
  41731. }
  41732. c1.copy( p1 ).addScaledVector( _d1, s );
  41733. c2.copy( p2 ).addScaledVector( _d2, t );
  41734. return c1.distanceToSquared( c2 );
  41735. }
  41736. /**
  41737. * Applies a 4x4 transformation matrix to this line segment.
  41738. *
  41739. * @param {Matrix4} matrix - The transformation matrix.
  41740. * @return {Line3} A reference to this line segment.
  41741. */
  41742. applyMatrix4( matrix ) {
  41743. this.start.applyMatrix4( matrix );
  41744. this.end.applyMatrix4( matrix );
  41745. return this;
  41746. }
  41747. /**
  41748. * Returns `true` if this line segment is equal with the given one.
  41749. *
  41750. * @param {Line3} line - The line segment to test for equality.
  41751. * @return {boolean} Whether this line segment is equal with the given one.
  41752. */
  41753. equals( line ) {
  41754. return line.start.equals( this.start ) && line.end.equals( this.end );
  41755. }
  41756. /**
  41757. * Returns a new line segment with copied values from this instance.
  41758. *
  41759. * @return {Line3} A clone of this instance.
  41760. */
  41761. clone() {
  41762. return new this.constructor().copy( this );
  41763. }
  41764. }
  41765. const _vector$3 = /*@__PURE__*/ new Vector3();
  41766. /**
  41767. * This displays a cone shaped helper object for a {@link SpotLight}.
  41768. *
  41769. * When the spot light or its target are transformed or light properties are
  41770. * changed, it's necessary to call the `update()` method of the respective helper.
  41771. *
  41772. * ```js
  41773. * const spotLight = new THREE.SpotLight( 0xffffff );
  41774. * spotLight.position.set( 10, 10, 10 );
  41775. * scene.add( spotLight );
  41776. *
  41777. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41778. * scene.add( spotLightHelper );
  41779. * ```
  41780. *
  41781. * @augments Object3D
  41782. */
  41783. class SpotLightHelper extends Object3D {
  41784. /**
  41785. * Constructs a new spot light helper.
  41786. *
  41787. * @param {HemisphereLight} light - The light to be visualized.
  41788. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41789. * the color of the light.
  41790. */
  41791. constructor( light, color ) {
  41792. super();
  41793. /**
  41794. * The light being visualized.
  41795. *
  41796. * @type {SpotLight}
  41797. */
  41798. this.light = light;
  41799. this.matrixAutoUpdate = false;
  41800. /**
  41801. * The color parameter passed in the constructor.
  41802. * If not set, the helper will take the color of the light.
  41803. *
  41804. * @type {number|Color|string}
  41805. */
  41806. this.color = color;
  41807. this.type = 'SpotLightHelper';
  41808. const geometry = new BufferGeometry();
  41809. const positions = [
  41810. 0, 0, 0, 0, 0, 1,
  41811. 0, 0, 0, 1, 0, 1,
  41812. 0, 0, 0, -1, 0, 1,
  41813. 0, 0, 0, 0, 1, 1,
  41814. 0, 0, 0, 0, -1, 1
  41815. ];
  41816. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41817. const p1 = ( i / l ) * Math.PI * 2;
  41818. const p2 = ( j / l ) * Math.PI * 2;
  41819. positions.push(
  41820. Math.cos( p1 ), Math.sin( p1 ), 1,
  41821. Math.cos( p2 ), Math.sin( p2 ), 1
  41822. );
  41823. }
  41824. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41825. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41826. this.cone = new LineSegments( geometry, material );
  41827. this.add( this.cone );
  41828. this.update();
  41829. }
  41830. /**
  41831. * Frees the GPU-related resources allocated by this instance. Call this
  41832. * method whenever this instance is no longer used in your app.
  41833. */
  41834. dispose() {
  41835. this.cone.geometry.dispose();
  41836. this.cone.material.dispose();
  41837. }
  41838. /**
  41839. * Updates the helper to match the position and direction of the
  41840. * light being visualized.
  41841. */
  41842. update() {
  41843. this.light.updateWorldMatrix( true, false );
  41844. this.light.target.updateWorldMatrix( true, false );
  41845. // update the local matrix based on the parent and light target transforms
  41846. if ( this.parent ) {
  41847. this.parent.updateWorldMatrix( true );
  41848. this.matrix
  41849. .copy( this.parent.matrixWorld )
  41850. .invert()
  41851. .multiply( this.light.matrixWorld );
  41852. } else {
  41853. this.matrix.copy( this.light.matrixWorld );
  41854. }
  41855. this.matrixWorldNeedsUpdate = true;
  41856. const coneLength = this.light.distance ? this.light.distance : 1000;
  41857. const coneWidth = coneLength * Math.tan( this.light.angle );
  41858. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41859. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41860. this.cone.lookAt( _vector$3 );
  41861. if ( this.color !== undefined ) {
  41862. this.cone.material.color.set( this.color );
  41863. } else {
  41864. this.cone.material.color.copy( this.light.color );
  41865. }
  41866. }
  41867. }
  41868. const _vector$2 = /*@__PURE__*/ new Vector3();
  41869. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41870. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41871. /**
  41872. * A helper object to assist with visualizing a {@link Skeleton}.
  41873. *
  41874. * ```js
  41875. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41876. * scene.add( helper );
  41877. * ```
  41878. *
  41879. * @augments LineSegments
  41880. */
  41881. class SkeletonHelper extends LineSegments {
  41882. /**
  41883. * Constructs a new skeleton helper.
  41884. *
  41885. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41886. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41887. */
  41888. constructor( object ) {
  41889. const bones = getBoneList( object );
  41890. const geometry = new BufferGeometry();
  41891. const vertices = [];
  41892. const colors = [];
  41893. for ( let i = 0; i < bones.length; i ++ ) {
  41894. const bone = bones[ i ];
  41895. if ( bone.parent && bone.parent.isBone ) {
  41896. vertices.push( 0, 0, 0 );
  41897. vertices.push( 0, 0, 0 );
  41898. colors.push( 0, 0, 0 );
  41899. colors.push( 0, 0, 0 );
  41900. }
  41901. }
  41902. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41903. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41904. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41905. super( geometry, material );
  41906. /**
  41907. * This flag can be used for type testing.
  41908. *
  41909. * @type {boolean}
  41910. * @readonly
  41911. * @default true
  41912. */
  41913. this.isSkeletonHelper = true;
  41914. this.type = 'SkeletonHelper';
  41915. /**
  41916. * The object being visualized.
  41917. *
  41918. * @type {Object3D}
  41919. */
  41920. this.root = object;
  41921. /**
  41922. * The list of bones that the helper visualizes.
  41923. *
  41924. * @type {Array<Bone>}
  41925. */
  41926. this.bones = bones;
  41927. this.matrix = object.matrixWorld;
  41928. this.matrixAutoUpdate = false;
  41929. // colors
  41930. const color1 = new Color( 0x0000ff );
  41931. const color2 = new Color( 0x00ff00 );
  41932. this.setColors( color1, color2 );
  41933. }
  41934. updateMatrixWorld( force ) {
  41935. const bones = this.bones;
  41936. const geometry = this.geometry;
  41937. const position = geometry.getAttribute( 'position' );
  41938. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41939. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41940. const bone = bones[ i ];
  41941. if ( bone.parent && bone.parent.isBone ) {
  41942. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41943. _vector$2.setFromMatrixPosition( _boneMatrix );
  41944. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41945. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41946. _vector$2.setFromMatrixPosition( _boneMatrix );
  41947. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41948. j += 2;
  41949. }
  41950. }
  41951. geometry.getAttribute( 'position' ).needsUpdate = true;
  41952. super.updateMatrixWorld( force );
  41953. }
  41954. /**
  41955. * Defines the colors of the helper.
  41956. *
  41957. * @param {Color} color1 - The first line color for each bone.
  41958. * @param {Color} color2 - The second line color for each bone.
  41959. * @return {SkeletonHelper} A reference to this helper.
  41960. */
  41961. setColors( color1, color2 ) {
  41962. const geometry = this.geometry;
  41963. const colorAttribute = geometry.getAttribute( 'color' );
  41964. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41965. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41966. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41967. }
  41968. colorAttribute.needsUpdate = true;
  41969. return this;
  41970. }
  41971. /**
  41972. * Frees the GPU-related resources allocated by this instance. Call this
  41973. * method whenever this instance is no longer used in your app.
  41974. */
  41975. dispose() {
  41976. this.geometry.dispose();
  41977. this.material.dispose();
  41978. }
  41979. }
  41980. function getBoneList( object ) {
  41981. const boneList = [];
  41982. if ( object.isBone === true ) {
  41983. boneList.push( object );
  41984. }
  41985. for ( let i = 0; i < object.children.length; i ++ ) {
  41986. boneList.push( ...getBoneList( object.children[ i ] ) );
  41987. }
  41988. return boneList;
  41989. }
  41990. /**
  41991. * This displays a helper object consisting of a spherical mesh for
  41992. * visualizing an instance of {@link PointLight}.
  41993. *
  41994. * ```js
  41995. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41996. * pointLight.position.set( 10, 10, 10 );
  41997. * scene.add( pointLight );
  41998. *
  41999. * const sphereSize = 1;
  42000. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  42001. * scene.add( pointLightHelper );
  42002. * ```
  42003. *
  42004. * @augments Mesh
  42005. */
  42006. class PointLightHelper extends Mesh {
  42007. /**
  42008. * Constructs a new point light helper.
  42009. *
  42010. * @param {PointLight} light - The light to be visualized.
  42011. * @param {number} [sphereSize=1] - The size of the sphere helper.
  42012. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  42013. * the color of the light.
  42014. */
  42015. constructor( light, sphereSize, color ) {
  42016. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  42017. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  42018. super( geometry, material );
  42019. /**
  42020. * The light being visualized.
  42021. *
  42022. * @type {PointLight}
  42023. */
  42024. this.light = light;
  42025. /**
  42026. * The color parameter passed in the constructor.
  42027. * If not set, the helper will take the color of the light.
  42028. *
  42029. * @type {number|Color|string}
  42030. */
  42031. this.color = color;
  42032. this.type = 'PointLightHelper';
  42033. this.matrix = this.light.matrixWorld;
  42034. this.matrixAutoUpdate = false;
  42035. this.update();
  42036. }
  42037. /**
  42038. * Frees the GPU-related resources allocated by this instance. Call this
  42039. * method whenever this instance is no longer used in your app.
  42040. */
  42041. dispose() {
  42042. this.geometry.dispose();
  42043. this.material.dispose();
  42044. }
  42045. /**
  42046. * Updates the helper to match the position of the
  42047. * light being visualized.
  42048. */
  42049. update() {
  42050. this.matrixWorldNeedsUpdate = true;
  42051. this.light.updateWorldMatrix( true, false );
  42052. if ( this.color !== undefined ) {
  42053. this.material.color.set( this.color );
  42054. } else {
  42055. this.material.color.copy( this.light.color );
  42056. }
  42057. /*
  42058. const d = this.light.distance;
  42059. if ( d === 0.0 ) {
  42060. this.lightDistance.visible = false;
  42061. } else {
  42062. this.lightDistance.visible = true;
  42063. this.lightDistance.scale.set( d, d, d );
  42064. }
  42065. */
  42066. }
  42067. }
  42068. const _vector$1 = /*@__PURE__*/ new Vector3();
  42069. const _color1 = /*@__PURE__*/ new Color();
  42070. const _color2 = /*@__PURE__*/ new Color();
  42071. /**
  42072. * Creates a visual aid consisting of a spherical mesh for a
  42073. * given {@link HemisphereLight}.
  42074. *
  42075. * When the hemisphere light is transformed or its light properties are changed,
  42076. * it's necessary to call the `update()` method of the respective helper.
  42077. *
  42078. * ```js
  42079. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  42080. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  42081. * scene.add( helper );
  42082. * ```
  42083. *
  42084. * @augments Object3D
  42085. */
  42086. class HemisphereLightHelper extends Object3D {
  42087. /**
  42088. * Constructs a new hemisphere light helper.
  42089. *
  42090. * @param {HemisphereLight} light - The light to be visualized.
  42091. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  42092. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  42093. * the color of the light.
  42094. */
  42095. constructor( light, size, color ) {
  42096. super();
  42097. /**
  42098. * The light being visualized.
  42099. *
  42100. * @type {HemisphereLight}
  42101. */
  42102. this.light = light;
  42103. this.matrix = light.matrixWorld;
  42104. this.matrixAutoUpdate = false;
  42105. /**
  42106. * The color parameter passed in the constructor.
  42107. * If not set, the helper will take the color of the light.
  42108. *
  42109. * @type {number|Color|string}
  42110. */
  42111. this.color = color;
  42112. this.type = 'HemisphereLightHelper';
  42113. const geometry = new OctahedronGeometry( size );
  42114. geometry.rotateY( Math.PI * 0.5 );
  42115. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  42116. if ( this.color === undefined ) this.material.vertexColors = true;
  42117. const position = geometry.getAttribute( 'position' );
  42118. const colors = new Float32Array( position.count * 3 );
  42119. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  42120. this.add( new Mesh( geometry, this.material ) );
  42121. this.update();
  42122. }
  42123. /**
  42124. * Frees the GPU-related resources allocated by this instance. Call this
  42125. * method whenever this instance is no longer used in your app.
  42126. */
  42127. dispose() {
  42128. this.children[ 0 ].geometry.dispose();
  42129. this.children[ 0 ].material.dispose();
  42130. }
  42131. /**
  42132. * Updates the helper to match the position and direction of the
  42133. * light being visualized.
  42134. */
  42135. update() {
  42136. const mesh = this.children[ 0 ];
  42137. if ( this.color !== undefined ) {
  42138. this.material.color.set( this.color );
  42139. } else {
  42140. const colors = mesh.geometry.getAttribute( 'color' );
  42141. _color1.copy( this.light.color );
  42142. _color2.copy( this.light.groundColor );
  42143. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  42144. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  42145. colors.setXYZ( i, color.r, color.g, color.b );
  42146. }
  42147. colors.needsUpdate = true;
  42148. }
  42149. this.matrixWorldNeedsUpdate = true;
  42150. this.light.updateWorldMatrix( true, false );
  42151. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  42152. }
  42153. }
  42154. /**
  42155. * The helper is an object to define grids. Grids are two-dimensional
  42156. * arrays of lines.
  42157. *
  42158. * ```js
  42159. * const size = 10;
  42160. * const divisions = 10;
  42161. *
  42162. * const gridHelper = new THREE.GridHelper( size, divisions );
  42163. * scene.add( gridHelper );
  42164. * ```
  42165. *
  42166. * @augments LineSegments
  42167. */
  42168. class GridHelper extends LineSegments {
  42169. /**
  42170. * Constructs a new grid helper.
  42171. *
  42172. * @param {number} [size=10] - The size of the grid.
  42173. * @param {number} [divisions=10] - The number of divisions across the grid.
  42174. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  42175. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  42176. */
  42177. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  42178. color1 = new Color( color1 );
  42179. color2 = new Color( color2 );
  42180. const center = divisions / 2;
  42181. const step = size / divisions;
  42182. const halfSize = size / 2;
  42183. const vertices = [], colors = [];
  42184. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  42185. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  42186. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  42187. const color = i === center ? color1 : color2;
  42188. color.toArray( colors, j ); j += 3;
  42189. color.toArray( colors, j ); j += 3;
  42190. color.toArray( colors, j ); j += 3;
  42191. color.toArray( colors, j ); j += 3;
  42192. }
  42193. const geometry = new BufferGeometry();
  42194. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42195. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42196. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42197. super( geometry, material );
  42198. this.type = 'GridHelper';
  42199. }
  42200. /**
  42201. * Frees the GPU-related resources allocated by this instance. Call this
  42202. * method whenever this instance is no longer used in your app.
  42203. */
  42204. dispose() {
  42205. this.geometry.dispose();
  42206. this.material.dispose();
  42207. }
  42208. }
  42209. /**
  42210. * This helper is an object to define polar grids. Grids are
  42211. * two-dimensional arrays of lines.
  42212. *
  42213. * ```js
  42214. * const radius = 10;
  42215. * const sectors = 16;
  42216. * const rings = 8;
  42217. * const divisions = 64;
  42218. *
  42219. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  42220. * scene.add( helper );
  42221. * ```
  42222. *
  42223. * @augments LineSegments
  42224. */
  42225. class PolarGridHelper extends LineSegments {
  42226. /**
  42227. * Constructs a new polar grid helper.
  42228. *
  42229. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  42230. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  42231. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  42232. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  42233. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  42234. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  42235. */
  42236. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  42237. color1 = new Color( color1 );
  42238. color2 = new Color( color2 );
  42239. const vertices = [];
  42240. const colors = [];
  42241. // create the sectors
  42242. if ( sectors > 1 ) {
  42243. for ( let i = 0; i < sectors; i ++ ) {
  42244. const v = ( i / sectors ) * ( Math.PI * 2 );
  42245. const x = Math.sin( v ) * radius;
  42246. const z = Math.cos( v ) * radius;
  42247. vertices.push( 0, 0, 0 );
  42248. vertices.push( x, 0, z );
  42249. const color = ( i & 1 ) ? color1 : color2;
  42250. colors.push( color.r, color.g, color.b );
  42251. colors.push( color.r, color.g, color.b );
  42252. }
  42253. }
  42254. // create the rings
  42255. for ( let i = 0; i < rings; i ++ ) {
  42256. const color = ( i & 1 ) ? color1 : color2;
  42257. const r = radius - ( radius / rings * i );
  42258. for ( let j = 0; j < divisions; j ++ ) {
  42259. // first vertex
  42260. let v = ( j / divisions ) * ( Math.PI * 2 );
  42261. let x = Math.sin( v ) * r;
  42262. let z = Math.cos( v ) * r;
  42263. vertices.push( x, 0, z );
  42264. colors.push( color.r, color.g, color.b );
  42265. // second vertex
  42266. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  42267. x = Math.sin( v ) * r;
  42268. z = Math.cos( v ) * r;
  42269. vertices.push( x, 0, z );
  42270. colors.push( color.r, color.g, color.b );
  42271. }
  42272. }
  42273. const geometry = new BufferGeometry();
  42274. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42275. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42276. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42277. super( geometry, material );
  42278. this.type = 'PolarGridHelper';
  42279. }
  42280. /**
  42281. * Frees the GPU-related resources allocated by this instance. Call this
  42282. * method whenever this instance is no longer used in your app.
  42283. */
  42284. dispose() {
  42285. this.geometry.dispose();
  42286. this.material.dispose();
  42287. }
  42288. }
  42289. const _v1 = /*@__PURE__*/ new Vector3();
  42290. const _v2 = /*@__PURE__*/ new Vector3();
  42291. const _v3 = /*@__PURE__*/ new Vector3();
  42292. /**
  42293. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  42294. * effect on the scene. This consists of a plane and a line representing the
  42295. * light's position and direction.
  42296. *
  42297. * When the directional light or its target are transformed or light properties
  42298. * are changed, it's necessary to call the `update()` method of the respective helper.
  42299. *
  42300. * ```js
  42301. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  42302. * scene.add( light );
  42303. *
  42304. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  42305. * scene.add( helper );
  42306. * ```
  42307. *
  42308. * @augments Object3D
  42309. */
  42310. class DirectionalLightHelper extends Object3D {
  42311. /**
  42312. * Constructs a new directional light helper.
  42313. *
  42314. * @param {DirectionalLight} light - The light to be visualized.
  42315. * @param {number} [size=1] - The dimensions of the plane.
  42316. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  42317. * the color of the light.
  42318. */
  42319. constructor( light, size, color ) {
  42320. super();
  42321. /**
  42322. * The light being visualized.
  42323. *
  42324. * @type {DirectionalLight}
  42325. */
  42326. this.light = light;
  42327. this.matrix = light.matrixWorld;
  42328. this.matrixAutoUpdate = false;
  42329. /**
  42330. * The color parameter passed in the constructor.
  42331. * If not set, the helper will take the color of the light.
  42332. *
  42333. * @type {number|Color|string}
  42334. */
  42335. this.color = color;
  42336. this.type = 'DirectionalLightHelper';
  42337. if ( size === undefined ) size = 1;
  42338. let geometry = new BufferGeometry();
  42339. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  42340. - size, size, 0,
  42341. size, size, 0,
  42342. size, - size, 0,
  42343. - size, - size, 0,
  42344. - size, size, 0
  42345. ], 3 ) );
  42346. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  42347. /**
  42348. * Contains the line showing the location of the directional light.
  42349. *
  42350. * @type {Line}
  42351. */
  42352. this.lightPlane = new Line( geometry, material );
  42353. this.add( this.lightPlane );
  42354. geometry = new BufferGeometry();
  42355. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  42356. /**
  42357. * Represents the target line of the directional light.
  42358. *
  42359. * @type {Line}
  42360. */
  42361. this.targetLine = new Line( geometry, material );
  42362. this.add( this.targetLine );
  42363. this.update();
  42364. }
  42365. /**
  42366. * Frees the GPU-related resources allocated by this instance. Call this
  42367. * method whenever this instance is no longer used in your app.
  42368. */
  42369. dispose() {
  42370. this.lightPlane.geometry.dispose();
  42371. this.lightPlane.material.dispose();
  42372. this.targetLine.geometry.dispose();
  42373. this.targetLine.material.dispose();
  42374. }
  42375. /**
  42376. * Updates the helper to match the position and direction of the
  42377. * light being visualized.
  42378. */
  42379. update() {
  42380. this.matrixWorldNeedsUpdate = true;
  42381. this.light.updateWorldMatrix( true, false );
  42382. this.light.target.updateWorldMatrix( true, false );
  42383. _v1.setFromMatrixPosition( this.light.matrixWorld );
  42384. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  42385. _v3.subVectors( _v2, _v1 );
  42386. this.lightPlane.lookAt( _v2 );
  42387. if ( this.color !== undefined ) {
  42388. this.lightPlane.material.color.set( this.color );
  42389. this.targetLine.material.color.set( this.color );
  42390. } else {
  42391. this.lightPlane.material.color.copy( this.light.color );
  42392. this.targetLine.material.color.copy( this.light.color );
  42393. }
  42394. this.targetLine.lookAt( _v2 );
  42395. this.targetLine.scale.z = _v3.length();
  42396. }
  42397. }
  42398. const _vector = /*@__PURE__*/ new Vector3();
  42399. const _camera = /*@__PURE__*/ new Camera();
  42400. /**
  42401. * This helps with visualizing what a camera contains in its frustum. It
  42402. * visualizes the frustum of a camera using a line segments.
  42403. *
  42404. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  42405. *
  42406. * `CameraHelper` must be a child of the scene.
  42407. *
  42408. * When the camera is transformed or its projection matrix is changed, it's necessary
  42409. * to call the `update()` method of the respective helper.
  42410. *
  42411. * ```js
  42412. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  42413. * const helper = new THREE.CameraHelper( camera );
  42414. * scene.add( helper );
  42415. * ```
  42416. *
  42417. * @augments LineSegments
  42418. */
  42419. class CameraHelper extends LineSegments {
  42420. /**
  42421. * Constructs a new arrow helper.
  42422. *
  42423. * @param {Camera} camera - The camera to visualize.
  42424. */
  42425. constructor( camera ) {
  42426. const geometry = new BufferGeometry();
  42427. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  42428. const vertices = [];
  42429. const colors = [];
  42430. const pointMap = {};
  42431. // near
  42432. addLine( 'n1', 'n2' );
  42433. addLine( 'n2', 'n4' );
  42434. addLine( 'n4', 'n3' );
  42435. addLine( 'n3', 'n1' );
  42436. // far
  42437. addLine( 'f1', 'f2' );
  42438. addLine( 'f2', 'f4' );
  42439. addLine( 'f4', 'f3' );
  42440. addLine( 'f3', 'f1' );
  42441. // sides
  42442. addLine( 'n1', 'f1' );
  42443. addLine( 'n2', 'f2' );
  42444. addLine( 'n3', 'f3' );
  42445. addLine( 'n4', 'f4' );
  42446. // cone
  42447. addLine( 'p', 'n1' );
  42448. addLine( 'p', 'n2' );
  42449. addLine( 'p', 'n3' );
  42450. addLine( 'p', 'n4' );
  42451. // up
  42452. addLine( 'u1', 'u2' );
  42453. addLine( 'u2', 'u3' );
  42454. addLine( 'u3', 'u1' );
  42455. // target
  42456. addLine( 'c', 't' );
  42457. addLine( 'p', 'c' );
  42458. // cross
  42459. addLine( 'cn1', 'cn2' );
  42460. addLine( 'cn3', 'cn4' );
  42461. addLine( 'cf1', 'cf2' );
  42462. addLine( 'cf3', 'cf4' );
  42463. function addLine( a, b ) {
  42464. addPoint( a );
  42465. addPoint( b );
  42466. }
  42467. function addPoint( id ) {
  42468. vertices.push( 0, 0, 0 );
  42469. colors.push( 0, 0, 0 );
  42470. if ( pointMap[ id ] === undefined ) {
  42471. pointMap[ id ] = [];
  42472. }
  42473. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  42474. }
  42475. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42476. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42477. super( geometry, material );
  42478. this.type = 'CameraHelper';
  42479. /**
  42480. * The camera being visualized.
  42481. *
  42482. * @type {Camera}
  42483. */
  42484. this.camera = camera;
  42485. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  42486. this.matrix = camera.matrixWorld;
  42487. this.matrixAutoUpdate = false;
  42488. /**
  42489. * This contains the points used to visualize the camera.
  42490. *
  42491. * @type {Object<string,Array<number>>}
  42492. */
  42493. this.pointMap = pointMap;
  42494. this.update();
  42495. // colors
  42496. const colorFrustum = new Color( 0xffaa00 );
  42497. const colorCone = new Color( 0xff0000 );
  42498. const colorUp = new Color( 0x00aaff );
  42499. const colorTarget = new Color( 0xffffff );
  42500. const colorCross = new Color( 0x333333 );
  42501. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  42502. }
  42503. /**
  42504. * Defines the colors of the helper.
  42505. *
  42506. * @param {Color} frustum - The frustum line color.
  42507. * @param {Color} cone - The cone line color.
  42508. * @param {Color} up - The up line color.
  42509. * @param {Color} target - The target line color.
  42510. * @param {Color} cross - The cross line color.
  42511. * @return {CameraHelper} A reference to this helper.
  42512. */
  42513. setColors( frustum, cone, up, target, cross ) {
  42514. const geometry = this.geometry;
  42515. const colorAttribute = geometry.getAttribute( 'color' );
  42516. // near
  42517. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  42518. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  42519. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  42520. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  42521. // far
  42522. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  42523. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  42524. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  42525. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  42526. // sides
  42527. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  42528. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  42529. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  42530. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  42531. // cone
  42532. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  42533. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  42534. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  42535. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  42536. // up
  42537. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  42538. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  42539. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  42540. // target
  42541. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  42542. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  42543. // cross
  42544. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  42545. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  42546. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  42547. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  42548. colorAttribute.needsUpdate = true;
  42549. return this;
  42550. }
  42551. /**
  42552. * Updates the helper based on the projection matrix of the camera.
  42553. */
  42554. update() {
  42555. const geometry = this.geometry;
  42556. const pointMap = this.pointMap;
  42557. const w = 1, h = 1;
  42558. let nearZ, farZ;
  42559. // we need just camera projection matrix inverse
  42560. // world matrix must be identity
  42561. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  42562. // Adjust z values based on coordinate system
  42563. if ( this.camera.reversedDepth === true ) {
  42564. nearZ = 1;
  42565. farZ = 0;
  42566. } else {
  42567. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  42568. nearZ = -1;
  42569. farZ = 1;
  42570. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  42571. nearZ = 0;
  42572. farZ = 1;
  42573. } else {
  42574. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  42575. }
  42576. }
  42577. // center / target
  42578. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  42579. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  42580. // near
  42581. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  42582. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  42583. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  42584. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  42585. // far
  42586. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  42587. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  42588. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  42589. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  42590. // up
  42591. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  42592. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  42593. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  42594. // cross
  42595. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  42596. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  42597. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  42598. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  42599. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  42600. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  42601. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  42602. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  42603. geometry.getAttribute( 'position' ).needsUpdate = true;
  42604. }
  42605. /**
  42606. * Frees the GPU-related resources allocated by this instance. Call this
  42607. * method whenever this instance is no longer used in your app.
  42608. */
  42609. dispose() {
  42610. this.geometry.dispose();
  42611. this.material.dispose();
  42612. }
  42613. }
  42614. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42615. _vector.set( x, y, z ).unproject( camera );
  42616. const points = pointMap[ point ];
  42617. if ( points !== undefined ) {
  42618. const position = geometry.getAttribute( 'position' );
  42619. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42620. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42621. }
  42622. }
  42623. }
  42624. const _box = /*@__PURE__*/ new Box3();
  42625. /**
  42626. * Helper object to graphically show the world-axis-aligned bounding box
  42627. * around an object. The actual bounding box is handled with {@link Box3},
  42628. * this is just a visual helper for debugging. It can be automatically
  42629. * resized with {@link BoxHelper#update} when the object it's created from
  42630. * is transformed. Note that the object must have a geometry for this to work,
  42631. * so it won't work with sprites.
  42632. *
  42633. * ```js
  42634. * const sphere = new THREE.SphereGeometry();
  42635. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42636. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42637. * scene.add( box );
  42638. * ```
  42639. *
  42640. * @augments LineSegments
  42641. */
  42642. class BoxHelper extends LineSegments {
  42643. /**
  42644. * Constructs a new box helper.
  42645. *
  42646. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42647. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42648. */
  42649. constructor( object, color = 0xffff00 ) {
  42650. 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 ] );
  42651. const positions = new Float32Array( 8 * 3 );
  42652. const geometry = new BufferGeometry();
  42653. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42654. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42655. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42656. /**
  42657. * The 3D object being visualized.
  42658. *
  42659. * @type {Object3D}
  42660. */
  42661. this.object = object;
  42662. this.type = 'BoxHelper';
  42663. this.matrixAutoUpdate = false;
  42664. this.update();
  42665. }
  42666. /**
  42667. * Updates the helper's geometry to match the dimensions of the object,
  42668. * including any children.
  42669. */
  42670. update() {
  42671. if ( this.object !== undefined ) {
  42672. _box.setFromObject( this.object );
  42673. }
  42674. if ( _box.isEmpty() ) return;
  42675. const min = _box.min;
  42676. const max = _box.max;
  42677. /*
  42678. 5____4
  42679. 1/___0/|
  42680. | 6__|_7
  42681. 2/___3/
  42682. 0: max.x, max.y, max.z
  42683. 1: min.x, max.y, max.z
  42684. 2: min.x, min.y, max.z
  42685. 3: max.x, min.y, max.z
  42686. 4: max.x, max.y, min.z
  42687. 5: min.x, max.y, min.z
  42688. 6: min.x, min.y, min.z
  42689. 7: max.x, min.y, min.z
  42690. */
  42691. const position = this.geometry.attributes.position;
  42692. const array = position.array;
  42693. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42694. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42695. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42696. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42697. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42698. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42699. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42700. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42701. position.needsUpdate = true;
  42702. this.geometry.computeBoundingSphere();
  42703. }
  42704. /**
  42705. * Updates the wireframe box for the passed object.
  42706. *
  42707. * @param {Object3D} object - The 3D object to create the helper for.
  42708. * @return {BoxHelper} A reference to this instance.
  42709. */
  42710. setFromObject( object ) {
  42711. this.object = object;
  42712. this.update();
  42713. return this;
  42714. }
  42715. copy( source, recursive ) {
  42716. super.copy( source, recursive );
  42717. this.object = source.object;
  42718. return this;
  42719. }
  42720. /**
  42721. * Frees the GPU-related resources allocated by this instance. Call this
  42722. * method whenever this instance is no longer used in your app.
  42723. */
  42724. dispose() {
  42725. this.geometry.dispose();
  42726. this.material.dispose();
  42727. }
  42728. }
  42729. /**
  42730. * A helper object to visualize an instance of {@link Box3}.
  42731. *
  42732. * ```js
  42733. * const box = new THREE.Box3();
  42734. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42735. *
  42736. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42737. * scene.add( helper )
  42738. * ```
  42739. *
  42740. * @augments LineSegments
  42741. */
  42742. class Box3Helper extends LineSegments {
  42743. /**
  42744. * Constructs a new box3 helper.
  42745. *
  42746. * @param {Box3} box - The box to visualize.
  42747. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42748. */
  42749. constructor( box, color = 0xffff00 ) {
  42750. 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 ] );
  42751. 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 ];
  42752. const geometry = new BufferGeometry();
  42753. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42754. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42755. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42756. /**
  42757. * The box being visualized.
  42758. *
  42759. * @type {Box3}
  42760. */
  42761. this.box = box;
  42762. this.type = 'Box3Helper';
  42763. this.geometry.computeBoundingSphere();
  42764. }
  42765. updateMatrixWorld( force ) {
  42766. const box = this.box;
  42767. if ( box.isEmpty() ) return;
  42768. box.getCenter( this.position );
  42769. box.getSize( this.scale );
  42770. this.scale.multiplyScalar( 0.5 );
  42771. super.updateMatrixWorld( force );
  42772. }
  42773. /**
  42774. * Frees the GPU-related resources allocated by this instance. Call this
  42775. * method whenever this instance is no longer used in your app.
  42776. */
  42777. dispose() {
  42778. this.geometry.dispose();
  42779. this.material.dispose();
  42780. }
  42781. }
  42782. /**
  42783. * A helper object to visualize an instance of {@link Plane}.
  42784. *
  42785. * ```js
  42786. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42787. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42788. * scene.add( helper );
  42789. * ```
  42790. *
  42791. * @augments Line
  42792. */
  42793. class PlaneHelper extends Line {
  42794. /**
  42795. * Constructs a new plane helper.
  42796. *
  42797. * @param {Plane} plane - The plane to be visualized.
  42798. * @param {number} [size=1] - The side length of plane helper.
  42799. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42800. */
  42801. constructor( plane, size = 1, hex = 0xffff00 ) {
  42802. const color = hex;
  42803. 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 ];
  42804. const geometry = new BufferGeometry();
  42805. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42806. geometry.computeBoundingSphere();
  42807. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42808. this.type = 'PlaneHelper';
  42809. /**
  42810. * The plane being visualized.
  42811. *
  42812. * @type {Plane}
  42813. */
  42814. this.plane = plane;
  42815. /**
  42816. * The side length of plane helper.
  42817. *
  42818. * @type {number}
  42819. * @default 1
  42820. */
  42821. this.size = size;
  42822. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42823. const geometry2 = new BufferGeometry();
  42824. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42825. geometry2.computeBoundingSphere();
  42826. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42827. }
  42828. updateMatrixWorld( force ) {
  42829. this.position.set( 0, 0, 0 );
  42830. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42831. this.lookAt( this.plane.normal );
  42832. this.translateZ( - this.plane.constant );
  42833. super.updateMatrixWorld( force );
  42834. }
  42835. /**
  42836. * Updates the helper to match the position and direction of the
  42837. * light being visualized.
  42838. */
  42839. dispose() {
  42840. this.geometry.dispose();
  42841. this.material.dispose();
  42842. this.children[ 0 ].geometry.dispose();
  42843. this.children[ 0 ].material.dispose();
  42844. }
  42845. }
  42846. const _axis = /*@__PURE__*/ new Vector3();
  42847. let _lineGeometry, _coneGeometry;
  42848. /**
  42849. * An 3D arrow object for visualizing directions.
  42850. *
  42851. * ```js
  42852. * const dir = new THREE.Vector3( 1, 2, 0 );
  42853. *
  42854. * //normalize the direction vector (convert to vector of length 1)
  42855. * dir.normalize();
  42856. *
  42857. * const origin = new THREE.Vector3( 0, 0, 0 );
  42858. * const length = 1;
  42859. * const hex = 0xffff00;
  42860. *
  42861. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42862. * scene.add( arrowHelper );
  42863. * ```
  42864. *
  42865. * @augments Object3D
  42866. */
  42867. class ArrowHelper extends Object3D {
  42868. /**
  42869. * Constructs a new arrow helper.
  42870. *
  42871. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42872. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42873. * @param {number} [length=1] - Length of the arrow in world units.
  42874. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42875. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42876. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42877. */
  42878. 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 ) {
  42879. super();
  42880. this.type = 'ArrowHelper';
  42881. if ( _lineGeometry === undefined ) {
  42882. _lineGeometry = new BufferGeometry();
  42883. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42884. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42885. _coneGeometry.translate( 0, -0.5, 0 );
  42886. }
  42887. this.position.copy( origin );
  42888. /**
  42889. * The line part of the arrow helper.
  42890. *
  42891. * @type {Line}
  42892. */
  42893. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42894. this.line.matrixAutoUpdate = false;
  42895. this.add( this.line );
  42896. /**
  42897. * The cone part of the arrow helper.
  42898. *
  42899. * @type {Mesh}
  42900. */
  42901. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42902. this.cone.matrixAutoUpdate = false;
  42903. this.add( this.cone );
  42904. this.setDirection( dir );
  42905. this.setLength( length, headLength, headWidth );
  42906. }
  42907. /**
  42908. * Sets the direction of the helper.
  42909. *
  42910. * @param {Vector3} dir - The normalized direction vector.
  42911. */
  42912. setDirection( dir ) {
  42913. // dir is assumed to be normalized
  42914. if ( dir.y > 0.99999 ) {
  42915. this.quaternion.set( 0, 0, 0, 1 );
  42916. } else if ( dir.y < -0.99999 ) {
  42917. this.quaternion.set( 1, 0, 0, 0 );
  42918. } else {
  42919. _axis.set( dir.z, 0, - dir.x ).normalize();
  42920. const radians = Math.acos( dir.y );
  42921. this.quaternion.setFromAxisAngle( _axis, radians );
  42922. }
  42923. }
  42924. /**
  42925. * Sets the length of the helper.
  42926. *
  42927. * @param {number} length - Length of the arrow in world units.
  42928. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42929. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42930. */
  42931. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42932. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42933. this.line.updateMatrix();
  42934. this.cone.scale.set( headWidth, headLength, headWidth );
  42935. this.cone.position.y = length;
  42936. this.cone.updateMatrix();
  42937. }
  42938. /**
  42939. * Sets the color of the helper.
  42940. *
  42941. * @param {number|Color|string} color - The color to set.
  42942. */
  42943. setColor( color ) {
  42944. this.line.material.color.set( color );
  42945. this.cone.material.color.set( color );
  42946. }
  42947. copy( source ) {
  42948. super.copy( source, false );
  42949. this.line.copy( source.line );
  42950. this.cone.copy( source.cone );
  42951. return this;
  42952. }
  42953. /**
  42954. * Frees the GPU-related resources allocated by this instance. Call this
  42955. * method whenever this instance is no longer used in your app.
  42956. */
  42957. dispose() {
  42958. this.line.geometry.dispose();
  42959. this.line.material.dispose();
  42960. this.cone.geometry.dispose();
  42961. this.cone.material.dispose();
  42962. }
  42963. }
  42964. /**
  42965. * An axis object to visualize the 3 axes in a simple way.
  42966. * The X axis is red. The Y axis is green. The Z axis is blue.
  42967. *
  42968. * ```js
  42969. * const axesHelper = new THREE.AxesHelper( 5 );
  42970. * scene.add( axesHelper );
  42971. * ```
  42972. *
  42973. * @augments LineSegments
  42974. */
  42975. class AxesHelper extends LineSegments {
  42976. /**
  42977. * Constructs a new axes helper.
  42978. *
  42979. * @param {number} [size=1] - Size of the lines representing the axes.
  42980. */
  42981. constructor( size = 1 ) {
  42982. const vertices = [
  42983. 0, 0, 0, size, 0, 0,
  42984. 0, 0, 0, 0, size, 0,
  42985. 0, 0, 0, 0, 0, size
  42986. ];
  42987. const colors = [
  42988. 1, 0, 0, 1, 0.6, 0,
  42989. 0, 1, 0, 0.6, 1, 0,
  42990. 0, 0, 1, 0, 0.6, 1
  42991. ];
  42992. const geometry = new BufferGeometry();
  42993. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42994. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42995. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42996. super( geometry, material );
  42997. this.type = 'AxesHelper';
  42998. }
  42999. /**
  43000. * Defines the colors of the axes helper.
  43001. *
  43002. * @param {number|Color|string} xAxisColor - The color for the x axis.
  43003. * @param {number|Color|string} yAxisColor - The color for the y axis.
  43004. * @param {number|Color|string} zAxisColor - The color for the z axis.
  43005. * @return {AxesHelper} A reference to this axes helper.
  43006. */
  43007. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  43008. const color = new Color();
  43009. const array = this.geometry.attributes.color.array;
  43010. color.set( xAxisColor );
  43011. color.toArray( array, 0 );
  43012. color.toArray( array, 3 );
  43013. color.set( yAxisColor );
  43014. color.toArray( array, 6 );
  43015. color.toArray( array, 9 );
  43016. color.set( zAxisColor );
  43017. color.toArray( array, 12 );
  43018. color.toArray( array, 15 );
  43019. this.geometry.attributes.color.needsUpdate = true;
  43020. return this;
  43021. }
  43022. /**
  43023. * Frees the GPU-related resources allocated by this instance. Call this
  43024. * method whenever this instance is no longer used in your app.
  43025. */
  43026. dispose() {
  43027. this.geometry.dispose();
  43028. this.material.dispose();
  43029. }
  43030. }
  43031. /**
  43032. * This class is used to convert a series of paths to an array of
  43033. * shapes. It is specifically used in context of fonts and SVG.
  43034. */
  43035. class ShapePath {
  43036. /**
  43037. * Constructs a new shape path.
  43038. */
  43039. constructor() {
  43040. this.type = 'ShapePath';
  43041. /**
  43042. * The color of the shape.
  43043. *
  43044. * @type {Color}
  43045. */
  43046. this.color = new Color();
  43047. /**
  43048. * The paths that have been generated for this shape.
  43049. *
  43050. * @type {Array<Path>}
  43051. * @default null
  43052. */
  43053. this.subPaths = [];
  43054. /**
  43055. * The current path that is being generated.
  43056. *
  43057. * @type {?Path}
  43058. * @default null
  43059. */
  43060. this.currentPath = null;
  43061. /**
  43062. * An object that can be used to store custom data about the shape path.
  43063. * Mainly used by SVGLoader to store style information.
  43064. *
  43065. * @type {Object}
  43066. */
  43067. this.userData = {};
  43068. }
  43069. /**
  43070. * Creates a new path and moves it current point to the given one.
  43071. *
  43072. * @param {number} x - The x coordinate.
  43073. * @param {number} y - The y coordinate.
  43074. * @return {ShapePath} A reference to this shape path.
  43075. */
  43076. moveTo( x, y ) {
  43077. this.currentPath = new Path();
  43078. this.subPaths.push( this.currentPath );
  43079. this.currentPath.moveTo( x, y );
  43080. return this;
  43081. }
  43082. /**
  43083. * Adds an instance of {@link LineCurve} to the path by connecting
  43084. * the current point with the given one.
  43085. *
  43086. * @param {number} x - The x coordinate of the end point.
  43087. * @param {number} y - The y coordinate of the end point.
  43088. * @return {ShapePath} A reference to this shape path.
  43089. */
  43090. lineTo( x, y ) {
  43091. this.currentPath.lineTo( x, y );
  43092. return this;
  43093. }
  43094. /**
  43095. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  43096. * the current point with the given one.
  43097. *
  43098. * @param {number} aCPx - The x coordinate of the control point.
  43099. * @param {number} aCPy - The y coordinate of the control point.
  43100. * @param {number} aX - The x coordinate of the end point.
  43101. * @param {number} aY - The y coordinate of the end point.
  43102. * @return {ShapePath} A reference to this shape path.
  43103. */
  43104. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  43105. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  43106. return this;
  43107. }
  43108. /**
  43109. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  43110. * the current point with the given one.
  43111. *
  43112. * @param {number} aCP1x - The x coordinate of the first control point.
  43113. * @param {number} aCP1y - The y coordinate of the first control point.
  43114. * @param {number} aCP2x - The x coordinate of the second control point.
  43115. * @param {number} aCP2y - The y coordinate of the second control point.
  43116. * @param {number} aX - The x coordinate of the end point.
  43117. * @param {number} aY - The y coordinate of the end point.
  43118. * @return {ShapePath} A reference to this shape path.
  43119. */
  43120. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  43121. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  43122. return this;
  43123. }
  43124. /**
  43125. * Adds an instance of {@link SplineCurve} to the path by connecting
  43126. * the current point with the given list of points.
  43127. *
  43128. * @param {Array<Vector2>} pts - An array of points in 2D space.
  43129. * @return {ShapePath} A reference to this shape path.
  43130. */
  43131. splineThru( pts ) {
  43132. this.currentPath.splineThru( pts );
  43133. return this;
  43134. }
  43135. /**
  43136. * Converts the paths into an array of shapes.
  43137. *
  43138. * @return {Array<Shape>} An array of shapes.
  43139. */
  43140. toShapes() {
  43141. // Point-in-polygon test using the even-odd ray-casting rule. Valid for
  43142. // simple (non self-intersecting) polygons.
  43143. function pointInPolygon( p, polygon ) {
  43144. let inside = false;
  43145. const n = polygon.length;
  43146. for ( let i = 0, j = n - 1; i < n; j = i ++ ) {
  43147. const a = polygon[ i ];
  43148. const b = polygon[ j ];
  43149. if ( ( a.y > p.y ) !== ( b.y > p.y ) &&
  43150. p.x < ( b.x - a.x ) * ( p.y - a.y ) / ( b.y - a.y ) + a.x ) {
  43151. inside = ! inside;
  43152. }
  43153. }
  43154. return inside;
  43155. }
  43156. // Returns a point guaranteed to be strictly inside the given simple
  43157. // polygon. First tries the bounding-box center; if that falls outside
  43158. // the polygon, casts a horizontal ray at the center's y and picks the
  43159. // midpoint between the first two sorted intercepts.
  43160. //
  43161. // Port of paper.js' Path#getInteriorPoint()
  43162. // https://github.com/paperjs/paper.js/blob/develop/src/path/PathItem.Boolean.js
  43163. function getInteriorPoint( polygon, boundingBox ) {
  43164. const point = boundingBox.getCenter( new Vector2() );
  43165. if ( pointInPolygon( point, polygon ) ) return point;
  43166. const y = point.y;
  43167. const intercepts = [];
  43168. const n = polygon.length;
  43169. for ( let i = 0; i < n; i ++ ) {
  43170. const a = polygon[ i ];
  43171. const b = polygon[ ( i + 1 ) % n ];
  43172. // Half-open crossing rule — counts each vertex exactly once and
  43173. // skips horizontal edges.
  43174. if ( ( a.y > y ) !== ( b.y > y ) ) {
  43175. const x = a.x + ( y - a.y ) * ( b.x - a.x ) / ( b.y - a.y );
  43176. intercepts.push( x );
  43177. }
  43178. }
  43179. if ( intercepts.length > 1 ) {
  43180. intercepts.sort( ( a, b ) => a - b );
  43181. point.x = ( intercepts[ 0 ] + intercepts[ 1 ] ) / 2;
  43182. }
  43183. return point;
  43184. }
  43185. // Resolve fill-rule. Defaults to 'nonzero'.
  43186. let fillRule = ( this.userData.style && this.userData.style.fillRule ) || 'nonzero';
  43187. if ( fillRule !== 'nonzero' && fillRule !== 'evenodd' ) {
  43188. warn( 'Fill-rule "' + fillRule + '" is not supported, falling back to "nonzero".' );
  43189. fillRule = 'nonzero';
  43190. }
  43191. // Predicate that decides whether a winding number falls inside the fill
  43192. // region, per the SVG fill-rule spec. Works for negative windings too,
  43193. // because JavaScript's bitwise AND preserves odd/even under two's
  43194. // complement.
  43195. const isInside = fillRule === 'nonzero'
  43196. ? ( w => w !== 0 )
  43197. : ( w => ( w & 1 ) !== 0 );
  43198. // Build an entry per usable subpath. Self-winding follows the standard
  43199. // convention used by ShapeUtils: counter-clockwise (signed area > 0)
  43200. // contributes +1 to the winding number at an interior point,
  43201. // clockwise contributes -1.
  43202. const entries = [];
  43203. for ( const subPath of this.subPaths ) {
  43204. const points = subPath.getPoints();
  43205. if ( points.length < 3 ) continue;
  43206. const area = ShapeUtils.area( points );
  43207. if ( area === 0 ) continue;
  43208. const boundingBox = new Box2();
  43209. for ( let i = 0; i < points.length; i ++ ) boundingBox.expandByPoint( points[ i ] );
  43210. entries.push( {
  43211. subPath: subPath,
  43212. points: points,
  43213. boundingBox: boundingBox,
  43214. interiorPoint: getInteriorPoint( points, boundingBox ),
  43215. absArea: Math.abs( area ),
  43216. winding: area < 0 ? -1 : 1,
  43217. container: null,
  43218. exclude: false,
  43219. role: null
  43220. } );
  43221. }
  43222. // Sort by area descending. This guarantees that any subpath that could
  43223. // contain `entries[i]` is located at a smaller index and has already
  43224. // been processed when it's entries[i]'s turn. Port of paper.js'
  43225. // reorientPaths() algorithm.
  43226. entries.sort( ( a, b ) => b.absArea - a.absArea );
  43227. // Walk already-processed entries from closest-in-size to largest,
  43228. // stopping at the innermost container. Accumulate the container's
  43229. // cumulative winding into this entry's winding so that the final value
  43230. // equals the winding number at this entry's interior point.
  43231. //
  43232. // A subpath only contributes to the fill boundary when crossing it
  43233. // actually flips the "insideness" per the fill rule; otherwise it's a
  43234. // redundant overlap and gets excluded to avoid double-counting.
  43235. for ( let i = 0; i < entries.length; i ++ ) {
  43236. const entry = entries[ i ];
  43237. let containerWinding = 0;
  43238. for ( let j = i - 1; j >= 0; j -- ) {
  43239. const candidate = entries[ j ];
  43240. if ( ! candidate.boundingBox.containsBox( entry.boundingBox ) ) continue;
  43241. if ( ! pointInPolygon( entry.interiorPoint, candidate.points ) ) continue;
  43242. entry.container = candidate.exclude ? candidate.container : candidate;
  43243. containerWinding = candidate.winding;
  43244. entry.winding += containerWinding;
  43245. break;
  43246. }
  43247. if ( isInside( entry.winding ) === isInside( containerWinding ) ) {
  43248. entry.exclude = true;
  43249. }
  43250. }
  43251. // Classify retained entries. An entry is an outer shape if it has no
  43252. // container or if its container is itself a hole (a solid nested inside
  43253. // a hole becomes a new top-level shape); otherwise it's a hole in its
  43254. // container. Entries were already sorted outermost-first, so each
  43255. // container's role is known by the time we look at it.
  43256. for ( const entry of entries ) {
  43257. if ( entry.exclude ) continue;
  43258. entry.role = ( entry.container === null || entry.container.role === 'hole' ) ? 'outer' : 'hole';
  43259. }
  43260. // Build Shapes for outers first, then attach holes to their container's
  43261. // Shape.
  43262. const shapes = [];
  43263. const shapeByEntry = new Map();
  43264. for ( const entry of entries ) {
  43265. if ( entry.exclude || entry.role !== 'outer' ) continue;
  43266. const shape = new Shape();
  43267. shape.curves = entry.subPath.curves;
  43268. shapes.push( shape );
  43269. shapeByEntry.set( entry, shape );
  43270. }
  43271. for ( const entry of entries ) {
  43272. if ( entry.exclude || entry.role !== 'hole' ) continue;
  43273. const shape = shapeByEntry.get( entry.container );
  43274. if ( ! shape ) continue;
  43275. const hole = new Path();
  43276. hole.curves = entry.subPath.curves;
  43277. shape.holes.push( hole );
  43278. }
  43279. return shapes;
  43280. }
  43281. }
  43282. /**
  43283. * Abstract base class for controls.
  43284. *
  43285. * @abstract
  43286. * @augments EventDispatcher
  43287. */
  43288. class Controls extends EventDispatcher {
  43289. /**
  43290. * Constructs a new controls instance.
  43291. *
  43292. * @param {Object3D} object - The object that is managed by the controls.
  43293. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  43294. */
  43295. constructor( object, domElement = null ) {
  43296. super();
  43297. /**
  43298. * The object that is managed by the controls.
  43299. *
  43300. * @type {Object3D}
  43301. */
  43302. this.object = object;
  43303. /**
  43304. * The HTML element used for event listeners.
  43305. *
  43306. * @type {?HTMLElement}
  43307. * @default null
  43308. */
  43309. this.domElement = domElement;
  43310. /**
  43311. * Whether the controls responds to user input or not.
  43312. *
  43313. * @type {boolean}
  43314. * @default true
  43315. */
  43316. this.enabled = true;
  43317. /**
  43318. * The internal state of the controls.
  43319. *
  43320. * @type {number}
  43321. * @default -1
  43322. */
  43323. this.state = -1;
  43324. /**
  43325. * This object defines the keyboard input of the controls.
  43326. *
  43327. * @type {Object}
  43328. */
  43329. this.keys = {};
  43330. /**
  43331. * This object defines what type of actions are assigned to the available mouse buttons.
  43332. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  43333. *
  43334. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  43335. */
  43336. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  43337. /**
  43338. * This object defines what type of actions are assigned to what kind of touch interaction.
  43339. * It depends on the control implementation what kind of touch interaction and actions are supported.
  43340. *
  43341. * @type {{ONE: ?number, TWO: ?number}}
  43342. */
  43343. this.touches = { ONE: null, TWO: null };
  43344. }
  43345. /**
  43346. * Connects the controls to the DOM. This method has so called "side effects" since
  43347. * it adds the module's event listeners to the DOM.
  43348. *
  43349. * @param {HTMLElement} element - The DOM element to connect to.
  43350. */
  43351. connect( element ) {
  43352. if ( this.domElement !== null ) this.disconnect();
  43353. this.domElement = element;
  43354. }
  43355. /**
  43356. * Disconnects the controls from the DOM.
  43357. */
  43358. disconnect() {}
  43359. /**
  43360. * Call this method if you no longer want use to the controls. It frees all internal
  43361. * resources and removes all event listeners.
  43362. */
  43363. dispose() {}
  43364. /**
  43365. * Controls should implement this method if they have to update their internal state
  43366. * per simulation step.
  43367. *
  43368. * @param {number} [delta] - The time delta in seconds.
  43369. */
  43370. update( /* delta */ ) {}
  43371. }
  43372. /**
  43373. * Scales the texture as large as possible within its surface without cropping
  43374. * or stretching the texture. The method preserves the original aspect ratio of
  43375. * the texture. Akin to CSS `object-fit: contain`
  43376. *
  43377. * @param {Texture} texture - The texture.
  43378. * @param {number} aspect - The texture's aspect ratio.
  43379. * @return {Texture} The updated texture.
  43380. */
  43381. function contain( texture, aspect ) {
  43382. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  43383. if ( imageAspect > aspect ) {
  43384. texture.repeat.x = 1;
  43385. texture.repeat.y = imageAspect / aspect;
  43386. texture.offset.x = 0;
  43387. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  43388. } else {
  43389. texture.repeat.x = aspect / imageAspect;
  43390. texture.repeat.y = 1;
  43391. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  43392. texture.offset.y = 0;
  43393. }
  43394. return texture;
  43395. }
  43396. /**
  43397. * Scales the texture to the smallest possible size to fill the surface, leaving
  43398. * no empty space. The method preserves the original aspect ratio of the texture.
  43399. * Akin to CSS `object-fit: cover`.
  43400. *
  43401. * @param {Texture} texture - The texture.
  43402. * @param {number} aspect - The texture's aspect ratio.
  43403. * @return {Texture} The updated texture.
  43404. */
  43405. function cover( texture, aspect ) {
  43406. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  43407. if ( imageAspect > aspect ) {
  43408. texture.repeat.x = aspect / imageAspect;
  43409. texture.repeat.y = 1;
  43410. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  43411. texture.offset.y = 0;
  43412. } else {
  43413. texture.repeat.x = 1;
  43414. texture.repeat.y = imageAspect / aspect;
  43415. texture.offset.x = 0;
  43416. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  43417. }
  43418. return texture;
  43419. }
  43420. /**
  43421. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43422. *
  43423. * @param {Texture} texture - The texture.
  43424. * @return {Texture} The updated texture.
  43425. */
  43426. function fill( texture ) {
  43427. texture.repeat.x = 1;
  43428. texture.repeat.y = 1;
  43429. texture.offset.x = 0;
  43430. texture.offset.y = 0;
  43431. return texture;
  43432. }
  43433. /**
  43434. * Determines how many bytes must be used to represent the texture.
  43435. *
  43436. * @param {number} width - The width of the texture.
  43437. * @param {number} height - The height of the texture.
  43438. * @param {number} format - The texture's format.
  43439. * @param {number} type - The texture's type.
  43440. * @return {number} The byte length.
  43441. */
  43442. function getByteLength( width, height, format, type ) {
  43443. const typeByteLength = getTextureTypeByteLength( type );
  43444. switch ( format ) {
  43445. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  43446. case AlphaFormat:
  43447. return width * height;
  43448. case RedFormat:
  43449. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43450. case RedIntegerFormat:
  43451. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43452. case RGFormat:
  43453. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43454. case RGIntegerFormat:
  43455. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43456. case RGBFormat:
  43457. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43458. case RGBAFormat:
  43459. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43460. case RGBAIntegerFormat:
  43461. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43462. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  43463. case RGB_S3TC_DXT1_Format:
  43464. case RGBA_S3TC_DXT1_Format:
  43465. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43466. case RGBA_S3TC_DXT3_Format:
  43467. case RGBA_S3TC_DXT5_Format:
  43468. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43469. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  43470. case RGB_PVRTC_2BPPV1_Format:
  43471. case RGBA_PVRTC_2BPPV1_Format:
  43472. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  43473. case RGB_PVRTC_4BPPV1_Format:
  43474. case RGBA_PVRTC_4BPPV1_Format:
  43475. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  43476. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  43477. case RGB_ETC1_Format:
  43478. case RGB_ETC2_Format:
  43479. case R11_EAC_Format:
  43480. case SIGNED_R11_EAC_Format:
  43481. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43482. case RGBA_ETC2_EAC_Format:
  43483. case RG11_EAC_Format:
  43484. case SIGNED_RG11_EAC_Format:
  43485. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43486. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  43487. case RGBA_ASTC_4x4_Format:
  43488. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43489. case RGBA_ASTC_5x4_Format:
  43490. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43491. case RGBA_ASTC_5x5_Format:
  43492. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43493. case RGBA_ASTC_6x5_Format:
  43494. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43495. case RGBA_ASTC_6x6_Format:
  43496. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43497. case RGBA_ASTC_8x5_Format:
  43498. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43499. case RGBA_ASTC_8x6_Format:
  43500. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43501. case RGBA_ASTC_8x8_Format:
  43502. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43503. case RGBA_ASTC_10x5_Format:
  43504. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43505. case RGBA_ASTC_10x6_Format:
  43506. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43507. case RGBA_ASTC_10x8_Format:
  43508. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43509. case RGBA_ASTC_10x10_Format:
  43510. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43511. case RGBA_ASTC_12x10_Format:
  43512. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43513. case RGBA_ASTC_12x12_Format:
  43514. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  43515. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  43516. case RGBA_BPTC_Format:
  43517. case RGB_BPTC_SIGNED_Format:
  43518. case RGB_BPTC_UNSIGNED_Format:
  43519. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43520. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  43521. case RED_RGTC1_Format:
  43522. case SIGNED_RED_RGTC1_Format:
  43523. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  43524. case RED_GREEN_RGTC2_Format:
  43525. case SIGNED_RED_GREEN_RGTC2_Format:
  43526. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43527. }
  43528. throw new Error(
  43529. `Unable to determine texture byte length for ${format} format.`,
  43530. );
  43531. }
  43532. function getTextureTypeByteLength( type ) {
  43533. switch ( type ) {
  43534. case UnsignedByteType:
  43535. case ByteType:
  43536. return { byteLength: 1, components: 1 };
  43537. case UnsignedShortType:
  43538. case ShortType:
  43539. case HalfFloatType:
  43540. return { byteLength: 2, components: 1 };
  43541. case UnsignedShort4444Type:
  43542. case UnsignedShort5551Type:
  43543. return { byteLength: 2, components: 4 };
  43544. case UnsignedIntType:
  43545. case IntType:
  43546. case FloatType:
  43547. return { byteLength: 4, components: 1 };
  43548. case UnsignedInt5999Type:
  43549. case UnsignedInt101111Type:
  43550. return { byteLength: 4, components: 3 };
  43551. }
  43552. throw new Error( `THREE.TextureUtils: Unknown texture type ${type}.` );
  43553. }
  43554. /**
  43555. * A class containing utility functions for textures.
  43556. *
  43557. * @hideconstructor
  43558. */
  43559. class TextureUtils {
  43560. /**
  43561. * Scales the texture as large as possible within its surface without cropping
  43562. * or stretching the texture. The method preserves the original aspect ratio of
  43563. * the texture. Akin to CSS `object-fit: contain`
  43564. *
  43565. * @param {Texture} texture - The texture.
  43566. * @param {number} aspect - The texture's aspect ratio.
  43567. * @return {Texture} The updated texture.
  43568. */
  43569. static contain( texture, aspect ) {
  43570. return contain( texture, aspect );
  43571. }
  43572. /**
  43573. * Scales the texture to the smallest possible size to fill the surface, leaving
  43574. * no empty space. The method preserves the original aspect ratio of the texture.
  43575. * Akin to CSS `object-fit: cover`.
  43576. *
  43577. * @param {Texture} texture - The texture.
  43578. * @param {number} aspect - The texture's aspect ratio.
  43579. * @return {Texture} The updated texture.
  43580. */
  43581. static cover( texture, aspect ) {
  43582. return cover( texture, aspect );
  43583. }
  43584. /**
  43585. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43586. *
  43587. * @param {Texture} texture - The texture.
  43588. * @return {Texture} The updated texture.
  43589. */
  43590. static fill( texture ) {
  43591. return fill( texture );
  43592. }
  43593. /**
  43594. * Determines how many bytes must be used to represent the texture.
  43595. *
  43596. * @param {number} width - The width of the texture.
  43597. * @param {number} height - The height of the texture.
  43598. * @param {number} format - The texture's format.
  43599. * @param {number} type - The texture's type.
  43600. * @return {number} The byte length.
  43601. */
  43602. static getByteLength( width, height, format, type ) {
  43603. return getByteLength( width, height, format, type );
  43604. }
  43605. }
  43606. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43607. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43608. revision: REVISION,
  43609. } } ) );
  43610. }
  43611. if ( typeof window !== 'undefined' ) {
  43612. if ( window.__THREE__ ) {
  43613. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43614. } else {
  43615. window.__THREE__ = REVISION;
  43616. }
  43617. }
  43618. 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号