three.core.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '185dev';
  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. const _edge1 = /*@__PURE__*/ new Vector3();
  16683. const _edge2 = /*@__PURE__*/ new Vector3();
  16684. const _normal$1 = /*@__PURE__*/ new Vector3();
  16685. /**
  16686. * A ray that emits from an origin in a certain direction. The class is used by
  16687. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  16688. * mouse picking (working out what objects in the 3D space the mouse is over)
  16689. * amongst other things.
  16690. */
  16691. class Ray {
  16692. /**
  16693. * Constructs a new ray.
  16694. *
  16695. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  16696. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  16697. */
  16698. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  16699. /**
  16700. * The origin of the ray.
  16701. *
  16702. * @type {Vector3}
  16703. */
  16704. this.origin = origin;
  16705. /**
  16706. * The (normalized) direction of the ray.
  16707. *
  16708. * @type {Vector3}
  16709. */
  16710. this.direction = direction;
  16711. }
  16712. /**
  16713. * Sets the ray's components by copying the given values.
  16714. *
  16715. * @param {Vector3} origin - The origin.
  16716. * @param {Vector3} direction - The direction.
  16717. * @return {Ray} A reference to this ray.
  16718. */
  16719. set( origin, direction ) {
  16720. this.origin.copy( origin );
  16721. this.direction.copy( direction );
  16722. return this;
  16723. }
  16724. /**
  16725. * Copies the values of the given ray to this instance.
  16726. *
  16727. * @param {Ray} ray - The ray to copy.
  16728. * @return {Ray} A reference to this ray.
  16729. */
  16730. copy( ray ) {
  16731. this.origin.copy( ray.origin );
  16732. this.direction.copy( ray.direction );
  16733. return this;
  16734. }
  16735. /**
  16736. * Returns a vector that is located at a given distance along this ray.
  16737. *
  16738. * @param {number} t - The distance along the ray to retrieve a position for.
  16739. * @param {Vector3} target - The target vector that is used to store the method's result.
  16740. * @return {Vector3} A position on the ray.
  16741. */
  16742. at( t, target ) {
  16743. return target.copy( this.origin ).addScaledVector( this.direction, t );
  16744. }
  16745. /**
  16746. * Adjusts the direction of the ray to point at the given vector in world space.
  16747. *
  16748. * @param {Vector3} v - The target position.
  16749. * @return {Ray} A reference to this ray.
  16750. */
  16751. lookAt( v ) {
  16752. this.direction.copy( v ).sub( this.origin ).normalize();
  16753. return this;
  16754. }
  16755. /**
  16756. * Shift the origin of this ray along its direction by the given distance.
  16757. *
  16758. * @param {number} t - The distance along the ray to interpolate.
  16759. * @return {Ray} A reference to this ray.
  16760. */
  16761. recast( t ) {
  16762. this.origin.copy( this.at( t, _vector$7 ) );
  16763. return this;
  16764. }
  16765. /**
  16766. * Returns the point along this ray that is closest to the given point.
  16767. *
  16768. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  16769. * @param {Vector3} target - The target vector that is used to store the method's result.
  16770. * @return {Vector3} The closest point on this ray.
  16771. */
  16772. closestPointToPoint( point, target ) {
  16773. target.subVectors( point, this.origin );
  16774. const directionDistance = target.dot( this.direction );
  16775. if ( directionDistance < 0 ) {
  16776. return target.copy( this.origin );
  16777. }
  16778. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16779. }
  16780. /**
  16781. * Returns the distance of the closest approach between this ray and the given point.
  16782. *
  16783. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16784. * @return {number} The distance.
  16785. */
  16786. distanceToPoint( point ) {
  16787. return Math.sqrt( this.distanceSqToPoint( point ) );
  16788. }
  16789. /**
  16790. * Returns the squared distance of the closest approach between this ray and the given point.
  16791. *
  16792. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16793. * @return {number} The squared distance.
  16794. */
  16795. distanceSqToPoint( point ) {
  16796. const directionDistance = _vector$7.subVectors( point, this.origin ).dot( this.direction );
  16797. // point behind the ray
  16798. if ( directionDistance < 0 ) {
  16799. return this.origin.distanceToSquared( point );
  16800. }
  16801. _vector$7.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16802. return _vector$7.distanceToSquared( point );
  16803. }
  16804. /**
  16805. * Returns the squared distance between this ray and the given line segment.
  16806. *
  16807. * @param {Vector3} v0 - The start point of the line segment.
  16808. * @param {Vector3} v1 - The end point of the line segment.
  16809. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  16810. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  16811. * @return {number} The squared distance.
  16812. */
  16813. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  16814. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  16815. // It returns the min distance between the ray and the segment
  16816. // defined by v0 and v1
  16817. // It can also set two optional targets :
  16818. // - The closest point on the ray
  16819. // - The closest point on the segment
  16820. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  16821. _segDir.copy( v1 ).sub( v0 ).normalize();
  16822. _diff.copy( this.origin ).sub( _segCenter );
  16823. const segExtent = v0.distanceTo( v1 ) * 0.5;
  16824. const a01 = - this.direction.dot( _segDir );
  16825. const b0 = _diff.dot( this.direction );
  16826. const b1 = - _diff.dot( _segDir );
  16827. const c = _diff.lengthSq();
  16828. const det = Math.abs( 1 - a01 * a01 );
  16829. let s0, s1, sqrDist, extDet;
  16830. if ( det > 0 ) {
  16831. // The ray and segment are not parallel.
  16832. s0 = a01 * b1 - b0;
  16833. s1 = a01 * b0 - b1;
  16834. extDet = segExtent * det;
  16835. if ( s0 >= 0 ) {
  16836. if ( s1 >= - extDet ) {
  16837. if ( s1 <= extDet ) {
  16838. // region 0
  16839. // Minimum at interior points of ray and segment.
  16840. const invDet = 1 / det;
  16841. s0 *= invDet;
  16842. s1 *= invDet;
  16843. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  16844. } else {
  16845. // region 1
  16846. s1 = segExtent;
  16847. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16848. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16849. }
  16850. } else {
  16851. // region 5
  16852. s1 = - segExtent;
  16853. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16854. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16855. }
  16856. } else {
  16857. if ( s1 <= - extDet ) {
  16858. // region 4
  16859. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  16860. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16861. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16862. } else if ( s1 <= extDet ) {
  16863. // region 3
  16864. s0 = 0;
  16865. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16866. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  16867. } else {
  16868. // region 2
  16869. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  16870. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16871. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16872. }
  16873. }
  16874. } else {
  16875. // Ray and segment are parallel.
  16876. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  16877. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16878. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16879. }
  16880. if ( optionalPointOnRay ) {
  16881. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  16882. }
  16883. if ( optionalPointOnSegment ) {
  16884. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  16885. }
  16886. return sqrDist;
  16887. }
  16888. /**
  16889. * Intersects this ray with the given sphere, returning the intersection
  16890. * point or `null` if there is no intersection.
  16891. *
  16892. * @param {Sphere} sphere - The sphere to intersect.
  16893. * @param {Vector3} target - The target vector that is used to store the method's result.
  16894. * @return {?Vector3} The intersection point.
  16895. */
  16896. intersectSphere( sphere, target ) {
  16897. _vector$7.subVectors( sphere.center, this.origin );
  16898. const tca = _vector$7.dot( this.direction );
  16899. const d2 = _vector$7.dot( _vector$7 ) - tca * tca;
  16900. const radius2 = sphere.radius * sphere.radius;
  16901. if ( d2 > radius2 ) return null;
  16902. const thc = Math.sqrt( radius2 - d2 );
  16903. // t0 = first intersect point - entrance on front of sphere
  16904. const t0 = tca - thc;
  16905. // t1 = second intersect point - exit point on back of sphere
  16906. const t1 = tca + thc;
  16907. // test to see if t1 is behind the ray - if so, return null
  16908. if ( t1 < 0 ) return null;
  16909. // test to see if t0 is behind the ray:
  16910. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  16911. // in order to always return an intersect point that is in front of the ray.
  16912. if ( t0 < 0 ) return this.at( t1, target );
  16913. // else t0 is in front of the ray, so return the first collision point scaled by t0
  16914. return this.at( t0, target );
  16915. }
  16916. /**
  16917. * Returns `true` if this ray intersects with the given sphere.
  16918. *
  16919. * @param {Sphere} sphere - The sphere to intersect.
  16920. * @return {boolean} Whether this ray intersects with the given sphere or not.
  16921. */
  16922. intersectsSphere( sphere ) {
  16923. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  16924. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  16925. }
  16926. /**
  16927. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  16928. * does not intersect with the plane.
  16929. *
  16930. * @param {Plane} plane - The plane to compute the distance to.
  16931. * @return {?number} Whether this ray intersects with the given sphere or not.
  16932. */
  16933. distanceToPlane( plane ) {
  16934. const denominator = plane.normal.dot( this.direction );
  16935. if ( denominator === 0 ) {
  16936. // line is coplanar, return origin
  16937. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  16938. return 0;
  16939. }
  16940. // Null is preferable to undefined since undefined means.... it is undefined
  16941. return null;
  16942. }
  16943. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  16944. // Return if the ray never intersects the plane
  16945. return t >= 0 ? t : null;
  16946. }
  16947. /**
  16948. * Intersects this ray with the given plane, returning the intersection
  16949. * point or `null` if there is no intersection.
  16950. *
  16951. * @param {Plane} plane - The plane to intersect.
  16952. * @param {Vector3} target - The target vector that is used to store the method's result.
  16953. * @return {?Vector3} The intersection point.
  16954. */
  16955. intersectPlane( plane, target ) {
  16956. const t = this.distanceToPlane( plane );
  16957. if ( t === null ) {
  16958. return null;
  16959. }
  16960. return this.at( t, target );
  16961. }
  16962. /**
  16963. * Returns `true` if this ray intersects with the given plane.
  16964. *
  16965. * @param {Plane} plane - The plane to intersect.
  16966. * @return {boolean} Whether this ray intersects with the given plane or not.
  16967. */
  16968. intersectsPlane( plane ) {
  16969. // check if the ray lies on the plane first
  16970. const distToPoint = plane.distanceToPoint( this.origin );
  16971. if ( distToPoint === 0 ) {
  16972. return true;
  16973. }
  16974. const denominator = plane.normal.dot( this.direction );
  16975. if ( denominator * distToPoint < 0 ) {
  16976. return true;
  16977. }
  16978. // ray origin is behind the plane (and is pointing behind it)
  16979. return false;
  16980. }
  16981. /**
  16982. * Intersects this ray with the given bounding box, returning the intersection
  16983. * point or `null` if there is no intersection.
  16984. *
  16985. * @param {Box3} box - The box to intersect.
  16986. * @param {Vector3} target - The target vector that is used to store the method's result.
  16987. * @return {?Vector3} The intersection point.
  16988. */
  16989. intersectBox( box, target ) {
  16990. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  16991. const invdirx = 1 / this.direction.x,
  16992. invdiry = 1 / this.direction.y,
  16993. invdirz = 1 / this.direction.z;
  16994. const origin = this.origin;
  16995. if ( invdirx >= 0 ) {
  16996. tmin = ( box.min.x - origin.x ) * invdirx;
  16997. tmax = ( box.max.x - origin.x ) * invdirx;
  16998. } else {
  16999. tmin = ( box.max.x - origin.x ) * invdirx;
  17000. tmax = ( box.min.x - origin.x ) * invdirx;
  17001. }
  17002. if ( invdiry >= 0 ) {
  17003. tymin = ( box.min.y - origin.y ) * invdiry;
  17004. tymax = ( box.max.y - origin.y ) * invdiry;
  17005. } else {
  17006. tymin = ( box.max.y - origin.y ) * invdiry;
  17007. tymax = ( box.min.y - origin.y ) * invdiry;
  17008. }
  17009. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  17010. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  17011. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  17012. if ( invdirz >= 0 ) {
  17013. tzmin = ( box.min.z - origin.z ) * invdirz;
  17014. tzmax = ( box.max.z - origin.z ) * invdirz;
  17015. } else {
  17016. tzmin = ( box.max.z - origin.z ) * invdirz;
  17017. tzmax = ( box.min.z - origin.z ) * invdirz;
  17018. }
  17019. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  17020. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  17021. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  17022. //return point closest to the ray (positive side)
  17023. if ( tmax < 0 ) return null;
  17024. return this.at( tmin >= 0 ? tmin : tmax, target );
  17025. }
  17026. /**
  17027. * Returns `true` if this ray intersects with the given box.
  17028. *
  17029. * @param {Box3} box - The box to intersect.
  17030. * @return {boolean} Whether this ray intersects with the given box or not.
  17031. */
  17032. intersectsBox( box ) {
  17033. return this.intersectBox( box, _vector$7 ) !== null;
  17034. }
  17035. /**
  17036. * Intersects this ray with the given triangle, returning the intersection
  17037. * point or `null` if there is no intersection.
  17038. *
  17039. * @param {Vector3} a - The first vertex of the triangle.
  17040. * @param {Vector3} b - The second vertex of the triangle.
  17041. * @param {Vector3} c - The third vertex of the triangle.
  17042. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  17043. * @param {Vector3} target - The target vector that is used to store the method's result.
  17044. * @return {?Vector3} The intersection point.
  17045. */
  17046. intersectTriangle( a, b, c, backfaceCulling, target ) {
  17047. // Compute the offset origin, edges, and normal.
  17048. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  17049. _edge1.subVectors( b, a );
  17050. _edge2.subVectors( c, a );
  17051. _normal$1.crossVectors( _edge1, _edge2 );
  17052. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  17053. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  17054. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  17055. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  17056. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  17057. let DdN = this.direction.dot( _normal$1 );
  17058. let sign;
  17059. if ( DdN > 0 ) {
  17060. if ( backfaceCulling ) return null;
  17061. sign = 1;
  17062. } else if ( DdN < 0 ) {
  17063. sign = -1;
  17064. DdN = - DdN;
  17065. } else {
  17066. return null;
  17067. }
  17068. _diff.subVectors( this.origin, a );
  17069. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  17070. // b1 < 0, no intersection
  17071. if ( DdQxE2 < 0 ) {
  17072. return null;
  17073. }
  17074. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  17075. // b2 < 0, no intersection
  17076. if ( DdE1xQ < 0 ) {
  17077. return null;
  17078. }
  17079. // b1+b2 > 1, no intersection
  17080. if ( DdQxE2 + DdE1xQ > DdN ) {
  17081. return null;
  17082. }
  17083. // Line intersects triangle, check if ray does.
  17084. const QdN = - sign * _diff.dot( _normal$1 );
  17085. // t < 0, no intersection
  17086. if ( QdN < 0 ) {
  17087. return null;
  17088. }
  17089. // Ray intersects triangle.
  17090. return this.at( QdN / DdN, target );
  17091. }
  17092. /**
  17093. * Transforms this ray with the given 4x4 transformation matrix.
  17094. *
  17095. * @param {Matrix4} matrix4 - The transformation matrix.
  17096. * @return {Ray} A reference to this ray.
  17097. */
  17098. applyMatrix4( matrix4 ) {
  17099. this.origin.applyMatrix4( matrix4 );
  17100. this.direction.transformDirection( matrix4 );
  17101. return this;
  17102. }
  17103. /**
  17104. * Returns `true` if this ray is equal with the given one.
  17105. *
  17106. * @param {Ray} ray - The ray to test for equality.
  17107. * @return {boolean} Whether this ray is equal with the given one.
  17108. */
  17109. equals( ray ) {
  17110. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  17111. }
  17112. /**
  17113. * Returns a new ray with copied values from this instance.
  17114. *
  17115. * @return {Ray} A clone of this instance.
  17116. */
  17117. clone() {
  17118. return new this.constructor().copy( this );
  17119. }
  17120. }
  17121. /**
  17122. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  17123. *
  17124. * This material is not affected by lights.
  17125. *
  17126. * @augments Material
  17127. * @demo scenes/material-browser.html#MeshBasicMaterial
  17128. */
  17129. class MeshBasicMaterial extends Material {
  17130. /**
  17131. * Constructs a new mesh basic material.
  17132. *
  17133. * @param {Object} [parameters] - An object with one or more properties
  17134. * defining the material's appearance. Any property of the material
  17135. * (including any property from inherited materials) can be passed
  17136. * in here. Color values can be passed any type of value accepted
  17137. * by {@link Color#set}.
  17138. */
  17139. constructor( parameters ) {
  17140. super();
  17141. /**
  17142. * This flag can be used for type testing.
  17143. *
  17144. * @type {boolean}
  17145. * @readonly
  17146. * @default true
  17147. */
  17148. this.isMeshBasicMaterial = true;
  17149. this.type = 'MeshBasicMaterial';
  17150. /**
  17151. * Color of the material.
  17152. *
  17153. * @type {Color}
  17154. * @default (1,1,1)
  17155. */
  17156. this.color = new Color( 0xffffff ); // diffuse
  17157. /**
  17158. * The color map. May optionally include an alpha channel, typically combined
  17159. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17160. * color is modulated by the diffuse `color`.
  17161. *
  17162. * `map` represents color data, and the texture must be assigned a
  17163. * {@link Texture#colorSpace}. Most `map` textures set
  17164. * `texture.colorSpace = SRGBColorSpace`.
  17165. *
  17166. * @type {?Texture}
  17167. * @default null
  17168. */
  17169. this.map = null;
  17170. /**
  17171. * The light map. Requires a second set of UVs.
  17172. *
  17173. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  17174. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  17175. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  17176. * such as `.exr` or `.hdr`.
  17177. *
  17178. * @type {?Texture}
  17179. * @default null
  17180. */
  17181. this.lightMap = null;
  17182. /**
  17183. * Intensity of the baked light.
  17184. *
  17185. * @type {number}
  17186. * @default 1
  17187. */
  17188. this.lightMapIntensity = 1.0;
  17189. /**
  17190. * The red channel of this texture is used as the ambient occlusion map.
  17191. * Requires a second set of UVs.
  17192. *
  17193. * `aoMap` represents non-color data. Any texture assigned must have
  17194. * `texture.colorSpace = NoColorSpace` (default).
  17195. *
  17196. * @type {?Texture}
  17197. * @default null
  17198. */
  17199. this.aoMap = null;
  17200. /**
  17201. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  17202. * disables ambient occlusion. Where intensity is `1` and the AO map's
  17203. * red channel is also `1`, ambient light is fully occluded on a surface.
  17204. *
  17205. * @type {number}
  17206. * @default 1
  17207. */
  17208. this.aoMapIntensity = 1.0;
  17209. /**
  17210. * Specular map used by the material.
  17211. *
  17212. * `specularMap` represents color data, and the texture must be assigned a
  17213. * {@link Texture#colorSpace}. Most `specularMap` textures set
  17214. * `texture.colorSpace = SRGBColorSpace`.
  17215. *
  17216. * @type {?Texture}
  17217. * @default null
  17218. */
  17219. this.specularMap = null;
  17220. /**
  17221. * The alpha map is a grayscale texture that controls the opacity across the
  17222. * surface (black: fully transparent; white: fully opaque).
  17223. *
  17224. * Only the color of the texture is used, ignoring the alpha channel if one
  17225. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17226. * when sampling this texture due to the extra bit of precision provided for
  17227. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17228. * luminance/alpha textures will also still work as expected.
  17229. *
  17230. * `alphaMap` represents non-color data. Any texture assigned must have
  17231. * `texture.colorSpace = NoColorSpace` (default).
  17232. *
  17233. * @type {?Texture}
  17234. * @default null
  17235. */
  17236. this.alphaMap = null;
  17237. /**
  17238. * The environment map.
  17239. *
  17240. * `envMap` represents luminance data, and the texture must be assigned
  17241. * a {@link Texture#colorSpace}. Most `envMap` textures set
  17242. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  17243. * such as `.exr` or `.hdr`.
  17244. *
  17245. * @type {?Texture}
  17246. * @default null
  17247. */
  17248. this.envMap = null;
  17249. /**
  17250. * The rotation of the environment map in radians.
  17251. *
  17252. * @type {Euler}
  17253. * @default (0,0,0)
  17254. */
  17255. this.envMapRotation = new Euler();
  17256. /**
  17257. * How to combine the result of the surface's color with the environment map, if any.
  17258. *
  17259. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  17260. * blend between the two colors.
  17261. *
  17262. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  17263. * @default MultiplyOperation
  17264. */
  17265. this.combine = MultiplyOperation;
  17266. /**
  17267. * How much the environment map affects the surface.
  17268. * The valid range is between `0` (no reflections) and `1` (full reflections).
  17269. *
  17270. * @type {number}
  17271. * @default 1
  17272. */
  17273. this.reflectivity = 1;
  17274. /**
  17275. * The index of refraction (IOR) of air (approximately 1) divided by the
  17276. * index of refraction of the material. It is used with environment mapping
  17277. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  17278. * The refraction ratio should not exceed `1`.
  17279. *
  17280. * @type {number}
  17281. * @default 0.98
  17282. */
  17283. this.refractionRatio = 0.98;
  17284. /**
  17285. * Renders the geometry as a wireframe.
  17286. *
  17287. * @type {boolean}
  17288. * @default false
  17289. */
  17290. this.wireframe = false;
  17291. /**
  17292. * Controls the thickness of the wireframe.
  17293. *
  17294. * Can only be used with {@link SVGRenderer}.
  17295. *
  17296. * @type {number}
  17297. * @default 1
  17298. */
  17299. this.wireframeLinewidth = 1;
  17300. /**
  17301. * Defines appearance of wireframe ends.
  17302. *
  17303. * Can only be used with {@link SVGRenderer}.
  17304. *
  17305. * @type {('round'|'bevel'|'miter')}
  17306. * @default 'round'
  17307. */
  17308. this.wireframeLinecap = 'round';
  17309. /**
  17310. * Defines appearance of wireframe joints.
  17311. *
  17312. * Can only be used with {@link SVGRenderer}.
  17313. *
  17314. * @type {('round'|'bevel'|'miter')}
  17315. * @default 'round'
  17316. */
  17317. this.wireframeLinejoin = 'round';
  17318. /**
  17319. * Whether the material is affected by fog or not.
  17320. *
  17321. * @type {boolean}
  17322. * @default true
  17323. */
  17324. this.fog = true;
  17325. this.setValues( parameters );
  17326. }
  17327. copy( source ) {
  17328. super.copy( source );
  17329. this.color.copy( source.color );
  17330. this.map = source.map;
  17331. this.lightMap = source.lightMap;
  17332. this.lightMapIntensity = source.lightMapIntensity;
  17333. this.aoMap = source.aoMap;
  17334. this.aoMapIntensity = source.aoMapIntensity;
  17335. this.specularMap = source.specularMap;
  17336. this.alphaMap = source.alphaMap;
  17337. this.envMap = source.envMap;
  17338. this.envMapRotation.copy( source.envMapRotation );
  17339. this.combine = source.combine;
  17340. this.reflectivity = source.reflectivity;
  17341. this.refractionRatio = source.refractionRatio;
  17342. this.wireframe = source.wireframe;
  17343. this.wireframeLinewidth = source.wireframeLinewidth;
  17344. this.wireframeLinecap = source.wireframeLinecap;
  17345. this.wireframeLinejoin = source.wireframeLinejoin;
  17346. this.fog = source.fog;
  17347. return this;
  17348. }
  17349. }
  17350. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  17351. const _ray$3 = /*@__PURE__*/ new Ray();
  17352. const _sphere$6 = /*@__PURE__*/ new Sphere();
  17353. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  17354. const _vA = /*@__PURE__*/ new Vector3();
  17355. const _vB = /*@__PURE__*/ new Vector3();
  17356. const _vC = /*@__PURE__*/ new Vector3();
  17357. const _tempA = /*@__PURE__*/ new Vector3();
  17358. const _morphA = /*@__PURE__*/ new Vector3();
  17359. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  17360. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  17361. /**
  17362. * Class representing triangular polygon mesh based objects.
  17363. *
  17364. * ```js
  17365. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  17366. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17367. * const mesh = new THREE.Mesh( geometry, material );
  17368. * scene.add( mesh );
  17369. * ```
  17370. *
  17371. * @augments Object3D
  17372. */
  17373. class Mesh extends Object3D {
  17374. /**
  17375. * Constructs a new mesh.
  17376. *
  17377. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17378. * @param {Material|Array<Material>} [material] - The mesh material.
  17379. */
  17380. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  17381. super();
  17382. /**
  17383. * This flag can be used for type testing.
  17384. *
  17385. * @type {boolean}
  17386. * @readonly
  17387. * @default true
  17388. */
  17389. this.isMesh = true;
  17390. this.type = 'Mesh';
  17391. /**
  17392. * The mesh geometry.
  17393. *
  17394. * @type {BufferGeometry}
  17395. */
  17396. this.geometry = geometry;
  17397. /**
  17398. * The mesh material.
  17399. *
  17400. * @type {Material|Array<Material>}
  17401. * @default MeshBasicMaterial
  17402. */
  17403. this.material = material;
  17404. /**
  17405. * A dictionary representing the morph targets in the geometry. The key is the
  17406. * morph targets name, the value its attribute index. This member is `undefined`
  17407. * by default and only set when morph targets are detected in the geometry.
  17408. *
  17409. * @type {Object<string,number>|undefined}
  17410. * @default undefined
  17411. */
  17412. this.morphTargetDictionary = undefined;
  17413. /**
  17414. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  17415. * is applied. This member is `undefined` by default and only set when morph targets are
  17416. * detected in the geometry.
  17417. *
  17418. * @type {Array<number>|undefined}
  17419. * @default undefined
  17420. */
  17421. this.morphTargetInfluences = undefined;
  17422. /**
  17423. * The number of instances of this mesh.
  17424. * Can only be used with {@link WebGPURenderer}.
  17425. *
  17426. * @type {number}
  17427. * @default 1
  17428. */
  17429. this.count = 1;
  17430. this.updateMorphTargets();
  17431. }
  17432. copy( source, recursive ) {
  17433. super.copy( source, recursive );
  17434. if ( source.morphTargetInfluences !== undefined ) {
  17435. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  17436. }
  17437. if ( source.morphTargetDictionary !== undefined ) {
  17438. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  17439. }
  17440. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  17441. this.geometry = source.geometry;
  17442. return this;
  17443. }
  17444. /**
  17445. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  17446. * to make sure existing morph targets can influence this 3D object.
  17447. */
  17448. updateMorphTargets() {
  17449. const geometry = this.geometry;
  17450. const morphAttributes = geometry.morphAttributes;
  17451. const keys = Object.keys( morphAttributes );
  17452. if ( keys.length > 0 ) {
  17453. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17454. if ( morphAttribute !== undefined ) {
  17455. this.morphTargetInfluences = [];
  17456. this.morphTargetDictionary = {};
  17457. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17458. const name = morphAttribute[ m ].name || String( m );
  17459. this.morphTargetInfluences.push( 0 );
  17460. this.morphTargetDictionary[ name ] = m;
  17461. }
  17462. }
  17463. }
  17464. }
  17465. /**
  17466. * Returns the local-space position of the vertex at the given index, taking into
  17467. * account the current animation state of both morph targets and skinning.
  17468. *
  17469. * @param {number} index - The vertex index.
  17470. * @param {Vector3} target - The target object that is used to store the method's result.
  17471. * @return {Vector3} The vertex position in local space.
  17472. */
  17473. getVertexPosition( index, target ) {
  17474. const geometry = this.geometry;
  17475. const position = geometry.attributes.position;
  17476. const morphPosition = geometry.morphAttributes.position;
  17477. const morphTargetsRelative = geometry.morphTargetsRelative;
  17478. target.fromBufferAttribute( position, index );
  17479. const morphInfluences = this.morphTargetInfluences;
  17480. if ( morphPosition && morphInfluences ) {
  17481. _morphA.set( 0, 0, 0 );
  17482. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  17483. const influence = morphInfluences[ i ];
  17484. const morphAttribute = morphPosition[ i ];
  17485. if ( influence === 0 ) continue;
  17486. _tempA.fromBufferAttribute( morphAttribute, index );
  17487. if ( morphTargetsRelative ) {
  17488. _morphA.addScaledVector( _tempA, influence );
  17489. } else {
  17490. _morphA.addScaledVector( _tempA.sub( target ), influence );
  17491. }
  17492. }
  17493. target.add( _morphA );
  17494. }
  17495. return target;
  17496. }
  17497. /**
  17498. * Computes intersection points between a casted ray and this line.
  17499. *
  17500. * @param {Raycaster} raycaster - The raycaster.
  17501. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17502. */
  17503. raycast( raycaster, intersects ) {
  17504. const geometry = this.geometry;
  17505. const material = this.material;
  17506. const matrixWorld = this.matrixWorld;
  17507. if ( material === undefined ) return;
  17508. // test with bounding sphere in world space
  17509. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17510. _sphere$6.copy( geometry.boundingSphere );
  17511. _sphere$6.applyMatrix4( matrixWorld );
  17512. // check distance from ray origin to bounding sphere
  17513. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  17514. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  17515. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  17516. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  17517. }
  17518. // convert ray to local space of mesh
  17519. _inverseMatrix$3.copy( matrixWorld ).invert();
  17520. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  17521. // test with bounding box in local space
  17522. if ( geometry.boundingBox !== null ) {
  17523. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  17524. }
  17525. // test for intersections with geometry
  17526. this._computeIntersections( raycaster, intersects, _ray$3 );
  17527. }
  17528. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  17529. let intersection;
  17530. const geometry = this.geometry;
  17531. const material = this.material;
  17532. const index = geometry.index;
  17533. const position = geometry.attributes.position;
  17534. const uv = geometry.attributes.uv;
  17535. const uv1 = geometry.attributes.uv1;
  17536. const normal = geometry.attributes.normal;
  17537. const groups = geometry.groups;
  17538. const drawRange = geometry.drawRange;
  17539. if ( index !== null ) {
  17540. // indexed buffer geometry
  17541. if ( Array.isArray( material ) ) {
  17542. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17543. const group = groups[ i ];
  17544. const groupMaterial = material[ group.materialIndex ];
  17545. const start = Math.max( group.start, drawRange.start );
  17546. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17547. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17548. const a = index.getX( j );
  17549. const b = index.getX( j + 1 );
  17550. const c = index.getX( j + 2 );
  17551. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17552. if ( intersection ) {
  17553. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  17554. intersection.face.materialIndex = group.materialIndex;
  17555. intersects.push( intersection );
  17556. }
  17557. }
  17558. }
  17559. } else {
  17560. const start = Math.max( 0, drawRange.start );
  17561. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17562. for ( let i = start, il = end; i < il; i += 3 ) {
  17563. const a = index.getX( i );
  17564. const b = index.getX( i + 1 );
  17565. const c = index.getX( i + 2 );
  17566. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17567. if ( intersection ) {
  17568. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  17569. intersects.push( intersection );
  17570. }
  17571. }
  17572. }
  17573. } else if ( position !== undefined ) {
  17574. // non-indexed buffer geometry
  17575. if ( Array.isArray( material ) ) {
  17576. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17577. const group = groups[ i ];
  17578. const groupMaterial = material[ group.materialIndex ];
  17579. const start = Math.max( group.start, drawRange.start );
  17580. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17581. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17582. const a = j;
  17583. const b = j + 1;
  17584. const c = j + 2;
  17585. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17586. if ( intersection ) {
  17587. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  17588. intersection.face.materialIndex = group.materialIndex;
  17589. intersects.push( intersection );
  17590. }
  17591. }
  17592. }
  17593. } else {
  17594. const start = Math.max( 0, drawRange.start );
  17595. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  17596. for ( let i = start, il = end; i < il; i += 3 ) {
  17597. const a = i;
  17598. const b = i + 1;
  17599. const c = i + 2;
  17600. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17601. if ( intersection ) {
  17602. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  17603. intersects.push( intersection );
  17604. }
  17605. }
  17606. }
  17607. }
  17608. }
  17609. }
  17610. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  17611. let intersect;
  17612. if ( material.side === BackSide ) {
  17613. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  17614. } else {
  17615. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  17616. }
  17617. if ( intersect === null ) return null;
  17618. _intersectionPointWorld.copy( point );
  17619. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  17620. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  17621. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  17622. return {
  17623. distance: distance,
  17624. point: _intersectionPointWorld.clone(),
  17625. object: object
  17626. };
  17627. }
  17628. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  17629. object.getVertexPosition( a, _vA );
  17630. object.getVertexPosition( b, _vB );
  17631. object.getVertexPosition( c, _vC );
  17632. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  17633. if ( intersection ) {
  17634. const barycoord = new Vector3();
  17635. Triangle.getBarycoord( _intersectionPoint, _vA, _vB, _vC, barycoord );
  17636. if ( uv ) {
  17637. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  17638. }
  17639. if ( uv1 ) {
  17640. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  17641. }
  17642. if ( normal ) {
  17643. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  17644. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  17645. intersection.normal.multiplyScalar( -1 );
  17646. }
  17647. }
  17648. const face = {
  17649. a: a,
  17650. b: b,
  17651. c: c,
  17652. normal: new Vector3(),
  17653. materialIndex: 0
  17654. };
  17655. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  17656. intersection.face = face;
  17657. intersection.barycoord = barycoord;
  17658. }
  17659. return intersection;
  17660. }
  17661. const _baseVector = /*@__PURE__*/ new Vector4();
  17662. const _skinIndex = /*@__PURE__*/ new Vector4();
  17663. const _skinWeight = /*@__PURE__*/ new Vector4();
  17664. const _vector4 = /*@__PURE__*/ new Vector4();
  17665. const _matrix4 = /*@__PURE__*/ new Matrix4();
  17666. const _vertex = /*@__PURE__*/ new Vector3();
  17667. const _sphere$5 = /*@__PURE__*/ new Sphere();
  17668. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  17669. const _ray$2 = /*@__PURE__*/ new Ray();
  17670. /**
  17671. * A mesh that has a {@link Skeleton} that can then be used to animate the
  17672. * vertices of the geometry with skinning/skeleton animation.
  17673. *
  17674. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  17675. * as buffer attributes in its geometry. These attribute define which bones affect a single
  17676. * vertex to a certain extend.
  17677. *
  17678. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  17679. * or {@link FBXLoader } import respective models.
  17680. *
  17681. * @augments Mesh
  17682. * @demo scenes/bones-browser.html
  17683. */
  17684. class SkinnedMesh extends Mesh {
  17685. /**
  17686. * Constructs a new skinned mesh.
  17687. *
  17688. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17689. * @param {Material|Array<Material>} [material] - The mesh material.
  17690. */
  17691. constructor( geometry, material ) {
  17692. super( geometry, material );
  17693. /**
  17694. * This flag can be used for type testing.
  17695. *
  17696. * @type {boolean}
  17697. * @readonly
  17698. * @default true
  17699. */
  17700. this.isSkinnedMesh = true;
  17701. this.type = 'SkinnedMesh';
  17702. /**
  17703. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  17704. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  17705. * across multiple skinned meshes.
  17706. *
  17707. * @type {(AttachedBindMode|DetachedBindMode)}
  17708. * @default AttachedBindMode
  17709. */
  17710. this.bindMode = AttachedBindMode;
  17711. /**
  17712. * The base matrix that is used for the bound bone transforms.
  17713. *
  17714. * @type {Matrix4}
  17715. */
  17716. this.bindMatrix = new Matrix4();
  17717. /**
  17718. * The base matrix that is used for resetting the bound bone transforms.
  17719. *
  17720. * @type {Matrix4}
  17721. */
  17722. this.bindMatrixInverse = new Matrix4();
  17723. /**
  17724. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  17725. *
  17726. * @type {?Box3}
  17727. * @default null
  17728. */
  17729. this.boundingBox = null;
  17730. /**
  17731. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  17732. *
  17733. * @type {?Sphere}
  17734. * @default null
  17735. */
  17736. this.boundingSphere = null;
  17737. }
  17738. /**
  17739. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  17740. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  17741. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  17742. * the current animation state.
  17743. */
  17744. computeBoundingBox() {
  17745. const geometry = this.geometry;
  17746. if ( this.boundingBox === null ) {
  17747. this.boundingBox = new Box3();
  17748. }
  17749. this.boundingBox.makeEmpty();
  17750. const positionAttribute = geometry.getAttribute( 'position' );
  17751. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17752. this.getVertexPosition( i, _vertex );
  17753. this.boundingBox.expandByPoint( _vertex );
  17754. }
  17755. }
  17756. /**
  17757. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  17758. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  17759. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  17760. * per frame in order to reflect the current animation state.
  17761. */
  17762. computeBoundingSphere() {
  17763. const geometry = this.geometry;
  17764. if ( this.boundingSphere === null ) {
  17765. this.boundingSphere = new Sphere();
  17766. }
  17767. this.boundingSphere.makeEmpty();
  17768. const positionAttribute = geometry.getAttribute( 'position' );
  17769. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17770. this.getVertexPosition( i, _vertex );
  17771. this.boundingSphere.expandByPoint( _vertex );
  17772. }
  17773. }
  17774. copy( source, recursive ) {
  17775. super.copy( source, recursive );
  17776. this.bindMode = source.bindMode;
  17777. this.bindMatrix.copy( source.bindMatrix );
  17778. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17779. this.skeleton = source.skeleton;
  17780. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  17781. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  17782. return this;
  17783. }
  17784. raycast( raycaster, intersects ) {
  17785. const material = this.material;
  17786. const matrixWorld = this.matrixWorld;
  17787. if ( material === undefined ) return;
  17788. // test with bounding sphere in world space
  17789. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  17790. _sphere$5.copy( this.boundingSphere );
  17791. _sphere$5.applyMatrix4( matrixWorld );
  17792. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  17793. // convert ray to local space of skinned mesh
  17794. _inverseMatrix$2.copy( matrixWorld ).invert();
  17795. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  17796. // test with bounding box in local space
  17797. if ( this.boundingBox !== null ) {
  17798. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  17799. }
  17800. // test for intersections with geometry
  17801. this._computeIntersections( raycaster, intersects, _ray$2 );
  17802. }
  17803. getVertexPosition( index, target ) {
  17804. super.getVertexPosition( index, target );
  17805. this.applyBoneTransform( index, target );
  17806. return target;
  17807. }
  17808. /**
  17809. * Binds the given skeleton to the skinned mesh.
  17810. *
  17811. * @param {Skeleton} skeleton - The skeleton to bind.
  17812. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  17813. * the skinned mesh's world matrix will be used instead.
  17814. */
  17815. bind( skeleton, bindMatrix ) {
  17816. this.skeleton = skeleton;
  17817. if ( bindMatrix === undefined ) {
  17818. this.updateMatrixWorld( true );
  17819. this.skeleton.calculateInverses();
  17820. bindMatrix = this.matrixWorld;
  17821. }
  17822. this.bindMatrix.copy( bindMatrix );
  17823. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17824. }
  17825. /**
  17826. * This method sets the skinned mesh in the rest pose).
  17827. */
  17828. pose() {
  17829. this.skeleton.pose();
  17830. }
  17831. /**
  17832. * Normalizes the skin weights which are defined as a buffer attribute
  17833. * in the skinned mesh's geometry.
  17834. */
  17835. normalizeSkinWeights() {
  17836. const vector = new Vector4();
  17837. const skinWeight = this.geometry.attributes.skinWeight;
  17838. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17839. vector.fromBufferAttribute( skinWeight, i );
  17840. const scale = 1.0 / vector.manhattanLength();
  17841. if ( scale !== Infinity ) {
  17842. vector.multiplyScalar( scale );
  17843. } else {
  17844. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17845. }
  17846. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17847. }
  17848. }
  17849. updateMatrixWorld( force ) {
  17850. super.updateMatrixWorld( force );
  17851. if ( this.bindMode === AttachedBindMode ) {
  17852. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17853. } else if ( this.bindMode === DetachedBindMode ) {
  17854. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17855. } else {
  17856. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17857. }
  17858. }
  17859. /**
  17860. * Applies the bone transform associated with the given index to the given
  17861. * vector. Can be used to transform positions or direction vectors by providing
  17862. * a Vector4 with 1 or 0 in the w component respectively. Returns the updated vector.
  17863. *
  17864. * @param {number} index - The vertex index.
  17865. * @param {Vector3|Vector4} target - The target object that is used to store the method's result.
  17866. * @return {Vector3|Vector4} The updated vertex attribute data.
  17867. */
  17868. applyBoneTransform( index, target ) {
  17869. const skeleton = this.skeleton;
  17870. const geometry = this.geometry;
  17871. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17872. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17873. if ( target.isVector4 ) {
  17874. _baseVector.copy( target );
  17875. target.set( 0, 0, 0, 0 );
  17876. } else {
  17877. _baseVector.set( ...target, 1 );
  17878. target.set( 0, 0, 0 );
  17879. }
  17880. _baseVector.applyMatrix4( this.bindMatrix );
  17881. for ( let i = 0; i < 4; i ++ ) {
  17882. const weight = _skinWeight.getComponent( i );
  17883. if ( weight !== 0 ) {
  17884. const boneIndex = _skinIndex.getComponent( i );
  17885. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17886. target.addScaledVector( _vector4.copy( _baseVector ).applyMatrix4( _matrix4 ), weight );
  17887. }
  17888. }
  17889. if ( target.isVector4 ) {
  17890. // ensure the homogenous coordinate remains unchanged after vector operations
  17891. target.w = _baseVector.w;
  17892. }
  17893. return target.applyMatrix4( this.bindMatrixInverse );
  17894. }
  17895. }
  17896. /**
  17897. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  17898. * the {@link SkinnedMesh}.
  17899. *
  17900. * ```js
  17901. * const root = new THREE.Bone();
  17902. * const child = new THREE.Bone();
  17903. *
  17904. * root.add( child );
  17905. * child.position.y = 5;
  17906. * ```
  17907. *
  17908. * @augments Object3D
  17909. */
  17910. class Bone extends Object3D {
  17911. /**
  17912. * Constructs a new bone.
  17913. */
  17914. constructor() {
  17915. super();
  17916. /**
  17917. * This flag can be used for type testing.
  17918. *
  17919. * @type {boolean}
  17920. * @readonly
  17921. * @default true
  17922. */
  17923. this.isBone = true;
  17924. this.type = 'Bone';
  17925. }
  17926. }
  17927. /**
  17928. * Creates a texture directly from raw buffer data.
  17929. *
  17930. * The interpretation of the data depends on type and format: If the type is
  17931. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  17932. * texel data. If the format is `RGBAFormat`, data needs four values for
  17933. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  17934. *
  17935. * @augments Texture
  17936. */
  17937. class DataTexture extends Texture {
  17938. /**
  17939. * Constructs a new data texture.
  17940. *
  17941. * @param {?TypedArray} [data=null] - The buffer data.
  17942. * @param {number} [width=1] - The width of the texture.
  17943. * @param {number} [height=1] - The height of the texture.
  17944. * @param {number} [format=RGBAFormat] - The texture format.
  17945. * @param {number} [type=UnsignedByteType] - The texture type.
  17946. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  17947. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  17948. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  17949. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  17950. * @param {number} [minFilter=NearestFilter] - The min filter value.
  17951. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  17952. * @param {string} [colorSpace=NoColorSpace] - The color space.
  17953. */
  17954. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  17955. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  17956. /**
  17957. * This flag can be used for type testing.
  17958. *
  17959. * @type {boolean}
  17960. * @readonly
  17961. * @default true
  17962. */
  17963. this.isDataTexture = true;
  17964. /**
  17965. * The image definition of a data texture.
  17966. *
  17967. * @type {{data:TypedArray,width:number,height:number}}
  17968. */
  17969. this.image = { data: data, width: width, height: height };
  17970. /**
  17971. * Whether to generate mipmaps (if possible) for a texture.
  17972. *
  17973. * Overwritten and set to `false` by default.
  17974. *
  17975. * @type {boolean}
  17976. * @default false
  17977. */
  17978. this.generateMipmaps = false;
  17979. /**
  17980. * If set to `true`, the texture is flipped along the vertical axis when
  17981. * uploaded to the GPU.
  17982. *
  17983. * Overwritten and set to `false` by default.
  17984. *
  17985. * @type {boolean}
  17986. * @default false
  17987. */
  17988. this.flipY = false;
  17989. /**
  17990. * Specifies the alignment requirements for the start of each pixel row in memory.
  17991. *
  17992. * Overwritten and set to `1` by default.
  17993. *
  17994. * @type {boolean}
  17995. * @default 1
  17996. */
  17997. this.unpackAlignment = 1;
  17998. }
  17999. }
  18000. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18001. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18002. /**
  18003. * Class for representing the armatures in `three.js`. The skeleton
  18004. * is defined by a hierarchy of bones.
  18005. *
  18006. * ```js
  18007. * const bones = [];
  18008. *
  18009. * const shoulder = new THREE.Bone();
  18010. * const elbow = new THREE.Bone();
  18011. * const hand = new THREE.Bone();
  18012. *
  18013. * shoulder.add( elbow );
  18014. * elbow.add( hand );
  18015. *
  18016. * bones.push( shoulder , elbow, hand);
  18017. *
  18018. * shoulder.position.y = -5;
  18019. * elbow.position.y = 0;
  18020. * hand.position.y = 5;
  18021. *
  18022. * const armSkeleton = new THREE.Skeleton( bones );
  18023. * ```
  18024. */
  18025. class Skeleton {
  18026. /**
  18027. * Constructs a new skeleton.
  18028. *
  18029. * @param {Array<Bone>} [bones] - An array of bones.
  18030. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18031. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18032. */
  18033. constructor( bones = [], boneInverses = [] ) {
  18034. this.uuid = generateUUID();
  18035. /**
  18036. * An array of bones defining the skeleton.
  18037. *
  18038. * @type {Array<Bone>}
  18039. */
  18040. this.bones = bones.slice( 0 );
  18041. /**
  18042. * An array of bone inverse matrices.
  18043. *
  18044. * @type {Array<Matrix4>}
  18045. */
  18046. this.boneInverses = boneInverses;
  18047. /**
  18048. * An array buffer holding the bone data.
  18049. * Input data for {@link Skeleton#boneTexture}.
  18050. *
  18051. * @type {?Float32Array}
  18052. * @default null
  18053. */
  18054. this.boneMatrices = null;
  18055. /**
  18056. * A texture holding the bone data for use
  18057. * in the vertex shader.
  18058. *
  18059. * @type {?DataTexture}
  18060. * @default null
  18061. */
  18062. this.boneTexture = null;
  18063. this.init();
  18064. }
  18065. /**
  18066. * Initializes the skeleton. This method gets automatically called by the constructor
  18067. * but depending on how the skeleton is created it might be necessary to call this method
  18068. * manually.
  18069. */
  18070. init() {
  18071. const bones = this.bones;
  18072. const boneInverses = this.boneInverses;
  18073. this.boneMatrices = new Float32Array( bones.length * 16 );
  18074. // calculate inverse bone matrices if necessary
  18075. if ( boneInverses.length === 0 ) {
  18076. this.calculateInverses();
  18077. } else {
  18078. // handle special case
  18079. if ( bones.length !== boneInverses.length ) {
  18080. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18081. this.boneInverses = [];
  18082. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18083. this.boneInverses.push( new Matrix4() );
  18084. }
  18085. }
  18086. }
  18087. }
  18088. /**
  18089. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18090. * and fills it with new matrices.
  18091. */
  18092. calculateInverses() {
  18093. this.boneInverses.length = 0;
  18094. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18095. const inverse = new Matrix4();
  18096. if ( this.bones[ i ] ) {
  18097. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18098. }
  18099. this.boneInverses.push( inverse );
  18100. }
  18101. }
  18102. /**
  18103. * Resets the skeleton to the base pose.
  18104. */
  18105. pose() {
  18106. // recover the bind-time world matrices
  18107. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18108. const bone = this.bones[ i ];
  18109. if ( bone ) {
  18110. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18111. }
  18112. }
  18113. // compute the local matrices, positions, rotations and scales
  18114. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18115. const bone = this.bones[ i ];
  18116. if ( bone ) {
  18117. if ( bone.parent && bone.parent.isBone ) {
  18118. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18119. bone.matrix.multiply( bone.matrixWorld );
  18120. } else {
  18121. bone.matrix.copy( bone.matrixWorld );
  18122. }
  18123. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18124. }
  18125. }
  18126. }
  18127. /**
  18128. * Resets the skeleton to the base pose.
  18129. */
  18130. update() {
  18131. const bones = this.bones;
  18132. const boneInverses = this.boneInverses;
  18133. const boneMatrices = this.boneMatrices;
  18134. const boneTexture = this.boneTexture;
  18135. // flatten bone matrices to array
  18136. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18137. // compute the offset between the current and the original transform
  18138. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18139. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18140. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18141. }
  18142. if ( boneTexture !== null ) {
  18143. boneTexture.needsUpdate = true;
  18144. }
  18145. }
  18146. /**
  18147. * Returns a new skeleton with copied values from this instance.
  18148. *
  18149. * @return {Skeleton} A clone of this instance.
  18150. */
  18151. clone() {
  18152. return new Skeleton( this.bones, this.boneInverses );
  18153. }
  18154. /**
  18155. * Computes a data texture for passing bone data to the vertex shader.
  18156. *
  18157. * @return {Skeleton} A reference of this instance.
  18158. */
  18159. computeBoneTexture() {
  18160. // layout (1 matrix = 4 pixels)
  18161. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18162. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18163. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18164. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18165. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18166. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18167. size = Math.ceil( size / 4 ) * 4;
  18168. size = Math.max( size, 4 );
  18169. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18170. boneMatrices.set( this.boneMatrices ); // copy current values
  18171. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18172. boneTexture.needsUpdate = true;
  18173. this.boneMatrices = boneMatrices;
  18174. this.boneTexture = boneTexture;
  18175. return this;
  18176. }
  18177. /**
  18178. * Searches through the skeleton's bone array and returns the first with a
  18179. * matching name.
  18180. *
  18181. * @param {string} name - The name of the bone.
  18182. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18183. */
  18184. getBoneByName( name ) {
  18185. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18186. const bone = this.bones[ i ];
  18187. if ( bone.name === name ) {
  18188. return bone;
  18189. }
  18190. }
  18191. return undefined;
  18192. }
  18193. /**
  18194. * Frees the GPU-related resources allocated by this instance. Call this
  18195. * method whenever this instance is no longer used in your app.
  18196. */
  18197. dispose( ) {
  18198. if ( this.boneTexture !== null ) {
  18199. this.boneTexture.dispose();
  18200. this.boneTexture = null;
  18201. }
  18202. }
  18203. /**
  18204. * Setups the skeleton by the given JSON and bones.
  18205. *
  18206. * @param {Object} json - The skeleton as serialized JSON.
  18207. * @param {Object<string, Bone>} bones - An array of bones.
  18208. * @return {Skeleton} A reference of this instance.
  18209. */
  18210. fromJSON( json, bones ) {
  18211. this.uuid = json.uuid;
  18212. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18213. const uuid = json.bones[ i ];
  18214. let bone = bones[ uuid ];
  18215. if ( bone === undefined ) {
  18216. warn( 'Skeleton: No bone found with UUID:', uuid );
  18217. bone = new Bone();
  18218. }
  18219. this.bones.push( bone );
  18220. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18221. }
  18222. this.init();
  18223. return this;
  18224. }
  18225. /**
  18226. * Serializes the skeleton into JSON.
  18227. *
  18228. * @return {Object} A JSON object representing the serialized skeleton.
  18229. * @see {@link ObjectLoader#parse}
  18230. */
  18231. toJSON() {
  18232. const data = {
  18233. metadata: {
  18234. version: 4.7,
  18235. type: 'Skeleton',
  18236. generator: 'Skeleton.toJSON'
  18237. },
  18238. bones: [],
  18239. boneInverses: []
  18240. };
  18241. data.uuid = this.uuid;
  18242. const bones = this.bones;
  18243. const boneInverses = this.boneInverses;
  18244. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18245. const bone = bones[ i ];
  18246. data.bones.push( bone.uuid );
  18247. const boneInverse = boneInverses[ i ];
  18248. data.boneInverses.push( boneInverse.toArray() );
  18249. }
  18250. return data;
  18251. }
  18252. }
  18253. /**
  18254. * An instanced version of a buffer attribute.
  18255. *
  18256. * @augments BufferAttribute
  18257. */
  18258. class InstancedBufferAttribute extends BufferAttribute {
  18259. /**
  18260. * Constructs a new instanced buffer attribute.
  18261. *
  18262. * @param {TypedArray} array - The array holding the attribute data.
  18263. * @param {number} itemSize - The item size.
  18264. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18265. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18266. */
  18267. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18268. super( array, itemSize, normalized );
  18269. /**
  18270. * This flag can be used for type testing.
  18271. *
  18272. * @type {boolean}
  18273. * @readonly
  18274. * @default true
  18275. */
  18276. this.isInstancedBufferAttribute = true;
  18277. /**
  18278. * Defines how often a value of this buffer attribute should be repeated. A
  18279. * value of one means that each value of the instanced attribute is used for
  18280. * a single instance. A value of two means that each value is used for two
  18281. * consecutive instances (and so on).
  18282. *
  18283. * @type {number}
  18284. * @default 1
  18285. */
  18286. this.meshPerAttribute = meshPerAttribute;
  18287. }
  18288. copy( source ) {
  18289. super.copy( source );
  18290. this.meshPerAttribute = source.meshPerAttribute;
  18291. return this;
  18292. }
  18293. toJSON() {
  18294. const data = super.toJSON();
  18295. data.meshPerAttribute = this.meshPerAttribute;
  18296. data.isInstancedBufferAttribute = true;
  18297. return data;
  18298. }
  18299. }
  18300. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18301. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18302. const _instanceIntersects = [];
  18303. const _box3 = /*@__PURE__*/ new Box3();
  18304. const _identity = /*@__PURE__*/ new Matrix4();
  18305. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18306. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18307. /**
  18308. * A special version of a mesh with instanced rendering support. Use
  18309. * this class if you have to render a large number of objects with the same
  18310. * geometry and material(s) but with different world transformations. The usage
  18311. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18312. * improve the overall rendering performance in your application.
  18313. *
  18314. * @augments Mesh
  18315. */
  18316. class InstancedMesh extends Mesh {
  18317. /**
  18318. * Constructs a new instanced mesh.
  18319. *
  18320. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18321. * @param {Material|Array<Material>} [material] - The mesh material.
  18322. * @param {number} count - The number of instances.
  18323. */
  18324. constructor( geometry, material, count ) {
  18325. super( geometry, material );
  18326. /**
  18327. * This flag can be used for type testing.
  18328. *
  18329. * @type {boolean}
  18330. * @readonly
  18331. * @default true
  18332. */
  18333. this.isInstancedMesh = true;
  18334. /**
  18335. * Represents the local transformation of all instances. You have to set its
  18336. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18337. * via {@link InstancedMesh#setMatrixAt}.
  18338. *
  18339. * @type {InstancedBufferAttribute}
  18340. */
  18341. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18342. /**
  18343. * Represents the color of all instances. You have to set its
  18344. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18345. * via {@link InstancedMesh#setColorAt}.
  18346. *
  18347. * @type {?InstancedBufferAttribute}
  18348. * @default null
  18349. */
  18350. this.instanceColor = null;
  18351. /**
  18352. * Represents the morph target weights of all instances. You have to set its
  18353. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18354. * via {@link InstancedMesh#setMorphAt}.
  18355. *
  18356. * @type {?DataTexture}
  18357. * @default null
  18358. */
  18359. this.morphTexture = null;
  18360. /**
  18361. * The number of instances.
  18362. *
  18363. * @type {number}
  18364. */
  18365. this.count = count;
  18366. /**
  18367. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18368. *
  18369. * @type {?Box3}
  18370. * @default null
  18371. */
  18372. this.boundingBox = null;
  18373. /**
  18374. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18375. *
  18376. * @type {?Sphere}
  18377. * @default null
  18378. */
  18379. this.boundingSphere = null;
  18380. for ( let i = 0; i < count; i ++ ) {
  18381. this.setMatrixAt( i, _identity );
  18382. }
  18383. }
  18384. /**
  18385. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18386. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18387. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18388. */
  18389. computeBoundingBox() {
  18390. const geometry = this.geometry;
  18391. const count = this.count;
  18392. if ( this.boundingBox === null ) {
  18393. this.boundingBox = new Box3();
  18394. }
  18395. if ( geometry.boundingBox === null ) {
  18396. geometry.computeBoundingBox();
  18397. }
  18398. this.boundingBox.makeEmpty();
  18399. for ( let i = 0; i < count; i ++ ) {
  18400. this.getMatrixAt( i, _instanceLocalMatrix );
  18401. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18402. this.boundingBox.union( _box3 );
  18403. }
  18404. }
  18405. /**
  18406. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18407. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18408. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18409. */
  18410. computeBoundingSphere() {
  18411. const geometry = this.geometry;
  18412. const count = this.count;
  18413. if ( this.boundingSphere === null ) {
  18414. this.boundingSphere = new Sphere();
  18415. }
  18416. if ( geometry.boundingSphere === null ) {
  18417. geometry.computeBoundingSphere();
  18418. }
  18419. this.boundingSphere.makeEmpty();
  18420. for ( let i = 0; i < count; i ++ ) {
  18421. this.getMatrixAt( i, _instanceLocalMatrix );
  18422. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18423. this.boundingSphere.union( _sphere$4 );
  18424. }
  18425. }
  18426. copy( source, recursive ) {
  18427. super.copy( source, recursive );
  18428. this.instanceMatrix.copy( source.instanceMatrix );
  18429. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18430. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18431. this.count = source.count;
  18432. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18433. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18434. return this;
  18435. }
  18436. /**
  18437. * Gets the color of the defined instance.
  18438. *
  18439. * @param {number} index - The instance index.
  18440. * @param {Color} color - The target object that is used to store the method's result.
  18441. * @return {Color} A reference to the target color.
  18442. */
  18443. getColorAt( index, color ) {
  18444. if ( this.instanceColor === null ) {
  18445. return color.setRGB( 1, 1, 1 );
  18446. } else {
  18447. return color.fromArray( this.instanceColor.array, index * 3 );
  18448. }
  18449. }
  18450. /**
  18451. * Gets the local transformation matrix of the defined instance.
  18452. *
  18453. * @param {number} index - The instance index.
  18454. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18455. * @return {Matrix4} A reference to the target matrix.
  18456. */
  18457. getMatrixAt( index, matrix ) {
  18458. return matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18459. }
  18460. /**
  18461. * Gets the morph target weights of the defined instance.
  18462. *
  18463. * @param {number} index - The instance index.
  18464. * @param {Mesh} object - The target object that is used to store the method's result.
  18465. */
  18466. getMorphAt( index, object ) {
  18467. const objectInfluences = object.morphTargetInfluences;
  18468. const array = this.morphTexture.source.data.data;
  18469. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18470. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18471. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18472. objectInfluences[ i ] = array[ dataIndex + i ];
  18473. }
  18474. }
  18475. raycast( raycaster, intersects ) {
  18476. const matrixWorld = this.matrixWorld;
  18477. const raycastTimes = this.count;
  18478. _mesh$1.geometry = this.geometry;
  18479. _mesh$1.material = this.material;
  18480. if ( _mesh$1.material === undefined ) return;
  18481. // test with bounding sphere first
  18482. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18483. _sphere$4.copy( this.boundingSphere );
  18484. _sphere$4.applyMatrix4( matrixWorld );
  18485. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18486. // now test each instance
  18487. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18488. // calculate the world matrix for each instance
  18489. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18490. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18491. // the mesh represents this single instance
  18492. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18493. _mesh$1.raycast( raycaster, _instanceIntersects );
  18494. // process the result of raycast
  18495. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18496. const intersect = _instanceIntersects[ i ];
  18497. intersect.instanceId = instanceId;
  18498. intersect.object = this;
  18499. intersects.push( intersect );
  18500. }
  18501. _instanceIntersects.length = 0;
  18502. }
  18503. }
  18504. /**
  18505. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18506. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18507. *
  18508. * @param {number} index - The instance index.
  18509. * @param {Color} color - The instance color.
  18510. * @return {InstancedMesh} A reference to this instanced mesh.
  18511. */
  18512. setColorAt( index, color ) {
  18513. if ( this.instanceColor === null ) {
  18514. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18515. }
  18516. color.toArray( this.instanceColor.array, index * 3 );
  18517. return this;
  18518. }
  18519. /**
  18520. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18521. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the matrices.
  18522. *
  18523. * @param {number} index - The instance index.
  18524. * @param {Matrix4} matrix - The local transformation.
  18525. * @return {InstancedMesh} A reference to this instanced mesh.
  18526. */
  18527. setMatrixAt( index, matrix ) {
  18528. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18529. return this;
  18530. }
  18531. /**
  18532. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18533. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18534. *
  18535. * @param {number} index - The instance index.
  18536. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18537. * of a single instance.
  18538. * @return {InstancedMesh} A reference to this instanced mesh.
  18539. */
  18540. setMorphAt( index, object ) {
  18541. const objectInfluences = object.morphTargetInfluences;
  18542. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18543. if ( this.morphTexture === null ) {
  18544. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18545. }
  18546. const array = this.morphTexture.source.data.data;
  18547. let morphInfluencesSum = 0;
  18548. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18549. morphInfluencesSum += objectInfluences[ i ];
  18550. }
  18551. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18552. const dataIndex = len * index;
  18553. array[ dataIndex ] = morphBaseInfluence;
  18554. array.set( objectInfluences, dataIndex + 1 );
  18555. return this;
  18556. }
  18557. updateMorphTargets() {
  18558. }
  18559. /**
  18560. * Frees the GPU-related resources allocated by this instance. Call this
  18561. * method whenever this instance is no longer used in your app.
  18562. */
  18563. dispose() {
  18564. this.dispatchEvent( { type: 'dispose' } );
  18565. if ( this.morphTexture !== null ) {
  18566. this.morphTexture.dispose();
  18567. this.morphTexture = null;
  18568. }
  18569. }
  18570. }
  18571. const _vector1 = /*@__PURE__*/ new Vector3();
  18572. const _vector2 = /*@__PURE__*/ new Vector3();
  18573. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  18574. /**
  18575. * A two dimensional surface that extends infinitely in 3D space, represented
  18576. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  18577. * by a unit length normal vector and a constant.
  18578. */
  18579. class Plane {
  18580. /**
  18581. * Constructs a new plane.
  18582. *
  18583. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  18584. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  18585. */
  18586. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  18587. /**
  18588. * This flag can be used for type testing.
  18589. *
  18590. * @type {boolean}
  18591. * @readonly
  18592. * @default true
  18593. */
  18594. this.isPlane = true;
  18595. /**
  18596. * A unit length vector defining the normal of the plane.
  18597. *
  18598. * @type {Vector3}
  18599. */
  18600. this.normal = normal;
  18601. /**
  18602. * The signed distance from the origin to the plane.
  18603. *
  18604. * @type {number}
  18605. * @default 0
  18606. */
  18607. this.constant = constant;
  18608. }
  18609. /**
  18610. * Sets the plane components by copying the given values.
  18611. *
  18612. * @param {Vector3} normal - The normal.
  18613. * @param {number} constant - The constant.
  18614. * @return {Plane} A reference to this plane.
  18615. */
  18616. set( normal, constant ) {
  18617. this.normal.copy( normal );
  18618. this.constant = constant;
  18619. return this;
  18620. }
  18621. /**
  18622. * Sets the plane components by defining `x`, `y`, `z` as the
  18623. * plane normal and `w` as the constant.
  18624. *
  18625. * @param {number} x - The value for the normal's x component.
  18626. * @param {number} y - The value for the normal's y component.
  18627. * @param {number} z - The value for the normal's z component.
  18628. * @param {number} w - The constant value.
  18629. * @return {Plane} A reference to this plane.
  18630. */
  18631. setComponents( x, y, z, w ) {
  18632. this.normal.set( x, y, z );
  18633. this.constant = w;
  18634. return this;
  18635. }
  18636. /**
  18637. * Sets the plane from the given normal and coplanar point (that is a point
  18638. * that lies onto the plane).
  18639. *
  18640. * @param {Vector3} normal - The normal.
  18641. * @param {Vector3} point - A coplanar point.
  18642. * @return {Plane} A reference to this plane.
  18643. */
  18644. setFromNormalAndCoplanarPoint( normal, point ) {
  18645. this.normal.copy( normal );
  18646. this.constant = - point.dot( this.normal );
  18647. return this;
  18648. }
  18649. /**
  18650. * Sets the plane from three coplanar points. The winding order is
  18651. * assumed to be counter-clockwise, and determines the direction of
  18652. * the plane normal.
  18653. *
  18654. * @param {Vector3} a - The first coplanar point.
  18655. * @param {Vector3} b - The second coplanar point.
  18656. * @param {Vector3} c - The third coplanar point.
  18657. * @return {Plane} A reference to this plane.
  18658. */
  18659. setFromCoplanarPoints( a, b, c ) {
  18660. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  18661. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  18662. this.setFromNormalAndCoplanarPoint( normal, a );
  18663. return this;
  18664. }
  18665. /**
  18666. * Copies the values of the given plane to this instance.
  18667. *
  18668. * @param {Plane} plane - The plane to copy.
  18669. * @return {Plane} A reference to this plane.
  18670. */
  18671. copy( plane ) {
  18672. this.normal.copy( plane.normal );
  18673. this.constant = plane.constant;
  18674. return this;
  18675. }
  18676. /**
  18677. * Normalizes the plane normal and adjusts the constant accordingly.
  18678. *
  18679. * @return {Plane} A reference to this plane.
  18680. */
  18681. normalize() {
  18682. // Note: will lead to a divide by zero if the plane is invalid.
  18683. const inverseNormalLength = 1.0 / this.normal.length();
  18684. this.normal.multiplyScalar( inverseNormalLength );
  18685. this.constant *= inverseNormalLength;
  18686. return this;
  18687. }
  18688. /**
  18689. * Negates both the plane normal and the constant.
  18690. *
  18691. * @return {Plane} A reference to this plane.
  18692. */
  18693. negate() {
  18694. this.constant *= -1;
  18695. this.normal.negate();
  18696. return this;
  18697. }
  18698. /**
  18699. * Returns the signed distance from the given point to this plane.
  18700. *
  18701. * @param {Vector3} point - The point to compute the distance for.
  18702. * @return {number} The signed distance.
  18703. */
  18704. distanceToPoint( point ) {
  18705. return this.normal.dot( point ) + this.constant;
  18706. }
  18707. /**
  18708. * Returns the signed distance from the given sphere to this plane.
  18709. *
  18710. * @param {Sphere} sphere - The sphere to compute the distance for.
  18711. * @return {number} The signed distance.
  18712. */
  18713. distanceToSphere( sphere ) {
  18714. return this.distanceToPoint( sphere.center ) - sphere.radius;
  18715. }
  18716. /**
  18717. * Projects a the given point onto the plane.
  18718. *
  18719. * @param {Vector3} point - The point to project.
  18720. * @param {Vector3} target - The target vector that is used to store the method's result.
  18721. * @return {Vector3} The projected point on the plane.
  18722. */
  18723. projectPoint( point, target ) {
  18724. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  18725. }
  18726. /**
  18727. * Returns the intersection point of the passed line and the plane. Returns
  18728. * `null` if the line does not intersect. Returns the line's starting point if
  18729. * the line is coplanar with the plane.
  18730. *
  18731. * @param {Line3} line - The line to compute the intersection for.
  18732. * @param {Vector3} target - The target vector that is used to store the method's result.
  18733. * @param {boolean} [clampToLine=true] - Whether to clamp the intersection to the line segment.
  18734. * @return {?Vector3} The intersection point. Returns `null` if no intersection is detected.
  18735. */
  18736. intersectLine( line, target, clampToLine = true ) {
  18737. const direction = line.delta( _vector1 );
  18738. const denominator = this.normal.dot( direction );
  18739. if ( denominator === 0 ) {
  18740. // line is coplanar, return origin
  18741. if ( this.distanceToPoint( line.start ) === 0 ) {
  18742. return target.copy( line.start );
  18743. }
  18744. // Unsure if this is the correct method to handle this case.
  18745. return null;
  18746. }
  18747. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  18748. if ( ( clampToLine === true ) && ( t < 0 || t > 1 ) ) {
  18749. return null;
  18750. }
  18751. return target.copy( line.start ).addScaledVector( direction, t );
  18752. }
  18753. /**
  18754. * Returns `true` if the given line segment intersects with (passes through) the plane.
  18755. *
  18756. * @param {Line3} line - The line to test.
  18757. * @return {boolean} Whether the given line segment intersects with the plane or not.
  18758. */
  18759. intersectsLine( line ) {
  18760. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  18761. const startSign = this.distanceToPoint( line.start );
  18762. const endSign = this.distanceToPoint( line.end );
  18763. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  18764. }
  18765. /**
  18766. * Returns `true` if the given bounding box intersects with the plane.
  18767. *
  18768. * @param {Box3} box - The bounding box to test.
  18769. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  18770. */
  18771. intersectsBox( box ) {
  18772. return box.intersectsPlane( this );
  18773. }
  18774. /**
  18775. * Returns `true` if the given bounding sphere intersects with the plane.
  18776. *
  18777. * @param {Sphere} sphere - The bounding sphere to test.
  18778. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  18779. */
  18780. intersectsSphere( sphere ) {
  18781. return sphere.intersectsPlane( this );
  18782. }
  18783. /**
  18784. * Returns a coplanar vector to the plane, by calculating the
  18785. * projection of the normal at the origin onto the plane.
  18786. *
  18787. * @param {Vector3} target - The target vector that is used to store the method's result.
  18788. * @return {Vector3} The coplanar point.
  18789. */
  18790. coplanarPoint( target ) {
  18791. return target.copy( this.normal ).multiplyScalar( - this.constant );
  18792. }
  18793. /**
  18794. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  18795. *
  18796. * The optional normal matrix can be pre-computed like so:
  18797. * ```js
  18798. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  18799. * ```
  18800. *
  18801. * @param {Matrix4} matrix - The transformation matrix.
  18802. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  18803. * @return {Plane} A reference to this plane.
  18804. */
  18805. applyMatrix4( matrix, optionalNormalMatrix ) {
  18806. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  18807. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  18808. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  18809. this.constant = - referencePoint.dot( normal );
  18810. return this;
  18811. }
  18812. /**
  18813. * Translates the plane by the distance defined by the given offset vector.
  18814. * Note that this only affects the plane constant and will not affect the normal vector.
  18815. *
  18816. * @param {Vector3} offset - The offset vector.
  18817. * @return {Plane} A reference to this plane.
  18818. */
  18819. translate( offset ) {
  18820. this.constant -= offset.dot( this.normal );
  18821. return this;
  18822. }
  18823. /**
  18824. * Returns `true` if this plane is equal with the given one.
  18825. *
  18826. * @param {Plane} plane - The plane to test for equality.
  18827. * @return {boolean} Whether this plane is equal with the given one.
  18828. */
  18829. equals( plane ) {
  18830. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  18831. }
  18832. /**
  18833. * Returns a new plane with copied values from this instance.
  18834. *
  18835. * @return {Plane} A clone of this instance.
  18836. */
  18837. clone() {
  18838. return new this.constructor().copy( this );
  18839. }
  18840. }
  18841. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18842. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  18843. const _vector$6 = /*@__PURE__*/ new Vector3();
  18844. /**
  18845. * Frustums are used to determine what is inside the camera's field of view.
  18846. * They help speed up the rendering process - objects which lie outside a camera's
  18847. * frustum can safely be excluded from rendering.
  18848. *
  18849. * This class is mainly intended for use internally by a renderer.
  18850. */
  18851. class Frustum {
  18852. /**
  18853. * Constructs a new frustum.
  18854. *
  18855. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18856. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18857. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18858. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18859. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18860. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18861. */
  18862. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  18863. /**
  18864. * This array holds the planes that enclose the frustum.
  18865. *
  18866. * @type {Array<Plane>}
  18867. */
  18868. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  18869. }
  18870. /**
  18871. * Sets the frustum planes by copying the given planes.
  18872. *
  18873. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18874. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18875. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18876. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18877. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18878. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18879. * @return {Frustum} A reference to this frustum.
  18880. */
  18881. set( p0, p1, p2, p3, p4, p5 ) {
  18882. const planes = this.planes;
  18883. planes[ 0 ].copy( p0 );
  18884. planes[ 1 ].copy( p1 );
  18885. planes[ 2 ].copy( p2 );
  18886. planes[ 3 ].copy( p3 );
  18887. planes[ 4 ].copy( p4 );
  18888. planes[ 5 ].copy( p5 );
  18889. return this;
  18890. }
  18891. /**
  18892. * Copies the values of the given frustum to this instance.
  18893. *
  18894. * @param {Frustum} frustum - The frustum to copy.
  18895. * @return {Frustum} A reference to this frustum.
  18896. */
  18897. copy( frustum ) {
  18898. const planes = this.planes;
  18899. for ( let i = 0; i < 6; i ++ ) {
  18900. planes[ i ].copy( frustum.planes[ i ] );
  18901. }
  18902. return this;
  18903. }
  18904. /**
  18905. * Sets the frustum planes from the given projection matrix.
  18906. *
  18907. * @param {Matrix4} m - The projection matrix.
  18908. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  18909. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  18910. * @return {Frustum} A reference to this frustum.
  18911. */
  18912. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  18913. const planes = this.planes;
  18914. const me = m.elements;
  18915. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  18916. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  18917. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  18918. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  18919. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  18920. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  18921. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  18922. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  18923. if ( reversedDepth ) {
  18924. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  18925. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  18926. } else {
  18927. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  18928. if ( coordinateSystem === WebGLCoordinateSystem ) {
  18929. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  18930. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  18931. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  18932. } else {
  18933. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  18934. }
  18935. }
  18936. return this;
  18937. }
  18938. /**
  18939. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  18940. *
  18941. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  18942. *
  18943. * @param {Object3D} object - The 3D object to test.
  18944. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  18945. */
  18946. intersectsObject( object ) {
  18947. if ( object.boundingSphere !== undefined ) {
  18948. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  18949. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  18950. } else {
  18951. const geometry = object.geometry;
  18952. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18953. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  18954. }
  18955. return this.intersectsSphere( _sphere$3 );
  18956. }
  18957. /**
  18958. * Returns `true` if the given sprite is intersecting this frustum.
  18959. *
  18960. * @param {Sprite} sprite - The sprite to test.
  18961. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  18962. */
  18963. intersectsSprite( sprite ) {
  18964. _sphere$3.center.set( 0, 0, 0 );
  18965. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  18966. _sphere$3.radius = 0.7071067811865476 + offset;
  18967. _sphere$3.applyMatrix4( sprite.matrixWorld );
  18968. return this.intersectsSphere( _sphere$3 );
  18969. }
  18970. /**
  18971. * Returns `true` if the given bounding sphere is intersecting this frustum.
  18972. *
  18973. * @param {Sphere} sphere - The bounding sphere to test.
  18974. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  18975. */
  18976. intersectsSphere( sphere ) {
  18977. const planes = this.planes;
  18978. const center = sphere.center;
  18979. const negRadius = - sphere.radius;
  18980. for ( let i = 0; i < 6; i ++ ) {
  18981. const distance = planes[ i ].distanceToPoint( center );
  18982. if ( distance < negRadius ) {
  18983. return false;
  18984. }
  18985. }
  18986. return true;
  18987. }
  18988. /**
  18989. * Returns `true` if the given bounding box is intersecting this frustum.
  18990. *
  18991. * @param {Box3} box - The bounding box to test.
  18992. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  18993. */
  18994. intersectsBox( box ) {
  18995. const planes = this.planes;
  18996. for ( let i = 0; i < 6; i ++ ) {
  18997. const plane = planes[ i ];
  18998. // corner at max distance
  18999. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19000. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19001. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19002. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19003. return false;
  19004. }
  19005. }
  19006. return true;
  19007. }
  19008. /**
  19009. * Returns `true` if the given point lies within the frustum.
  19010. *
  19011. * @param {Vector3} point - The point to test.
  19012. * @return {boolean} Whether the point lies within this frustum or not.
  19013. */
  19014. containsPoint( point ) {
  19015. const planes = this.planes;
  19016. for ( let i = 0; i < 6; i ++ ) {
  19017. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19018. return false;
  19019. }
  19020. }
  19021. return true;
  19022. }
  19023. /**
  19024. * Returns a new frustum with copied values from this instance.
  19025. *
  19026. * @return {Frustum} A clone of this instance.
  19027. */
  19028. clone() {
  19029. return new this.constructor().copy( this );
  19030. }
  19031. }
  19032. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  19033. /**
  19034. * FrustumArray is used to determine if an object is visible in at least one camera
  19035. * from an array of cameras. This is particularly useful for multi-view renderers.
  19036. */
  19037. class FrustumArray {
  19038. /**
  19039. * Constructs a new frustum array.
  19040. *
  19041. */
  19042. constructor() {
  19043. /**
  19044. * The coordinate system to use.
  19045. *
  19046. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19047. * @default WebGLCoordinateSystem
  19048. */
  19049. this.coordinateSystem = WebGLCoordinateSystem;
  19050. /**
  19051. * A pool of frustum instances. It may hold more entries than are
  19052. * currently in use; surplus instances are kept for reuse to avoid
  19053. * reallocating when array cameras of different lengths are rendered.
  19054. *
  19055. * @private
  19056. * @type {Array<Frustum>}
  19057. */
  19058. this._frustums = [];
  19059. /**
  19060. * The number of frustums in {@link FrustumArray#_frustums} that are currently
  19061. * in use.
  19062. *
  19063. * @private
  19064. * @type {number}
  19065. * @default 0
  19066. */
  19067. this._count = 0;
  19068. }
  19069. /**
  19070. * Computes and caches a frustum for each camera of the given array camera.
  19071. *
  19072. * @param {ArrayCamera} cameraArray - The array camera whose sub-cameras define the frustums.
  19073. * @return {FrustumArray} A reference to this frustum array.
  19074. */
  19075. setFromArrayCamera( cameraArray ) {
  19076. const cameras = cameraArray.cameras;
  19077. const frustums = this._frustums;
  19078. for ( let i = 0; i < cameras.length; i ++ ) {
  19079. const camera = cameras[ i ];
  19080. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  19081. if ( frustums[ i ] === undefined ) frustums[ i ] = new Frustum();
  19082. frustums[ i ].setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  19083. }
  19084. this._count = cameras.length;
  19085. return this;
  19086. }
  19087. /**
  19088. * Returns `true` if the 3D object's bounding sphere is intersecting any cached frustum.
  19089. *
  19090. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19091. *
  19092. * @param {Object3D} object - The 3D object to test.
  19093. * @return {boolean} Whether the 3D object is visible in any camera.
  19094. */
  19095. intersectsObject( object ) {
  19096. const frustums = this._frustums;
  19097. for ( let i = 0; i < this._count; i ++ ) {
  19098. if ( frustums[ i ].intersectsObject( object ) ) return true;
  19099. }
  19100. return false;
  19101. }
  19102. /**
  19103. * Returns `true` if the given sprite is intersecting any cached frustum.
  19104. *
  19105. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19106. *
  19107. * @param {Sprite} sprite - The sprite to test.
  19108. * @return {boolean} Whether the sprite is visible in any camera.
  19109. */
  19110. intersectsSprite( sprite ) {
  19111. const frustums = this._frustums;
  19112. for ( let i = 0; i < this._count; i ++ ) {
  19113. if ( frustums[ i ].intersectsSprite( sprite ) ) return true;
  19114. }
  19115. return false;
  19116. }
  19117. /**
  19118. * Returns `true` if the given bounding sphere is intersecting any cached frustum.
  19119. *
  19120. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19121. *
  19122. * @param {Sphere} sphere - The bounding sphere to test.
  19123. * @return {boolean} Whether the sphere is visible in any camera.
  19124. */
  19125. intersectsSphere( sphere ) {
  19126. const frustums = this._frustums;
  19127. for ( let i = 0; i < this._count; i ++ ) {
  19128. if ( frustums[ i ].intersectsSphere( sphere ) ) return true;
  19129. }
  19130. return false;
  19131. }
  19132. /**
  19133. * Returns `true` if the given bounding box is intersecting any cached frustum.
  19134. *
  19135. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19136. *
  19137. * @param {Box3} box - The bounding box to test.
  19138. * @return {boolean} Whether the box is visible in any camera.
  19139. */
  19140. intersectsBox( box ) {
  19141. const frustums = this._frustums;
  19142. for ( let i = 0; i < this._count; i ++ ) {
  19143. if ( frustums[ i ].intersectsBox( box ) ) return true;
  19144. }
  19145. return false;
  19146. }
  19147. /**
  19148. * Returns `true` if the given point lies within any cached frustum.
  19149. *
  19150. * {@link FrustumArray#setFromArrayCamera} must be called once per render before this method.
  19151. *
  19152. * @param {Vector3} point - The point to test.
  19153. * @return {boolean} Whether the point is visible in any camera.
  19154. */
  19155. containsPoint( point ) {
  19156. const frustums = this._frustums;
  19157. for ( let i = 0; i < this._count; i ++ ) {
  19158. if ( frustums[ i ].containsPoint( point ) ) return true;
  19159. }
  19160. return false;
  19161. }
  19162. /**
  19163. * Copies the values of the given frustum array to this instance.
  19164. *
  19165. * @param {FrustumArray} frustumArray - The frustum array to copy.
  19166. * @return {FrustumArray} A reference to this frustum array.
  19167. */
  19168. copy( source ) {
  19169. this.coordinateSystem = source.coordinateSystem;
  19170. const frustums = this._frustums;
  19171. const sourceFrustums = source._frustums;
  19172. for ( let i = 0; i < source._count; i ++ ) {
  19173. if ( frustums[ i ] === undefined ) frustums[ i ] = new Frustum();
  19174. frustums[ i ].copy( sourceFrustums[ i ] );
  19175. }
  19176. this._count = source._count;
  19177. return this;
  19178. }
  19179. /**
  19180. * Returns a new frustum array with copied values from this instance.
  19181. *
  19182. * @return {FrustumArray} A clone of this instance.
  19183. */
  19184. clone() {
  19185. return new FrustumArray().copy( this );
  19186. }
  19187. }
  19188. function ascIdSort( a, b ) {
  19189. return a - b;
  19190. }
  19191. function sortOpaque( a, b ) {
  19192. return a.z - b.z;
  19193. }
  19194. function sortTransparent( a, b ) {
  19195. return b.z - a.z;
  19196. }
  19197. class MultiDrawRenderList {
  19198. constructor() {
  19199. this.index = 0;
  19200. this.pool = [];
  19201. this.list = [];
  19202. }
  19203. push( start, count, z, index ) {
  19204. const pool = this.pool;
  19205. const list = this.list;
  19206. if ( this.index >= pool.length ) {
  19207. pool.push( {
  19208. start: -1,
  19209. count: -1,
  19210. z: -1,
  19211. index: -1,
  19212. } );
  19213. }
  19214. const item = pool[ this.index ];
  19215. list.push( item );
  19216. this.index ++;
  19217. item.start = start;
  19218. item.count = count;
  19219. item.z = z;
  19220. item.index = index;
  19221. }
  19222. reset() {
  19223. this.list.length = 0;
  19224. this.index = 0;
  19225. }
  19226. }
  19227. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19228. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19229. const _frustum = /*@__PURE__*/ new Frustum();
  19230. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19231. const _box$1 = /*@__PURE__*/ new Box3();
  19232. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19233. const _vector$5 = /*@__PURE__*/ new Vector3();
  19234. const _forward$1 = /*@__PURE__*/ new Vector3();
  19235. const _temp = /*@__PURE__*/ new Vector3();
  19236. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19237. const _mesh = /*@__PURE__*/ new Mesh();
  19238. const _batchIntersects = [];
  19239. // copies data from attribute "src" into "target" starting at "targetOffset"
  19240. function copyAttributeData( src, target, targetOffset = 0 ) {
  19241. const itemSize = target.itemSize;
  19242. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19243. // use the component getters and setters if the array data cannot
  19244. // be copied directly
  19245. const vertexCount = src.count;
  19246. for ( let i = 0; i < vertexCount; i ++ ) {
  19247. for ( let c = 0; c < itemSize; c ++ ) {
  19248. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19249. }
  19250. }
  19251. } else {
  19252. // faster copy approach using typed array set function
  19253. target.array.set( src.array, targetOffset * itemSize );
  19254. }
  19255. target.needsUpdate = true;
  19256. }
  19257. // safely copies array contents to a potentially smaller array
  19258. function copyArrayContents( src, target ) {
  19259. if ( src.constructor !== target.constructor ) {
  19260. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19261. const len = Math.min( src.length, target.length );
  19262. for ( let i = 0; i < len; i ++ ) {
  19263. target[ i ] = src[ i ];
  19264. }
  19265. } else {
  19266. // if the arrays use the same data layout we can use a fast block copy
  19267. const len = Math.min( src.length, target.length );
  19268. target.set( new src.constructor( src.buffer, 0, len ) );
  19269. }
  19270. }
  19271. /**
  19272. * A special version of a mesh with multi draw batch rendering support. Use
  19273. * this class if you have to render a large number of objects with the same
  19274. * material but with different geometries or world transformations. The usage of
  19275. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19276. * rendering performance in your application.
  19277. *
  19278. * ```js
  19279. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19280. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19281. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19282. *
  19283. * // initialize and add geometries into the batched mesh
  19284. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19285. * const boxGeometryId = batchedMesh.addGeometry( box );
  19286. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19287. *
  19288. * // create instances of those geometries
  19289. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19290. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19291. *
  19292. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19293. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19294. *
  19295. * // position the geometries
  19296. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19297. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19298. *
  19299. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19300. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19301. *
  19302. * scene.add( batchedMesh );
  19303. * ```
  19304. *
  19305. * @augments Mesh
  19306. */
  19307. class BatchedMesh extends Mesh {
  19308. /**
  19309. * Constructs a new batched mesh.
  19310. *
  19311. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19312. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19313. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19314. * @param {Material|Array<Material>} [material] - The mesh material.
  19315. */
  19316. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19317. super( new BufferGeometry(), material );
  19318. /**
  19319. * This flag can be used for type testing.
  19320. *
  19321. * @type {boolean}
  19322. * @readonly
  19323. * @default true
  19324. */
  19325. this.isBatchedMesh = true;
  19326. /**
  19327. * When set ot `true`, the individual objects of a batch are frustum culled.
  19328. *
  19329. * @type {boolean}
  19330. * @default true
  19331. */
  19332. this.perObjectFrustumCulled = true;
  19333. /**
  19334. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19335. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19336. * rendered front to back.
  19337. *
  19338. * @type {boolean}
  19339. * @default true
  19340. */
  19341. this.sortObjects = true;
  19342. /**
  19343. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19344. *
  19345. * @type {?Box3}
  19346. * @default null
  19347. */
  19348. this.boundingBox = null;
  19349. /**
  19350. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19351. *
  19352. * @type {?Sphere}
  19353. * @default null
  19354. */
  19355. this.boundingSphere = null;
  19356. /**
  19357. * Takes a sort a function that is run before render. The function takes a list of instances to
  19358. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19359. * sort with.
  19360. *
  19361. * @type {?Function}
  19362. * @default null
  19363. */
  19364. this.customSort = null;
  19365. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19366. this._instanceInfo = [];
  19367. this._geometryInfo = [];
  19368. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19369. this._availableInstanceIds = [];
  19370. this._availableGeometryIds = [];
  19371. // used to track where the next point is that geometry should be inserted
  19372. this._nextIndexStart = 0;
  19373. this._nextVertexStart = 0;
  19374. this._geometryCount = 0;
  19375. // flags
  19376. this._visibilityChanged = true;
  19377. this._geometryInitialized = false;
  19378. // cached user options
  19379. this._maxInstanceCount = maxInstanceCount;
  19380. this._maxVertexCount = maxVertexCount;
  19381. this._maxIndexCount = maxIndexCount;
  19382. // buffers for multi draw
  19383. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19384. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19385. this._multiDrawCount = 0;
  19386. // Local matrix per geometry by using data texture
  19387. this._matricesTexture = null;
  19388. this._indirectTexture = null;
  19389. this._colorsTexture = null;
  19390. this._initMatricesTexture();
  19391. this._initIndirectTexture();
  19392. }
  19393. /**
  19394. * The maximum number of individual instances that can be stored in the batch.
  19395. *
  19396. * @type {number}
  19397. * @readonly
  19398. */
  19399. get maxInstanceCount() {
  19400. return this._maxInstanceCount;
  19401. }
  19402. /**
  19403. * The instance count.
  19404. *
  19405. * @type {number}
  19406. * @readonly
  19407. */
  19408. get instanceCount() {
  19409. return this._instanceInfo.length - this._availableInstanceIds.length;
  19410. }
  19411. /**
  19412. * The number of unused vertices.
  19413. *
  19414. * @type {number}
  19415. * @readonly
  19416. */
  19417. get unusedVertexCount() {
  19418. return this._maxVertexCount - this._nextVertexStart;
  19419. }
  19420. /**
  19421. * The number of unused indices.
  19422. *
  19423. * @type {number}
  19424. * @readonly
  19425. */
  19426. get unusedIndexCount() {
  19427. return this._maxIndexCount - this._nextIndexStart;
  19428. }
  19429. _initMatricesTexture() {
  19430. // layout (1 matrix = 4 pixels)
  19431. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19432. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19433. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19434. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19435. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19436. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19437. size = Math.ceil( size / 4 ) * 4;
  19438. size = Math.max( size, 4 );
  19439. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19440. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19441. this._matricesTexture = matricesTexture;
  19442. }
  19443. _initIndirectTexture() {
  19444. let size = Math.sqrt( this._maxInstanceCount );
  19445. size = Math.ceil( size );
  19446. const indirectArray = new Uint32Array( size * size );
  19447. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19448. this._indirectTexture = indirectTexture;
  19449. }
  19450. _initColorsTexture() {
  19451. let size = Math.sqrt( this._maxInstanceCount );
  19452. size = Math.ceil( size );
  19453. // 4 floats per RGBA pixel initialized to white
  19454. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19455. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19456. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19457. this._colorsTexture = colorsTexture;
  19458. }
  19459. _initializeGeometry( reference ) {
  19460. const geometry = this.geometry;
  19461. const maxVertexCount = this._maxVertexCount;
  19462. const maxIndexCount = this._maxIndexCount;
  19463. if ( this._geometryInitialized === false ) {
  19464. for ( const attributeName in reference.attributes ) {
  19465. const srcAttribute = reference.getAttribute( attributeName );
  19466. const { array, itemSize, normalized } = srcAttribute;
  19467. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19468. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19469. geometry.setAttribute( attributeName, dstAttribute );
  19470. }
  19471. if ( reference.getIndex() !== null ) {
  19472. // Reserve last u16 index for primitive restart.
  19473. const indexArray = maxVertexCount > 65535
  19474. ? new Uint32Array( maxIndexCount )
  19475. : new Uint16Array( maxIndexCount );
  19476. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19477. }
  19478. this._geometryInitialized = true;
  19479. }
  19480. }
  19481. // Make sure the geometry is compatible with the existing combined geometry attributes
  19482. _validateGeometry( geometry ) {
  19483. // check to ensure the geometries are using consistent attributes and indices
  19484. const batchGeometry = this.geometry;
  19485. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19486. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19487. }
  19488. for ( const attributeName in batchGeometry.attributes ) {
  19489. if ( ! geometry.hasAttribute( attributeName ) ) {
  19490. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19491. }
  19492. const srcAttribute = geometry.getAttribute( attributeName );
  19493. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19494. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19495. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19496. }
  19497. }
  19498. }
  19499. /**
  19500. * Validates the instance defined by the given ID.
  19501. *
  19502. * @param {number} instanceId - The instance to validate.
  19503. */
  19504. validateInstanceId( instanceId ) {
  19505. const instanceInfo = this._instanceInfo;
  19506. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19507. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19508. }
  19509. }
  19510. /**
  19511. * Validates the geometry defined by the given ID.
  19512. *
  19513. * @param {number} geometryId - The geometry to validate.
  19514. */
  19515. validateGeometryId( geometryId ) {
  19516. const geometryInfoList = this._geometryInfo;
  19517. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19518. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19519. }
  19520. }
  19521. /**
  19522. * Takes a sort a function that is run before render. The function takes a list of instances to
  19523. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19524. *
  19525. * @param {Function} func - The custom sort function.
  19526. * @return {BatchedMesh} A reference to this batched mesh.
  19527. */
  19528. setCustomSort( func ) {
  19529. this.customSort = func;
  19530. return this;
  19531. }
  19532. /**
  19533. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19534. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19535. * otherwise they are `null`.
  19536. */
  19537. computeBoundingBox() {
  19538. if ( this.boundingBox === null ) {
  19539. this.boundingBox = new Box3();
  19540. }
  19541. const boundingBox = this.boundingBox;
  19542. const instanceInfo = this._instanceInfo;
  19543. boundingBox.makeEmpty();
  19544. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19545. if ( instanceInfo[ i ].active === false ) continue;
  19546. const geometryId = instanceInfo[ i ].geometryIndex;
  19547. this.getMatrixAt( i, _matrix$1 );
  19548. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19549. boundingBox.union( _box$1 );
  19550. }
  19551. }
  19552. /**
  19553. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19554. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19555. * otherwise they are `null`.
  19556. */
  19557. computeBoundingSphere() {
  19558. if ( this.boundingSphere === null ) {
  19559. this.boundingSphere = new Sphere();
  19560. }
  19561. const boundingSphere = this.boundingSphere;
  19562. const instanceInfo = this._instanceInfo;
  19563. boundingSphere.makeEmpty();
  19564. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19565. if ( instanceInfo[ i ].active === false ) continue;
  19566. const geometryId = instanceInfo[ i ].geometryIndex;
  19567. this.getMatrixAt( i, _matrix$1 );
  19568. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19569. boundingSphere.union( _sphere$2 );
  19570. }
  19571. }
  19572. /**
  19573. * Adds a new instance to the batch using the geometry of the given ID and returns
  19574. * a new id referring to the new instance to be used by other functions.
  19575. *
  19576. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  19577. * @return {number} The instance ID.
  19578. */
  19579. addInstance( geometryId ) {
  19580. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  19581. // ensure we're not over geometry
  19582. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  19583. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  19584. }
  19585. const instanceInfo = {
  19586. visible: true,
  19587. active: true,
  19588. geometryIndex: geometryId,
  19589. };
  19590. let drawId = null;
  19591. // Prioritize using previously freed instance ids
  19592. if ( this._availableInstanceIds.length > 0 ) {
  19593. this._availableInstanceIds.sort( ascIdSort );
  19594. drawId = this._availableInstanceIds.shift();
  19595. this._instanceInfo[ drawId ] = instanceInfo;
  19596. } else {
  19597. drawId = this._instanceInfo.length;
  19598. this._instanceInfo.push( instanceInfo );
  19599. }
  19600. const matricesTexture = this._matricesTexture;
  19601. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  19602. matricesTexture.needsUpdate = true;
  19603. const colorsTexture = this._colorsTexture;
  19604. if ( colorsTexture ) {
  19605. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  19606. colorsTexture.needsUpdate = true;
  19607. }
  19608. this._visibilityChanged = true;
  19609. return drawId;
  19610. }
  19611. /**
  19612. * Adds the given geometry to the batch and returns the associated
  19613. * geometry id referring to it to be used in other functions.
  19614. *
  19615. * @param {BufferGeometry} geometry - The geometry to add.
  19616. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  19617. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  19618. * to set a new geometry at this index at a later time that is larger than the original geometry.
  19619. * Defaults to the length of the given geometry vertex buffer.
  19620. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  19621. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  19622. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  19623. * the length of the given geometry index buffer.
  19624. * @return {number} The geometry ID.
  19625. */
  19626. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  19627. this._initializeGeometry( geometry );
  19628. this._validateGeometry( geometry );
  19629. const geometryInfo = {
  19630. // geometry information
  19631. vertexStart: -1,
  19632. vertexCount: -1,
  19633. reservedVertexCount: -1,
  19634. indexStart: -1,
  19635. indexCount: -1,
  19636. reservedIndexCount: -1,
  19637. // draw range information
  19638. start: -1,
  19639. count: -1,
  19640. // state
  19641. boundingBox: null,
  19642. boundingSphere: null,
  19643. active: true,
  19644. };
  19645. const geometryInfoList = this._geometryInfo;
  19646. geometryInfo.vertexStart = this._nextVertexStart;
  19647. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  19648. const index = geometry.getIndex();
  19649. const hasIndex = index !== null;
  19650. if ( hasIndex ) {
  19651. geometryInfo.indexStart = this._nextIndexStart;
  19652. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  19653. }
  19654. if (
  19655. geometryInfo.indexStart !== -1 &&
  19656. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  19657. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  19658. ) {
  19659. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19660. }
  19661. // update id
  19662. let geometryId;
  19663. if ( this._availableGeometryIds.length > 0 ) {
  19664. this._availableGeometryIds.sort( ascIdSort );
  19665. geometryId = this._availableGeometryIds.shift();
  19666. geometryInfoList[ geometryId ] = geometryInfo;
  19667. } else {
  19668. geometryId = this._geometryCount;
  19669. this._geometryCount ++;
  19670. geometryInfoList.push( geometryInfo );
  19671. }
  19672. // update the geometry
  19673. this.setGeometryAt( geometryId, geometry );
  19674. // increment the next geometry position
  19675. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  19676. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  19677. return geometryId;
  19678. }
  19679. /**
  19680. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  19681. * is not enough space reserved for geometry. Calling this will change all instances that are
  19682. * rendering that geometry.
  19683. *
  19684. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  19685. * @param {BufferGeometry} geometry - The new geometry.
  19686. * @return {number} The geometry ID.
  19687. */
  19688. setGeometryAt( geometryId, geometry ) {
  19689. if ( geometryId >= this._geometryCount ) {
  19690. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  19691. }
  19692. this._validateGeometry( geometry );
  19693. const batchGeometry = this.geometry;
  19694. const hasIndex = batchGeometry.getIndex() !== null;
  19695. const dstIndex = batchGeometry.getIndex();
  19696. const srcIndex = geometry.getIndex();
  19697. const geometryInfo = this._geometryInfo[ geometryId ];
  19698. if (
  19699. hasIndex &&
  19700. srcIndex.count > geometryInfo.reservedIndexCount ||
  19701. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  19702. ) {
  19703. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  19704. }
  19705. // copy geometry buffer data over
  19706. const vertexStart = geometryInfo.vertexStart;
  19707. const reservedVertexCount = geometryInfo.reservedVertexCount;
  19708. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  19709. for ( const attributeName in batchGeometry.attributes ) {
  19710. // copy attribute data
  19711. const srcAttribute = geometry.getAttribute( attributeName );
  19712. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19713. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19714. // fill the rest in with zeroes
  19715. const itemSize = srcAttribute.itemSize;
  19716. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  19717. const index = vertexStart + i;
  19718. for ( let c = 0; c < itemSize; c ++ ) {
  19719. dstAttribute.setComponent( index, c, 0 );
  19720. }
  19721. }
  19722. dstAttribute.needsUpdate = true;
  19723. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  19724. }
  19725. // copy index
  19726. if ( hasIndex ) {
  19727. const indexStart = geometryInfo.indexStart;
  19728. const reservedIndexCount = geometryInfo.reservedIndexCount;
  19729. geometryInfo.indexCount = geometry.getIndex().count;
  19730. // copy index data over
  19731. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19732. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19733. }
  19734. // fill the rest in with zeroes
  19735. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  19736. dstIndex.setX( indexStart + i, vertexStart );
  19737. }
  19738. dstIndex.needsUpdate = true;
  19739. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  19740. }
  19741. // update the draw range
  19742. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19743. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  19744. // store the bounding boxes
  19745. geometryInfo.boundingBox = null;
  19746. if ( geometry.boundingBox !== null ) {
  19747. geometryInfo.boundingBox = geometry.boundingBox.clone();
  19748. }
  19749. geometryInfo.boundingSphere = null;
  19750. if ( geometry.boundingSphere !== null ) {
  19751. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  19752. }
  19753. this._visibilityChanged = true;
  19754. return geometryId;
  19755. }
  19756. /**
  19757. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  19758. * this geometry will also be removed as a side effect.
  19759. *
  19760. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  19761. * @return {BatchedMesh} A reference to this batched mesh.
  19762. */
  19763. deleteGeometry( geometryId ) {
  19764. const geometryInfoList = this._geometryInfo;
  19765. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19766. return this;
  19767. }
  19768. // delete any instances associated with this geometry
  19769. const instanceInfo = this._instanceInfo;
  19770. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19771. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  19772. this.deleteInstance( i );
  19773. }
  19774. }
  19775. geometryInfoList[ geometryId ].active = false;
  19776. this._availableGeometryIds.push( geometryId );
  19777. this._visibilityChanged = true;
  19778. return this;
  19779. }
  19780. /**
  19781. * Deletes an existing instance from the batch using the given ID.
  19782. *
  19783. * @param {number} instanceId - The ID of the instance to remove from the batch.
  19784. * @return {BatchedMesh} A reference to this batched mesh.
  19785. */
  19786. deleteInstance( instanceId ) {
  19787. this.validateInstanceId( instanceId );
  19788. this._instanceInfo[ instanceId ].active = false;
  19789. this._availableInstanceIds.push( instanceId );
  19790. this._visibilityChanged = true;
  19791. return this;
  19792. }
  19793. /**
  19794. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  19795. * previously deleted geometry, freeing up space to add new geometry.
  19796. *
  19797. * @return {BatchedMesh} A reference to this batched mesh.
  19798. */
  19799. optimize() {
  19800. // track the next indices to copy data to
  19801. let nextVertexStart = 0;
  19802. let nextIndexStart = 0;
  19803. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  19804. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  19805. const geometryInfoList = this._geometryInfo;
  19806. const indices = geometryInfoList
  19807. .map( ( e, i ) => i )
  19808. .sort( ( a, b ) => {
  19809. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  19810. } );
  19811. const geometry = this.geometry;
  19812. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  19813. // if a geometry range is inactive then don't copy anything
  19814. const index = indices[ i ];
  19815. const geometryInfo = geometryInfoList[ index ];
  19816. if ( geometryInfo.active === false ) {
  19817. continue;
  19818. }
  19819. // if a geometry contains an index buffer then shift it, as well
  19820. if ( geometry.index !== null ) {
  19821. if ( geometryInfo.indexStart !== nextIndexStart ) {
  19822. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  19823. const index = geometry.index;
  19824. const array = index.array;
  19825. // shift the index pointers based on how the vertex data will shift
  19826. // adjusting the index must happen first so the original vertex start value is available
  19827. const elementDelta = nextVertexStart - vertexStart;
  19828. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  19829. array[ j ] = array[ j ] + elementDelta;
  19830. }
  19831. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  19832. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  19833. index.needsUpdate = true;
  19834. geometryInfo.indexStart = nextIndexStart;
  19835. }
  19836. nextIndexStart += geometryInfo.reservedIndexCount;
  19837. }
  19838. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  19839. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  19840. const { vertexStart, reservedVertexCount } = geometryInfo;
  19841. const attributes = geometry.attributes;
  19842. for ( const key in attributes ) {
  19843. const attribute = attributes[ key ];
  19844. const { array, itemSize } = attribute;
  19845. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  19846. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  19847. attribute.needsUpdate = true;
  19848. }
  19849. geometryInfo.vertexStart = nextVertexStart;
  19850. }
  19851. nextVertexStart += geometryInfo.reservedVertexCount;
  19852. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19853. }
  19854. this._nextIndexStart = nextIndexStart;
  19855. this._nextVertexStart = nextVertexStart;
  19856. this._visibilityChanged = true;
  19857. return this;
  19858. }
  19859. /**
  19860. * Returns the bounding box for the given geometry.
  19861. *
  19862. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  19863. * @param {Box3} target - The target object that is used to store the method's result.
  19864. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  19865. */
  19866. getBoundingBoxAt( geometryId, target ) {
  19867. if ( geometryId >= this._geometryCount ) {
  19868. return null;
  19869. }
  19870. // compute bounding box
  19871. const geometry = this.geometry;
  19872. const geometryInfo = this._geometryInfo[ geometryId ];
  19873. if ( geometryInfo.boundingBox === null ) {
  19874. const box = new Box3();
  19875. const index = geometry.index;
  19876. const position = geometry.attributes.position;
  19877. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19878. let iv = i;
  19879. if ( index ) {
  19880. iv = index.getX( iv );
  19881. }
  19882. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19883. }
  19884. geometryInfo.boundingBox = box;
  19885. }
  19886. target.copy( geometryInfo.boundingBox );
  19887. return target;
  19888. }
  19889. /**
  19890. * Returns the bounding sphere for the given geometry.
  19891. *
  19892. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  19893. * @param {Sphere} target - The target object that is used to store the method's result.
  19894. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  19895. */
  19896. getBoundingSphereAt( geometryId, target ) {
  19897. if ( geometryId >= this._geometryCount ) {
  19898. return null;
  19899. }
  19900. // compute bounding sphere
  19901. const geometry = this.geometry;
  19902. const geometryInfo = this._geometryInfo[ geometryId ];
  19903. if ( geometryInfo.boundingSphere === null ) {
  19904. const sphere = new Sphere();
  19905. this.getBoundingBoxAt( geometryId, _box$1 );
  19906. _box$1.getCenter( sphere.center );
  19907. const index = geometry.index;
  19908. const position = geometry.attributes.position;
  19909. let maxRadiusSq = 0;
  19910. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19911. let iv = i;
  19912. if ( index ) {
  19913. iv = index.getX( iv );
  19914. }
  19915. _vector$5.fromBufferAttribute( position, iv );
  19916. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19917. }
  19918. sphere.radius = Math.sqrt( maxRadiusSq );
  19919. geometryInfo.boundingSphere = sphere;
  19920. }
  19921. target.copy( geometryInfo.boundingSphere );
  19922. return target;
  19923. }
  19924. /**
  19925. * Sets the given local transformation matrix to the defined instance.
  19926. * Negatively scaled matrices are not supported.
  19927. *
  19928. * @param {number} instanceId - The ID of an instance to set the matrix of.
  19929. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  19930. * @return {BatchedMesh} A reference to this batched mesh.
  19931. */
  19932. setMatrixAt( instanceId, matrix ) {
  19933. this.validateInstanceId( instanceId );
  19934. const matricesTexture = this._matricesTexture;
  19935. const matricesArray = this._matricesTexture.image.data;
  19936. matrix.toArray( matricesArray, instanceId * 16 );
  19937. matricesTexture.needsUpdate = true;
  19938. return this;
  19939. }
  19940. /**
  19941. * Returns the local transformation matrix of the defined instance.
  19942. *
  19943. * @param {number} instanceId - The ID of an instance to get the matrix of.
  19944. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19945. * @return {Matrix4} The instance's local transformation matrix.
  19946. */
  19947. getMatrixAt( instanceId, matrix ) {
  19948. this.validateInstanceId( instanceId );
  19949. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  19950. }
  19951. /**
  19952. * Sets the given color to the defined instance.
  19953. *
  19954. * @param {number} instanceId - The ID of an instance to set the color of.
  19955. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  19956. * @return {BatchedMesh} A reference to this batched mesh.
  19957. */
  19958. setColorAt( instanceId, color ) {
  19959. this.validateInstanceId( instanceId );
  19960. if ( this._colorsTexture === null ) {
  19961. this._initColorsTexture();
  19962. }
  19963. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  19964. this._colorsTexture.needsUpdate = true;
  19965. return this;
  19966. }
  19967. /**
  19968. * Returns the color of the defined instance.
  19969. *
  19970. * @param {number} instanceId - The ID of an instance to get the color of.
  19971. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  19972. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  19973. */
  19974. getColorAt( instanceId, color ) {
  19975. this.validateInstanceId( instanceId );
  19976. if ( this._colorsTexture === null ) {
  19977. if ( color.isVector4 ) {
  19978. return color.set( 1, 1, 1, 1 );
  19979. } else {
  19980. return color.setRGB( 1, 1, 1 );
  19981. }
  19982. } else {
  19983. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  19984. }
  19985. }
  19986. /**
  19987. * Sets the visibility of the instance.
  19988. *
  19989. * @param {number} instanceId - The id of the instance to set the visibility of.
  19990. * @param {boolean} visible - Whether the instance is visible or not.
  19991. * @return {BatchedMesh} A reference to this batched mesh.
  19992. */
  19993. setVisibleAt( instanceId, visible ) {
  19994. this.validateInstanceId( instanceId );
  19995. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  19996. return this;
  19997. }
  19998. this._instanceInfo[ instanceId ].visible = visible;
  19999. this._visibilityChanged = true;
  20000. return this;
  20001. }
  20002. /**
  20003. * Returns the visibility state of the defined instance.
  20004. *
  20005. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20006. * @return {boolean} Whether the instance is visible or not.
  20007. */
  20008. getVisibleAt( instanceId ) {
  20009. this.validateInstanceId( instanceId );
  20010. return this._instanceInfo[ instanceId ].visible;
  20011. }
  20012. /**
  20013. * Sets the geometry ID of the instance at the given index.
  20014. *
  20015. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20016. * @param {number} geometryId - The geometry ID to be use by the instance.
  20017. * @return {BatchedMesh} A reference to this batched mesh.
  20018. */
  20019. setGeometryIdAt( instanceId, geometryId ) {
  20020. this.validateInstanceId( instanceId );
  20021. this.validateGeometryId( geometryId );
  20022. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20023. return this;
  20024. }
  20025. /**
  20026. * Returns the geometry ID of the defined instance.
  20027. *
  20028. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20029. * @return {number} The instance's geometry ID.
  20030. */
  20031. getGeometryIdAt( instanceId ) {
  20032. this.validateInstanceId( instanceId );
  20033. return this._instanceInfo[ instanceId ].geometryIndex;
  20034. }
  20035. /**
  20036. * Get the range representing the subset of triangles related to the attached geometry,
  20037. * indicating the starting offset and count, or `null` if invalid.
  20038. *
  20039. * @param {number} geometryId - The id of the geometry to get the range of.
  20040. * @param {Object} [target] - The target object that is used to store the method's result.
  20041. * @return {{
  20042. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20043. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20044. * start:number,count:number
  20045. * }} The result object with range data.
  20046. */
  20047. getGeometryRangeAt( geometryId, target = {} ) {
  20048. this.validateGeometryId( geometryId );
  20049. const geometryInfo = this._geometryInfo[ geometryId ];
  20050. target.vertexStart = geometryInfo.vertexStart;
  20051. target.vertexCount = geometryInfo.vertexCount;
  20052. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20053. target.indexStart = geometryInfo.indexStart;
  20054. target.indexCount = geometryInfo.indexCount;
  20055. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20056. target.start = geometryInfo.start;
  20057. target.count = geometryInfo.count;
  20058. return target;
  20059. }
  20060. /**
  20061. * Resizes the necessary buffers to support the provided number of instances.
  20062. * If the provided arguments shrink the number of instances but there are not enough
  20063. * unused Ids at the end of the list then an error is thrown.
  20064. *
  20065. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20066. */
  20067. setInstanceCount( maxInstanceCount ) {
  20068. // shrink the available instances as much as possible
  20069. const availableInstanceIds = this._availableInstanceIds;
  20070. const instanceInfo = this._instanceInfo;
  20071. availableInstanceIds.sort( ascIdSort );
  20072. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20073. instanceInfo.pop();
  20074. availableInstanceIds.pop();
  20075. }
  20076. // throw an error if it can't be shrunk to the desired size
  20077. if ( maxInstanceCount < instanceInfo.length ) {
  20078. throw new Error( `THREE.BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20079. }
  20080. // copy the multi draw counts
  20081. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20082. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20083. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20084. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20085. this._multiDrawCounts = multiDrawCounts;
  20086. this._multiDrawStarts = multiDrawStarts;
  20087. this._maxInstanceCount = maxInstanceCount;
  20088. // update texture data for instance sampling
  20089. const indirectTexture = this._indirectTexture;
  20090. const matricesTexture = this._matricesTexture;
  20091. const colorsTexture = this._colorsTexture;
  20092. indirectTexture.dispose();
  20093. this._initIndirectTexture();
  20094. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20095. matricesTexture.dispose();
  20096. this._initMatricesTexture();
  20097. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20098. if ( colorsTexture ) {
  20099. colorsTexture.dispose();
  20100. this._initColorsTexture();
  20101. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20102. }
  20103. }
  20104. /**
  20105. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20106. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20107. * end of the geometry attributes then an error is thrown.
  20108. *
  20109. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20110. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20111. */
  20112. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20113. // Check if we can shrink to the requested vertex attribute size
  20114. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20115. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20116. if ( requiredVertexLength > maxVertexCount ) {
  20117. throw new Error( `THREE.BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20118. }
  20119. // Check if we can shrink to the requested index attribute size
  20120. if ( this.geometry.index ) {
  20121. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20122. if ( requiredIndexLength > maxIndexCount ) {
  20123. throw new Error( `THREE.BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20124. }
  20125. }
  20126. //
  20127. // dispose of the previous geometry
  20128. const oldGeometry = this.geometry;
  20129. oldGeometry.dispose();
  20130. // recreate the geometry needed based on the previous variant
  20131. this._maxVertexCount = maxVertexCount;
  20132. this._maxIndexCount = maxIndexCount;
  20133. if ( this._geometryInitialized ) {
  20134. this._geometryInitialized = false;
  20135. this.geometry = new BufferGeometry();
  20136. this._initializeGeometry( oldGeometry );
  20137. }
  20138. // copy data from the previous geometry
  20139. const geometry = this.geometry;
  20140. if ( oldGeometry.index ) {
  20141. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20142. }
  20143. for ( const key in oldGeometry.attributes ) {
  20144. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20145. }
  20146. }
  20147. raycast( raycaster, intersects ) {
  20148. const instanceInfo = this._instanceInfo;
  20149. const geometryInfoList = this._geometryInfo;
  20150. const matrixWorld = this.matrixWorld;
  20151. const batchGeometry = this.geometry;
  20152. // iterate over each geometry
  20153. _mesh.material = this.material;
  20154. _mesh.geometry.index = batchGeometry.index;
  20155. _mesh.geometry.attributes = batchGeometry.attributes;
  20156. if ( _mesh.geometry.boundingBox === null ) {
  20157. _mesh.geometry.boundingBox = new Box3();
  20158. }
  20159. if ( _mesh.geometry.boundingSphere === null ) {
  20160. _mesh.geometry.boundingSphere = new Sphere();
  20161. }
  20162. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20163. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20164. continue;
  20165. }
  20166. const geometryId = instanceInfo[ i ].geometryIndex;
  20167. const geometryInfo = geometryInfoList[ geometryId ];
  20168. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20169. // get the intersects
  20170. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20171. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20172. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20173. _mesh.raycast( raycaster, _batchIntersects );
  20174. // add batch id to the intersects
  20175. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20176. const intersect = _batchIntersects[ j ];
  20177. intersect.object = this;
  20178. intersect.batchId = i;
  20179. intersects.push( intersect );
  20180. }
  20181. _batchIntersects.length = 0;
  20182. }
  20183. _mesh.material = null;
  20184. _mesh.geometry.index = null;
  20185. _mesh.geometry.attributes = {};
  20186. _mesh.geometry.setDrawRange( 0, Infinity );
  20187. }
  20188. copy( source ) {
  20189. super.copy( source );
  20190. this.geometry = source.geometry.clone();
  20191. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20192. this.sortObjects = source.sortObjects;
  20193. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20194. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20195. this._geometryInfo = source._geometryInfo.map( info => ( {
  20196. ...info,
  20197. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20198. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20199. } ) );
  20200. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20201. this._availableInstanceIds = source._availableInstanceIds.slice();
  20202. this._availableGeometryIds = source._availableGeometryIds.slice();
  20203. this._nextIndexStart = source._nextIndexStart;
  20204. this._nextVertexStart = source._nextVertexStart;
  20205. this._geometryCount = source._geometryCount;
  20206. this._maxInstanceCount = source._maxInstanceCount;
  20207. this._maxVertexCount = source._maxVertexCount;
  20208. this._maxIndexCount = source._maxIndexCount;
  20209. this._geometryInitialized = source._geometryInitialized;
  20210. this._multiDrawCounts = source._multiDrawCounts.slice();
  20211. this._multiDrawStarts = source._multiDrawStarts.slice();
  20212. this._indirectTexture = source._indirectTexture.clone();
  20213. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20214. this._matricesTexture = source._matricesTexture.clone();
  20215. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20216. if ( this._colorsTexture !== null ) {
  20217. this._colorsTexture = source._colorsTexture.clone();
  20218. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20219. }
  20220. return this;
  20221. }
  20222. /**
  20223. * Frees the GPU-related resources allocated by this instance. Call this
  20224. * method whenever this instance is no longer used in your app.
  20225. */
  20226. dispose() {
  20227. // Assuming the geometry is not shared with other meshes
  20228. this.geometry.dispose();
  20229. this._matricesTexture.dispose();
  20230. this._matricesTexture = null;
  20231. this._indirectTexture.dispose();
  20232. this._indirectTexture = null;
  20233. if ( this._colorsTexture !== null ) {
  20234. this._colorsTexture.dispose();
  20235. this._colorsTexture = null;
  20236. }
  20237. }
  20238. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20239. // if visibility has not changed and frustum culling and object sorting is not required
  20240. // then skip iterating over all items
  20241. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20242. return;
  20243. }
  20244. // the indexed version of the multi draw function requires specifying the start
  20245. // offset in bytes.
  20246. const index = geometry.getIndex();
  20247. let bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20248. // the "wireframe" attribute implicitly creates a line attribute in the renderer, which is double
  20249. // the vertices to draw (3 lines per triangle) so we multiply the draw counts / starts and make
  20250. // assumptions about the index buffer byte size.
  20251. let multiDrawMultiplier = 1;
  20252. if ( material.wireframe ) {
  20253. multiDrawMultiplier = 2;
  20254. bytesPerElement = geometry.attributes.position.count > 65535 ? 4 : 2;
  20255. }
  20256. const instanceInfo = this._instanceInfo;
  20257. const multiDrawStarts = this._multiDrawStarts;
  20258. const multiDrawCounts = this._multiDrawCounts;
  20259. const geometryInfoList = this._geometryInfo;
  20260. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20261. const indirectTexture = this._indirectTexture;
  20262. const indirectArray = indirectTexture.image.data;
  20263. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20264. // prepare the frustum in the local frame
  20265. if ( perObjectFrustumCulled ) {
  20266. if ( camera.isArrayCamera ) {
  20267. frustum.setFromArrayCamera( camera );
  20268. } else {
  20269. _matrix$1
  20270. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20271. .multiply( this.matrixWorld );
  20272. frustum.setFromProjectionMatrix(
  20273. _matrix$1,
  20274. camera.coordinateSystem,
  20275. camera.reversedDepth
  20276. );
  20277. }
  20278. }
  20279. let multiDrawCount = 0;
  20280. if ( this.sortObjects ) {
  20281. // get the camera position in the local frame
  20282. _matrix$1.copy( this.matrixWorld ).invert();
  20283. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20284. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20285. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20286. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20287. const geometryId = instanceInfo[ i ].geometryIndex;
  20288. // get the bounds in world space
  20289. this.getMatrixAt( i, _matrix$1 );
  20290. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20291. // determine whether the batched geometry is within the frustum
  20292. let culled = false;
  20293. if ( perObjectFrustumCulled ) {
  20294. culled = ! frustum.intersectsSphere( _sphere$2 );
  20295. }
  20296. if ( ! culled ) {
  20297. // get the distance from camera used for sorting
  20298. const geometryInfo = geometryInfoList[ geometryId ];
  20299. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20300. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20301. }
  20302. }
  20303. }
  20304. // Sort the draw ranges and prep for rendering
  20305. const list = _renderList.list;
  20306. const customSort = this.customSort;
  20307. if ( customSort === null ) {
  20308. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20309. } else {
  20310. customSort.call( this, list, camera );
  20311. }
  20312. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20313. const item = list[ i ];
  20314. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement * multiDrawMultiplier;
  20315. multiDrawCounts[ multiDrawCount ] = item.count * multiDrawMultiplier;
  20316. indirectArray[ multiDrawCount ] = item.index;
  20317. multiDrawCount ++;
  20318. }
  20319. _renderList.reset();
  20320. } else {
  20321. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20322. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20323. const geometryId = instanceInfo[ i ].geometryIndex;
  20324. // determine whether the batched geometry is within the frustum
  20325. let culled = false;
  20326. if ( perObjectFrustumCulled ) {
  20327. // get the bounds in world space
  20328. this.getMatrixAt( i, _matrix$1 );
  20329. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20330. culled = ! frustum.intersectsSphere( _sphere$2 );
  20331. }
  20332. if ( ! culled ) {
  20333. const geometryInfo = geometryInfoList[ geometryId ];
  20334. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement * multiDrawMultiplier;
  20335. multiDrawCounts[ multiDrawCount ] = geometryInfo.count * multiDrawMultiplier;
  20336. indirectArray[ multiDrawCount ] = i;
  20337. multiDrawCount ++;
  20338. }
  20339. }
  20340. }
  20341. }
  20342. indirectTexture.needsUpdate = true;
  20343. this._multiDrawCount = multiDrawCount;
  20344. this._visibilityChanged = false;
  20345. }
  20346. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20347. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20348. }
  20349. }
  20350. /**
  20351. * A material for rendering line primitives.
  20352. *
  20353. * Materials define the appearance of renderable 3D objects.
  20354. *
  20355. * ```js
  20356. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20357. * ```
  20358. *
  20359. * @augments Material
  20360. */
  20361. class LineBasicMaterial extends Material {
  20362. /**
  20363. * Constructs a new line basic material.
  20364. *
  20365. * @param {Object} [parameters] - An object with one or more properties
  20366. * defining the material's appearance. Any property of the material
  20367. * (including any property from inherited materials) can be passed
  20368. * in here. Color values can be passed any type of value accepted
  20369. * by {@link Color#set}.
  20370. */
  20371. constructor( parameters ) {
  20372. super();
  20373. /**
  20374. * This flag can be used for type testing.
  20375. *
  20376. * @type {boolean}
  20377. * @readonly
  20378. * @default true
  20379. */
  20380. this.isLineBasicMaterial = true;
  20381. this.type = 'LineBasicMaterial';
  20382. /**
  20383. * Color of the material.
  20384. *
  20385. * @type {Color}
  20386. * @default (1,1,1)
  20387. */
  20388. this.color = new Color( 0xffffff );
  20389. /**
  20390. * Sets the color of the lines using data from a texture. The texture map
  20391. * color is modulated by the diffuse `color`.
  20392. *
  20393. * `map` represents color data, and the texture must be assigned a
  20394. * {@link Texture#colorSpace}. Most `map` textures set
  20395. * `texture.colorSpace = SRGBColorSpace`.
  20396. *
  20397. * @type {?Texture}
  20398. * @default null
  20399. */
  20400. this.map = null;
  20401. /**
  20402. * Controls line thickness or lines.
  20403. *
  20404. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20405. * ignore this setting and always render line primitives with a
  20406. * width of one pixel.
  20407. *
  20408. * @type {number}
  20409. * @default 1
  20410. */
  20411. this.linewidth = 1;
  20412. /**
  20413. * Defines appearance of line ends.
  20414. *
  20415. * Can only be used with {@link SVGRenderer}.
  20416. *
  20417. * @type {('butt'|'round'|'square')}
  20418. * @default 'round'
  20419. */
  20420. this.linecap = 'round';
  20421. /**
  20422. * Defines appearance of line joints.
  20423. *
  20424. * Can only be used with {@link SVGRenderer}.
  20425. *
  20426. * @type {('round'|'bevel'|'miter')}
  20427. * @default 'round'
  20428. */
  20429. this.linejoin = 'round';
  20430. /**
  20431. * Whether the material is affected by fog or not.
  20432. *
  20433. * @type {boolean}
  20434. * @default true
  20435. */
  20436. this.fog = true;
  20437. this.setValues( parameters );
  20438. }
  20439. copy( source ) {
  20440. super.copy( source );
  20441. this.color.copy( source.color );
  20442. this.map = source.map;
  20443. this.linewidth = source.linewidth;
  20444. this.linecap = source.linecap;
  20445. this.linejoin = source.linejoin;
  20446. this.fog = source.fog;
  20447. return this;
  20448. }
  20449. }
  20450. const _vStart = /*@__PURE__*/ new Vector3();
  20451. const _vEnd = /*@__PURE__*/ new Vector3();
  20452. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20453. const _ray$1 = /*@__PURE__*/ new Ray();
  20454. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20455. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20456. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20457. /**
  20458. * A continuous line. The line are rendered by connecting consecutive
  20459. * vertices with straight lines.
  20460. *
  20461. * ```js
  20462. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20463. *
  20464. * const points = [];
  20465. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20466. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20467. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20468. *
  20469. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20470. *
  20471. * const line = new THREE.Line( geometry, material );
  20472. * scene.add( line );
  20473. * ```
  20474. *
  20475. * @augments Object3D
  20476. */
  20477. class Line extends Object3D {
  20478. /**
  20479. * Constructs a new line.
  20480. *
  20481. * @param {BufferGeometry} [geometry] - The line geometry.
  20482. * @param {Material|Array<Material>} [material] - The line material.
  20483. */
  20484. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20485. super();
  20486. /**
  20487. * This flag can be used for type testing.
  20488. *
  20489. * @type {boolean}
  20490. * @readonly
  20491. * @default true
  20492. */
  20493. this.isLine = true;
  20494. this.type = 'Line';
  20495. /**
  20496. * The line geometry.
  20497. *
  20498. * @type {BufferGeometry}
  20499. */
  20500. this.geometry = geometry;
  20501. /**
  20502. * The line material.
  20503. *
  20504. * @type {Material|Array<Material>}
  20505. * @default LineBasicMaterial
  20506. */
  20507. this.material = material;
  20508. /**
  20509. * A dictionary representing the morph targets in the geometry. The key is the
  20510. * morph targets name, the value its attribute index. This member is `undefined`
  20511. * by default and only set when morph targets are detected in the geometry.
  20512. *
  20513. * @type {Object<string,number>|undefined}
  20514. * @default undefined
  20515. */
  20516. this.morphTargetDictionary = undefined;
  20517. /**
  20518. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20519. * is applied. This member is `undefined` by default and only set when morph targets are
  20520. * detected in the geometry.
  20521. *
  20522. * @type {Array<number>|undefined}
  20523. * @default undefined
  20524. */
  20525. this.morphTargetInfluences = undefined;
  20526. this.updateMorphTargets();
  20527. }
  20528. copy( source, recursive ) {
  20529. super.copy( source, recursive );
  20530. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20531. this.geometry = source.geometry;
  20532. return this;
  20533. }
  20534. /**
  20535. * Computes an array of distance values which are necessary for rendering dashed lines.
  20536. * For each vertex in the geometry, the method calculates the cumulative length from the
  20537. * current point to the very beginning of the line.
  20538. *
  20539. * @return {Line} A reference to this line.
  20540. */
  20541. computeLineDistances() {
  20542. const geometry = this.geometry;
  20543. // we assume non-indexed geometry
  20544. if ( geometry.index === null ) {
  20545. const positionAttribute = geometry.attributes.position;
  20546. const lineDistances = [ 0 ];
  20547. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20548. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20549. _vEnd.fromBufferAttribute( positionAttribute, i );
  20550. lineDistances[ i ] = lineDistances[ i - 1 ];
  20551. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20552. }
  20553. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20554. } else {
  20555. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20556. }
  20557. return this;
  20558. }
  20559. /**
  20560. * Computes intersection points between a casted ray and this line.
  20561. *
  20562. * @param {Raycaster} raycaster - The raycaster.
  20563. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20564. */
  20565. raycast( raycaster, intersects ) {
  20566. const geometry = this.geometry;
  20567. const matrixWorld = this.matrixWorld;
  20568. const threshold = raycaster.params.Line.threshold;
  20569. const drawRange = geometry.drawRange;
  20570. // Checking boundingSphere distance to ray
  20571. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20572. _sphere$1.copy( geometry.boundingSphere );
  20573. _sphere$1.applyMatrix4( matrixWorld );
  20574. _sphere$1.radius += threshold;
  20575. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20576. //
  20577. _inverseMatrix$1.copy( matrixWorld ).invert();
  20578. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20579. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20580. const localThresholdSq = localThreshold * localThreshold;
  20581. const step = this.isLineSegments ? 2 : 1;
  20582. const index = geometry.index;
  20583. const attributes = geometry.attributes;
  20584. const positionAttribute = attributes.position;
  20585. if ( index !== null ) {
  20586. const start = Math.max( 0, drawRange.start );
  20587. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20588. for ( let i = start, l = end - 1; i < l; i += step ) {
  20589. const a = index.getX( i );
  20590. const b = index.getX( i + 1 );
  20591. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  20592. if ( intersect ) {
  20593. intersects.push( intersect );
  20594. }
  20595. }
  20596. if ( this.isLineLoop ) {
  20597. const a = index.getX( end - 1 );
  20598. const b = index.getX( start );
  20599. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  20600. if ( intersect ) {
  20601. intersects.push( intersect );
  20602. }
  20603. }
  20604. } else {
  20605. const start = Math.max( 0, drawRange.start );
  20606. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20607. for ( let i = start, l = end - 1; i < l; i += step ) {
  20608. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  20609. if ( intersect ) {
  20610. intersects.push( intersect );
  20611. }
  20612. }
  20613. if ( this.isLineLoop ) {
  20614. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  20615. if ( intersect ) {
  20616. intersects.push( intersect );
  20617. }
  20618. }
  20619. }
  20620. }
  20621. /**
  20622. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  20623. * to make sure existing morph targets can influence this 3D object.
  20624. */
  20625. updateMorphTargets() {
  20626. const geometry = this.geometry;
  20627. const morphAttributes = geometry.morphAttributes;
  20628. const keys = Object.keys( morphAttributes );
  20629. if ( keys.length > 0 ) {
  20630. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20631. if ( morphAttribute !== undefined ) {
  20632. this.morphTargetInfluences = [];
  20633. this.morphTargetDictionary = {};
  20634. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20635. const name = morphAttribute[ m ].name || String( m );
  20636. this.morphTargetInfluences.push( 0 );
  20637. this.morphTargetDictionary[ name ] = m;
  20638. }
  20639. }
  20640. }
  20641. }
  20642. }
  20643. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  20644. const positionAttribute = object.geometry.attributes.position;
  20645. _vStart.fromBufferAttribute( positionAttribute, a );
  20646. _vEnd.fromBufferAttribute( positionAttribute, b );
  20647. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20648. if ( distSq > thresholdSq ) return;
  20649. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20650. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20651. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20652. return {
  20653. distance: distance,
  20654. // What do we want? intersection point on the ray or on the segment??
  20655. // point: raycaster.ray.at( distance ),
  20656. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20657. index: i,
  20658. face: null,
  20659. faceIndex: null,
  20660. barycoord: null,
  20661. object: object
  20662. };
  20663. }
  20664. const _start = /*@__PURE__*/ new Vector3();
  20665. const _end = /*@__PURE__*/ new Vector3();
  20666. /**
  20667. * A series of lines drawn between pairs of vertices.
  20668. *
  20669. * @augments Line
  20670. */
  20671. class LineSegments extends Line {
  20672. /**
  20673. * Constructs a new line segments.
  20674. *
  20675. * @param {BufferGeometry} [geometry] - The line geometry.
  20676. * @param {Material|Array<Material>} [material] - The line material.
  20677. */
  20678. constructor( geometry, material ) {
  20679. super( geometry, material );
  20680. /**
  20681. * This flag can be used for type testing.
  20682. *
  20683. * @type {boolean}
  20684. * @readonly
  20685. * @default true
  20686. */
  20687. this.isLineSegments = true;
  20688. this.type = 'LineSegments';
  20689. }
  20690. computeLineDistances() {
  20691. const geometry = this.geometry;
  20692. // we assume non-indexed geometry
  20693. if ( geometry.index === null ) {
  20694. const positionAttribute = geometry.attributes.position;
  20695. const lineDistances = [];
  20696. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20697. _start.fromBufferAttribute( positionAttribute, i );
  20698. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20699. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20700. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20701. }
  20702. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20703. } else {
  20704. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20705. }
  20706. return this;
  20707. }
  20708. }
  20709. /**
  20710. * A continuous line. This is nearly the same as {@link Line} the only difference
  20711. * is that the last vertex is connected with the first vertex in order to close
  20712. * the line to form a loop.
  20713. *
  20714. * @augments Line
  20715. */
  20716. class LineLoop extends Line {
  20717. /**
  20718. * Constructs a new line loop.
  20719. *
  20720. * @param {BufferGeometry} [geometry] - The line geometry.
  20721. * @param {Material|Array<Material>} [material] - The line material.
  20722. */
  20723. constructor( geometry, material ) {
  20724. super( geometry, material );
  20725. /**
  20726. * This flag can be used for type testing.
  20727. *
  20728. * @type {boolean}
  20729. * @readonly
  20730. * @default true
  20731. */
  20732. this.isLineLoop = true;
  20733. this.type = 'LineLoop';
  20734. }
  20735. }
  20736. /**
  20737. * A material for rendering point primitives.
  20738. *
  20739. * Materials define the appearance of renderable 3D objects.
  20740. *
  20741. * ```js
  20742. * const vertices = [];
  20743. *
  20744. * for ( let i = 0; i < 10000; i ++ ) {
  20745. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  20746. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  20747. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  20748. *
  20749. * vertices.push( x, y, z );
  20750. * }
  20751. *
  20752. * const geometry = new THREE.BufferGeometry();
  20753. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  20754. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  20755. * const points = new THREE.Points( geometry, material );
  20756. * scene.add( points );
  20757. * ```
  20758. *
  20759. * @augments Material
  20760. */
  20761. class PointsMaterial extends Material {
  20762. /**
  20763. * Constructs a new points material.
  20764. *
  20765. * @param {Object} [parameters] - An object with one or more properties
  20766. * defining the material's appearance. Any property of the material
  20767. * (including any property from inherited materials) can be passed
  20768. * in here. Color values can be passed any type of value accepted
  20769. * by {@link Color#set}.
  20770. */
  20771. constructor( parameters ) {
  20772. super();
  20773. /**
  20774. * This flag can be used for type testing.
  20775. *
  20776. * @type {boolean}
  20777. * @readonly
  20778. * @default true
  20779. */
  20780. this.isPointsMaterial = true;
  20781. this.type = 'PointsMaterial';
  20782. /**
  20783. * Color of the material.
  20784. *
  20785. * @type {Color}
  20786. * @default (1,1,1)
  20787. */
  20788. this.color = new Color( 0xffffff );
  20789. /**
  20790. * The color map. May optionally include an alpha channel, typically combined
  20791. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  20792. * color is modulated by the diffuse `color`.
  20793. *
  20794. * `map` represents color data, and the texture must be assigned a
  20795. * {@link Texture#colorSpace}. Most `map` textures set
  20796. * `texture.colorSpace = SRGBColorSpace`.
  20797. *
  20798. * @type {?Texture}
  20799. * @default null
  20800. */
  20801. this.map = null;
  20802. /**
  20803. * The alpha map is a grayscale texture that controls the opacity across the
  20804. * surface (black: fully transparent; white: fully opaque).
  20805. *
  20806. * Only the color of the texture is used, ignoring the alpha channel if one
  20807. * exists. For RGB and RGBA textures, the renderer will use the green channel
  20808. * when sampling this texture due to the extra bit of precision provided for
  20809. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  20810. * luminance/alpha textures will also still work as expected.
  20811. *
  20812. * `alphaMap` represents non-color data. Any texture assigned must have
  20813. * `texture.colorSpace = NoColorSpace` (default).
  20814. *
  20815. * @type {?Texture}
  20816. * @default null
  20817. */
  20818. this.alphaMap = null;
  20819. /**
  20820. * Defines the size of the points in pixels.
  20821. *
  20822. * 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).
  20823. *
  20824. * @type {number}
  20825. * @default 1
  20826. */
  20827. this.size = 1;
  20828. /**
  20829. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  20830. *
  20831. * @type {boolean}
  20832. * @default true
  20833. */
  20834. this.sizeAttenuation = true;
  20835. /**
  20836. * Whether the material is affected by fog or not.
  20837. *
  20838. * @type {boolean}
  20839. * @default true
  20840. */
  20841. this.fog = true;
  20842. this.setValues( parameters );
  20843. }
  20844. copy( source ) {
  20845. super.copy( source );
  20846. this.color.copy( source.color );
  20847. this.map = source.map;
  20848. this.alphaMap = source.alphaMap;
  20849. this.size = source.size;
  20850. this.sizeAttenuation = source.sizeAttenuation;
  20851. this.fog = source.fog;
  20852. return this;
  20853. }
  20854. }
  20855. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20856. const _ray = /*@__PURE__*/ new Ray();
  20857. const _sphere = /*@__PURE__*/ new Sphere();
  20858. const _position$3 = /*@__PURE__*/ new Vector3();
  20859. /**
  20860. * A class for displaying points or point clouds.
  20861. *
  20862. * @augments Object3D
  20863. */
  20864. class Points extends Object3D {
  20865. /**
  20866. * Constructs a new point cloud.
  20867. *
  20868. * @param {BufferGeometry} [geometry] - The points geometry.
  20869. * @param {Material|Array<Material>} [material] - The points material.
  20870. */
  20871. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20872. super();
  20873. /**
  20874. * This flag can be used for type testing.
  20875. *
  20876. * @type {boolean}
  20877. * @readonly
  20878. * @default true
  20879. */
  20880. this.isPoints = true;
  20881. this.type = 'Points';
  20882. /**
  20883. * The points geometry.
  20884. *
  20885. * @type {BufferGeometry}
  20886. */
  20887. this.geometry = geometry;
  20888. /**
  20889. * The line material.
  20890. *
  20891. * @type {Material|Array<Material>}
  20892. * @default PointsMaterial
  20893. */
  20894. this.material = material;
  20895. /**
  20896. * A dictionary representing the morph targets in the geometry. The key is the
  20897. * morph targets name, the value its attribute index. This member is `undefined`
  20898. * by default and only set when morph targets are detected in the geometry.
  20899. *
  20900. * @type {Object<string,number>|undefined}
  20901. * @default undefined
  20902. */
  20903. this.morphTargetDictionary = undefined;
  20904. /**
  20905. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20906. * is applied. This member is `undefined` by default and only set when morph targets are
  20907. * detected in the geometry.
  20908. *
  20909. * @type {Array<number>|undefined}
  20910. * @default undefined
  20911. */
  20912. this.morphTargetInfluences = undefined;
  20913. this.updateMorphTargets();
  20914. }
  20915. copy( source, recursive ) {
  20916. super.copy( source, recursive );
  20917. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20918. this.geometry = source.geometry;
  20919. return this;
  20920. }
  20921. /**
  20922. * Computes intersection points between a casted ray and this point cloud.
  20923. *
  20924. * @param {Raycaster} raycaster - The raycaster.
  20925. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20926. */
  20927. raycast( raycaster, intersects ) {
  20928. const geometry = this.geometry;
  20929. const matrixWorld = this.matrixWorld;
  20930. const threshold = raycaster.params.Points.threshold;
  20931. const drawRange = geometry.drawRange;
  20932. // Checking boundingSphere distance to ray
  20933. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20934. _sphere.copy( geometry.boundingSphere );
  20935. _sphere.applyMatrix4( matrixWorld );
  20936. _sphere.radius += threshold;
  20937. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20938. //
  20939. _inverseMatrix.copy( matrixWorld ).invert();
  20940. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20941. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20942. const localThresholdSq = localThreshold * localThreshold;
  20943. const index = geometry.index;
  20944. const attributes = geometry.attributes;
  20945. const positionAttribute = attributes.position;
  20946. if ( index !== null ) {
  20947. const start = Math.max( 0, drawRange.start );
  20948. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20949. for ( let i = start, il = end; i < il; i ++ ) {
  20950. const a = index.getX( i );
  20951. _position$3.fromBufferAttribute( positionAttribute, a );
  20952. testPoint( _position$3, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20953. }
  20954. } else {
  20955. const start = Math.max( 0, drawRange.start );
  20956. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20957. for ( let i = start, l = end; i < l; i ++ ) {
  20958. _position$3.fromBufferAttribute( positionAttribute, i );
  20959. testPoint( _position$3, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20960. }
  20961. }
  20962. }
  20963. /**
  20964. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  20965. * to make sure existing morph targets can influence this 3D object.
  20966. */
  20967. updateMorphTargets() {
  20968. const geometry = this.geometry;
  20969. const morphAttributes = geometry.morphAttributes;
  20970. const keys = Object.keys( morphAttributes );
  20971. if ( keys.length > 0 ) {
  20972. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20973. if ( morphAttribute !== undefined ) {
  20974. this.morphTargetInfluences = [];
  20975. this.morphTargetDictionary = {};
  20976. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20977. const name = morphAttribute[ m ].name || String( m );
  20978. this.morphTargetInfluences.push( 0 );
  20979. this.morphTargetDictionary[ name ] = m;
  20980. }
  20981. }
  20982. }
  20983. }
  20984. }
  20985. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20986. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20987. if ( rayPointDistanceSq < localThresholdSq ) {
  20988. const intersectPoint = new Vector3();
  20989. _ray.closestPointToPoint( point, intersectPoint );
  20990. intersectPoint.applyMatrix4( matrixWorld );
  20991. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20992. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20993. intersects.push( {
  20994. distance: distance,
  20995. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20996. point: intersectPoint,
  20997. index: index,
  20998. face: null,
  20999. faceIndex: null,
  21000. barycoord: null,
  21001. object: object
  21002. } );
  21003. }
  21004. }
  21005. /**
  21006. * A texture for use with a video.
  21007. *
  21008. * ```js
  21009. * // assuming you have created a HTML video element with id="video"
  21010. * const video = document.getElementById( 'video' );
  21011. * const texture = new THREE.VideoTexture( video );
  21012. * ```
  21013. *
  21014. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21015. * set to THREE.SRGBColorSpace.
  21016. *
  21017. * Note: After the initial use of a texture, its dimensions, format, and type
  21018. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21019. *
  21020. * @augments Texture
  21021. */
  21022. class VideoTexture extends Texture {
  21023. /**
  21024. * Constructs a new video texture.
  21025. *
  21026. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21027. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21028. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21029. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21030. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21031. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21032. * @param {number} [format=RGBAFormat] - The texture format.
  21033. * @param {number} [type=UnsignedByteType] - The texture type.
  21034. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21035. */
  21036. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21037. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21038. /**
  21039. * This flag can be used for type testing.
  21040. *
  21041. * @type {boolean}
  21042. * @readonly
  21043. * @default true
  21044. */
  21045. this.isVideoTexture = true;
  21046. /**
  21047. * Whether to generate mipmaps (if possible) for a texture.
  21048. *
  21049. * Overwritten and set to `false` by default.
  21050. *
  21051. * @type {boolean}
  21052. * @default false
  21053. */
  21054. this.generateMipmaps = false;
  21055. /**
  21056. * The video frame request callback identifier, which is a positive integer.
  21057. *
  21058. * Value of 0 represents no scheduled rVFC.
  21059. *
  21060. * @private
  21061. * @type {number}
  21062. */
  21063. this._requestVideoFrameCallbackId = 0;
  21064. const scope = this;
  21065. function updateVideo() {
  21066. scope.needsUpdate = true;
  21067. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21068. }
  21069. if ( 'requestVideoFrameCallback' in video ) {
  21070. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21071. }
  21072. }
  21073. clone() {
  21074. return new this.constructor( this.image ).copy( this );
  21075. }
  21076. /**
  21077. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21078. * to `true` every time a new frame is available.
  21079. *
  21080. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21081. */
  21082. update() {
  21083. const video = this.image;
  21084. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21085. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21086. this.needsUpdate = true;
  21087. }
  21088. }
  21089. dispose() {
  21090. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21091. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21092. this._requestVideoFrameCallbackId = 0;
  21093. }
  21094. super.dispose();
  21095. }
  21096. }
  21097. /**
  21098. * This class can be used as an alternative way to define video data. Instead of using
  21099. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21100. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21101. * video frames are decoded with the WebCodecs API.
  21102. *
  21103. * ```js
  21104. * const texture = new THREE.VideoFrameTexture();
  21105. * texture.setFrame( frame );
  21106. * ```
  21107. *
  21108. * @augments VideoTexture
  21109. */
  21110. class VideoFrameTexture extends VideoTexture {
  21111. /**
  21112. * Constructs a new video frame texture.
  21113. *
  21114. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21115. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21116. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21117. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21118. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21119. * @param {number} [format=RGBAFormat] - The texture format.
  21120. * @param {number} [type=UnsignedByteType] - The texture type.
  21121. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21122. */
  21123. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21124. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21125. /**
  21126. * This flag can be used for type testing.
  21127. *
  21128. * @type {boolean}
  21129. * @readonly
  21130. * @default true
  21131. */
  21132. this.isVideoFrameTexture = true;
  21133. }
  21134. /**
  21135. * This method overwritten with an empty implementation since
  21136. * this type of texture is updated via `setFrame()`.
  21137. */
  21138. update() {}
  21139. clone() {
  21140. return new this.constructor().copy( this ); // restoring Texture.clone()
  21141. }
  21142. /**
  21143. * Sets the current frame of the video. This will automatically update the texture
  21144. * so the data can be used for rendering.
  21145. *
  21146. * @param {VideoFrame} frame - The video frame.
  21147. */
  21148. setFrame( frame ) {
  21149. this.image = frame;
  21150. this.needsUpdate = true;
  21151. }
  21152. }
  21153. /**
  21154. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21155. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21156. * as a texture for further usage.
  21157. *
  21158. * ```js
  21159. * const pixelRatio = window.devicePixelRatio;
  21160. * const textureSize = 128 * pixelRatio;
  21161. *
  21162. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21163. *
  21164. * // calculate start position for copying part of the frame data
  21165. * const vector = new Vector2();
  21166. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21167. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21168. *
  21169. * renderer.render( scene, camera );
  21170. *
  21171. * // copy part of the rendered frame into the framebuffer texture
  21172. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21173. * ```
  21174. *
  21175. * @augments Texture
  21176. */
  21177. class FramebufferTexture extends Texture {
  21178. /**
  21179. * Constructs a new framebuffer texture.
  21180. *
  21181. * @param {number} [width] - The width of the texture.
  21182. * @param {number} [height] - The height of the texture.
  21183. */
  21184. constructor( width, height ) {
  21185. super( { width, height } );
  21186. /**
  21187. * This flag can be used for type testing.
  21188. *
  21189. * @type {boolean}
  21190. * @readonly
  21191. * @default true
  21192. */
  21193. this.isFramebufferTexture = true;
  21194. /**
  21195. * How the texture is sampled when a texel covers more than one pixel.
  21196. *
  21197. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21198. *
  21199. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21200. * @default NearestFilter
  21201. */
  21202. this.magFilter = NearestFilter;
  21203. /**
  21204. * How the texture is sampled when a texel covers less than one pixel.
  21205. *
  21206. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21207. *
  21208. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21209. * @default NearestFilter
  21210. */
  21211. this.minFilter = NearestFilter;
  21212. /**
  21213. * Whether to generate mipmaps (if possible) for a texture.
  21214. *
  21215. * Overwritten and set to `false` by default.
  21216. *
  21217. * @type {boolean}
  21218. * @default false
  21219. */
  21220. this.generateMipmaps = false;
  21221. this.needsUpdate = true;
  21222. }
  21223. }
  21224. /**
  21225. * Creates a texture based on data in compressed form.
  21226. *
  21227. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21228. *
  21229. * @augments Texture
  21230. */
  21231. class CompressedTexture extends Texture {
  21232. /**
  21233. * Constructs a new compressed texture.
  21234. *
  21235. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21236. * the data and dimensions.
  21237. * @param {number} width - The width of the texture.
  21238. * @param {number} height - The height of the texture.
  21239. * @param {number} [format=RGBAFormat] - The texture format.
  21240. * @param {number} [type=UnsignedByteType] - The texture type.
  21241. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21242. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21243. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21244. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21245. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21246. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21247. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21248. */
  21249. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21250. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21251. /**
  21252. * This flag can be used for type testing.
  21253. *
  21254. * @type {boolean}
  21255. * @readonly
  21256. * @default true
  21257. */
  21258. this.isCompressedTexture = true;
  21259. /**
  21260. * The image property of a compressed texture just defines its dimensions.
  21261. *
  21262. * @type {{width:number,height:number}}
  21263. */
  21264. this.image = { width: width, height: height };
  21265. /**
  21266. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21267. *
  21268. * @type {Array<Object>}
  21269. */
  21270. this.mipmaps = mipmaps;
  21271. /**
  21272. * If set to `true`, the texture is flipped along the vertical axis when
  21273. * uploaded to the GPU.
  21274. *
  21275. * Overwritten and set to `false` by default since it is not possible to
  21276. * flip compressed textures.
  21277. *
  21278. * @type {boolean}
  21279. * @default false
  21280. * @readonly
  21281. */
  21282. this.flipY = false;
  21283. /**
  21284. * Whether to generate mipmaps (if possible) for a texture.
  21285. *
  21286. * Overwritten and set to `false` by default since it is not
  21287. * possible to generate mipmaps for compressed data. Mipmaps
  21288. * must be embedded in the compressed texture file.
  21289. *
  21290. * @type {boolean}
  21291. * @default false
  21292. * @readonly
  21293. */
  21294. this.generateMipmaps = false;
  21295. }
  21296. }
  21297. /**
  21298. * Creates a texture 2D array based on data in compressed form.
  21299. *
  21300. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21301. *
  21302. * @augments CompressedTexture
  21303. */
  21304. class CompressedArrayTexture extends CompressedTexture {
  21305. /**
  21306. * Constructs a new compressed array texture.
  21307. *
  21308. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21309. * the data and dimensions.
  21310. * @param {number} width - The width of the texture.
  21311. * @param {number} height - The height of the texture.
  21312. * @param {number} depth - The depth of the texture.
  21313. * @param {number} [format=RGBAFormat] - The min filter value.
  21314. * @param {number} [type=UnsignedByteType] - The min filter value.
  21315. */
  21316. constructor( mipmaps, width, height, depth, format, type ) {
  21317. super( mipmaps, width, height, format, type );
  21318. /**
  21319. * This flag can be used for type testing.
  21320. *
  21321. * @type {boolean}
  21322. * @readonly
  21323. * @default true
  21324. */
  21325. this.isCompressedArrayTexture = true;
  21326. /**
  21327. * The image property of a compressed texture just defines its dimensions.
  21328. *
  21329. * @name CompressedArrayTexture#image
  21330. * @type {{width:number,height:number,depth:number}}
  21331. */
  21332. this.image.depth = depth;
  21333. /**
  21334. * This defines how the texture is wrapped in the depth and corresponds to
  21335. * *W* in UVW mapping.
  21336. *
  21337. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21338. * @default ClampToEdgeWrapping
  21339. */
  21340. this.wrapR = ClampToEdgeWrapping;
  21341. /**
  21342. * A set of all layers which need to be updated in the texture.
  21343. *
  21344. * @type {Set<number>}
  21345. */
  21346. this.layerUpdates = new Set();
  21347. }
  21348. /**
  21349. * Describes that a specific layer of the texture needs to be updated.
  21350. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21351. * entire compressed texture array is sent to the GPU. Marking specific
  21352. * layers will only transmit subsets of all mipmaps associated with a
  21353. * specific depth in the array which is often much more performant.
  21354. *
  21355. * @param {number} layerIndex - The layer index that should be updated.
  21356. */
  21357. addLayerUpdate( layerIndex ) {
  21358. this.layerUpdates.add( layerIndex );
  21359. }
  21360. /**
  21361. * Resets the layer updates registry.
  21362. */
  21363. clearLayerUpdates() {
  21364. this.layerUpdates.clear();
  21365. }
  21366. }
  21367. /**
  21368. * Creates a cube texture based on data in compressed form.
  21369. *
  21370. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21371. *
  21372. * @augments CompressedTexture
  21373. */
  21374. class CompressedCubeTexture extends CompressedTexture {
  21375. /**
  21376. * Constructs a new compressed texture.
  21377. *
  21378. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21379. * @param {number} [format=RGBAFormat] - The texture format.
  21380. * @param {number} [type=UnsignedByteType] - The texture type.
  21381. */
  21382. constructor( images, format, type ) {
  21383. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21384. /**
  21385. * This flag can be used for type testing.
  21386. *
  21387. * @type {boolean}
  21388. * @readonly
  21389. * @default true
  21390. */
  21391. this.isCompressedCubeTexture = true;
  21392. /**
  21393. * This flag can be used for type testing.
  21394. *
  21395. * @type {boolean}
  21396. * @readonly
  21397. * @default true
  21398. */
  21399. this.isCubeTexture = true;
  21400. this.image = images;
  21401. }
  21402. }
  21403. /**
  21404. * Creates a cube texture made up of six images.
  21405. *
  21406. * ```js
  21407. * const loader = new THREE.CubeTextureLoader();
  21408. * loader.setPath( 'textures/cube/pisa/' );
  21409. *
  21410. * const textureCube = loader.load( [
  21411. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  21412. * ] );
  21413. *
  21414. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  21415. * ```
  21416. *
  21417. * @augments Texture
  21418. */
  21419. class CubeTexture extends Texture {
  21420. /**
  21421. * Constructs a new cube texture.
  21422. *
  21423. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  21424. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21425. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21426. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21427. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21428. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21429. * @param {number} [format=RGBAFormat] - The texture format.
  21430. * @param {number} [type=UnsignedByteType] - The texture type.
  21431. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21432. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  21433. */
  21434. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  21435. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21436. /**
  21437. * This flag can be used for type testing.
  21438. *
  21439. * @type {boolean}
  21440. * @readonly
  21441. * @default true
  21442. */
  21443. this.isCubeTexture = true;
  21444. /**
  21445. * If set to `true`, the texture is flipped along the vertical axis when
  21446. * uploaded to the GPU.
  21447. *
  21448. * Overwritten and set to `false` by default.
  21449. *
  21450. * @type {boolean}
  21451. * @default false
  21452. */
  21453. this.flipY = false;
  21454. }
  21455. /**
  21456. * Alias for {@link CubeTexture#image}.
  21457. *
  21458. * @type {Array<Image>}
  21459. */
  21460. get images() {
  21461. return this.image;
  21462. }
  21463. set images( value ) {
  21464. this.image = value;
  21465. }
  21466. }
  21467. /**
  21468. * Creates a texture from a canvas element.
  21469. *
  21470. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21471. * to `true` immediately since a canvas can directly be used for rendering.
  21472. *
  21473. * @augments Texture
  21474. */
  21475. class CanvasTexture extends Texture {
  21476. /**
  21477. * Constructs a new texture.
  21478. *
  21479. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21480. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21481. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21482. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21483. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21484. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21485. * @param {number} [format=RGBAFormat] - The texture format.
  21486. * @param {number} [type=UnsignedByteType] - The texture type.
  21487. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21488. */
  21489. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21490. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21491. /**
  21492. * This flag can be used for type testing.
  21493. *
  21494. * @type {boolean}
  21495. * @readonly
  21496. * @default true
  21497. */
  21498. this.isCanvasTexture = true;
  21499. this.needsUpdate = true;
  21500. }
  21501. }
  21502. /**
  21503. * Creates a texture from an HTML element.
  21504. *
  21505. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21506. * to `true` immediately and listens for the parent canvas's paint events to trigger updates.
  21507. *
  21508. * @augments Texture
  21509. */
  21510. class HTMLTexture extends Texture {
  21511. /**
  21512. * Constructs a new texture.
  21513. *
  21514. * @param {HTMLElement} [element] - The HTML element.
  21515. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21516. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21517. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21518. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21519. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21520. * @param {number} [format=RGBAFormat] - The texture format.
  21521. * @param {number} [type=UnsignedByteType] - The texture type.
  21522. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21523. */
  21524. constructor( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21525. super( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21526. /**
  21527. * This flag can be used for type testing.
  21528. *
  21529. * @type {boolean}
  21530. * @readonly
  21531. * @default true
  21532. */
  21533. this.isHTMLTexture = true;
  21534. this.generateMipmaps = false;
  21535. this.needsUpdate = true;
  21536. const parent = element ? element.parentNode : null;
  21537. if ( parent !== null && 'requestPaint' in parent ) {
  21538. parent.onpaint = () => {
  21539. this.needsUpdate = true;
  21540. };
  21541. parent.requestPaint();
  21542. }
  21543. }
  21544. dispose() {
  21545. const parent = this.image ? this.image.parentNode : null;
  21546. if ( parent !== null && 'onpaint' in parent ) {
  21547. parent.onpaint = null;
  21548. }
  21549. super.dispose();
  21550. }
  21551. }
  21552. /**
  21553. * This class can be used to automatically save the depth information of a
  21554. * rendering into a texture.
  21555. *
  21556. * @augments Texture
  21557. */
  21558. class DepthTexture extends Texture {
  21559. /**
  21560. * Constructs a new depth texture.
  21561. *
  21562. * @param {number} width - The width of the texture.
  21563. * @param {number} height - The height of the texture.
  21564. * @param {number} [type=UnsignedIntType] - The texture type.
  21565. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21566. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21567. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21568. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21569. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21570. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21571. * @param {number} [format=DepthFormat] - The texture format.
  21572. * @param {number} [depth=1] - The depth of the texture.
  21573. */
  21574. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  21575. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21576. throw new Error( 'THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21577. }
  21578. const image = { width: width, height: height, depth: depth };
  21579. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21580. /**
  21581. * This flag can be used for type testing.
  21582. *
  21583. * @type {boolean}
  21584. * @readonly
  21585. * @default true
  21586. */
  21587. this.isDepthTexture = true;
  21588. /**
  21589. * If set to `true`, the texture is flipped along the vertical axis when
  21590. * uploaded to the GPU.
  21591. *
  21592. * Overwritten and set to `false` by default.
  21593. *
  21594. * @type {boolean}
  21595. * @default false
  21596. */
  21597. this.flipY = false;
  21598. /**
  21599. * Whether to generate mipmaps (if possible) for a texture.
  21600. *
  21601. * Overwritten and set to `false` by default.
  21602. *
  21603. * @type {boolean}
  21604. * @default false
  21605. */
  21606. this.generateMipmaps = false;
  21607. /**
  21608. * Code corresponding to the depth compare function.
  21609. *
  21610. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21611. * @default null
  21612. */
  21613. this.compareFunction = null;
  21614. }
  21615. copy( source ) {
  21616. super.copy( source );
  21617. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21618. this.compareFunction = source.compareFunction;
  21619. return this;
  21620. }
  21621. toJSON( meta ) {
  21622. const data = super.toJSON( meta );
  21623. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21624. return data;
  21625. }
  21626. }
  21627. /**
  21628. * This class can be used to automatically save the depth information of a
  21629. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  21630. *
  21631. * @augments DepthTexture
  21632. */
  21633. class CubeDepthTexture extends DepthTexture {
  21634. /**
  21635. * Constructs a new cube depth texture.
  21636. *
  21637. * @param {number} size - The size (width and height) of each cube face.
  21638. * @param {number} [type=UnsignedIntType] - The texture type.
  21639. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21640. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21641. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21642. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  21643. * @param {number} [minFilter=NearestFilter] - The min filter value.
  21644. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21645. * @param {number} [format=DepthFormat] - The texture format.
  21646. */
  21647. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21648. // Create 6 identical image descriptors for the cube faces
  21649. const image = { width: size, height: size, depth: 1 };
  21650. const images = [ image, image, image, image, image, image ];
  21651. // Call DepthTexture constructor with width, height
  21652. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  21653. // Replace the single image with the array of 6 images
  21654. this.image = images;
  21655. /**
  21656. * This flag can be used for type testing.
  21657. *
  21658. * @type {boolean}
  21659. * @readonly
  21660. * @default true
  21661. */
  21662. this.isCubeDepthTexture = true;
  21663. /**
  21664. * Set to true for cube texture handling in WebGLTextures.
  21665. *
  21666. * @type {boolean}
  21667. * @readonly
  21668. * @default true
  21669. */
  21670. this.isCubeTexture = true;
  21671. }
  21672. /**
  21673. * Alias for {@link CubeDepthTexture#image}.
  21674. *
  21675. * @type {Array<Image>}
  21676. */
  21677. get images() {
  21678. return this.image;
  21679. }
  21680. set images( value ) {
  21681. this.image = value;
  21682. }
  21683. }
  21684. /**
  21685. * Represents a texture created externally with the same renderer context.
  21686. *
  21687. * This may be a texture from a protected media stream, device camera feed,
  21688. * or other data feeds like a depth sensor.
  21689. *
  21690. * @augments Texture
  21691. */
  21692. class ExternalTexture extends Texture {
  21693. /**
  21694. * Creates a new raw texture.
  21695. *
  21696. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  21697. */
  21698. constructor( sourceTexture = null ) {
  21699. super();
  21700. /**
  21701. * The external source texture.
  21702. *
  21703. * @type {?(WebGLTexture|GPUTexture)}
  21704. * @default null
  21705. */
  21706. this.sourceTexture = sourceTexture;
  21707. /**
  21708. * This flag can be used for type testing.
  21709. *
  21710. * @type {boolean}
  21711. * @readonly
  21712. * @default true
  21713. */
  21714. this.isExternalTexture = true;
  21715. }
  21716. copy( source ) {
  21717. super.copy( source );
  21718. this.sourceTexture = source.sourceTexture;
  21719. return this;
  21720. }
  21721. }
  21722. /**
  21723. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  21724. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  21725. * of the axes.
  21726. *
  21727. * ```js
  21728. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  21729. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21730. * const cube = new THREE.Mesh( geometry, material );
  21731. * scene.add( cube );
  21732. * ```
  21733. *
  21734. * @augments BufferGeometry
  21735. * @demo scenes/geometry-browser.html#BoxGeometry
  21736. */
  21737. class BoxGeometry extends BufferGeometry {
  21738. /**
  21739. * Constructs a new box geometry.
  21740. *
  21741. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  21742. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  21743. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  21744. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  21745. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  21746. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  21747. */
  21748. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  21749. super();
  21750. this.type = 'BoxGeometry';
  21751. /**
  21752. * Holds the constructor parameters that have been
  21753. * used to generate the geometry. Any modification
  21754. * after instantiation does not change the geometry.
  21755. *
  21756. * @type {Object}
  21757. */
  21758. this.parameters = {
  21759. width: width,
  21760. height: height,
  21761. depth: depth,
  21762. widthSegments: widthSegments,
  21763. heightSegments: heightSegments,
  21764. depthSegments: depthSegments
  21765. };
  21766. const scope = this;
  21767. // segments
  21768. widthSegments = Math.floor( widthSegments );
  21769. heightSegments = Math.floor( heightSegments );
  21770. depthSegments = Math.floor( depthSegments );
  21771. // buffers
  21772. const indices = [];
  21773. const vertices = [];
  21774. const normals = [];
  21775. const uvs = [];
  21776. // helper variables
  21777. let numberOfVertices = 0;
  21778. let groupStart = 0;
  21779. // build each side of the box geometry
  21780. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  21781. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  21782. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  21783. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  21784. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  21785. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  21786. // build geometry
  21787. this.setIndex( indices );
  21788. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21789. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21790. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21791. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  21792. const segmentWidth = width / gridX;
  21793. const segmentHeight = height / gridY;
  21794. const widthHalf = width / 2;
  21795. const heightHalf = height / 2;
  21796. const depthHalf = depth / 2;
  21797. const gridX1 = gridX + 1;
  21798. const gridY1 = gridY + 1;
  21799. let vertexCounter = 0;
  21800. let groupCount = 0;
  21801. const vector = new Vector3();
  21802. // generate vertices, normals and uvs
  21803. for ( let iy = 0; iy < gridY1; iy ++ ) {
  21804. const y = iy * segmentHeight - heightHalf;
  21805. for ( let ix = 0; ix < gridX1; ix ++ ) {
  21806. const x = ix * segmentWidth - widthHalf;
  21807. // set values to correct vector component
  21808. vector[ u ] = x * udir;
  21809. vector[ v ] = y * vdir;
  21810. vector[ w ] = depthHalf;
  21811. // now apply vector to vertex buffer
  21812. vertices.push( vector.x, vector.y, vector.z );
  21813. // set values to correct vector component
  21814. vector[ u ] = 0;
  21815. vector[ v ] = 0;
  21816. vector[ w ] = depth > 0 ? 1 : -1;
  21817. // now apply vector to normal buffer
  21818. normals.push( vector.x, vector.y, vector.z );
  21819. // uvs
  21820. uvs.push( ix / gridX );
  21821. uvs.push( 1 - ( iy / gridY ) );
  21822. // counters
  21823. vertexCounter += 1;
  21824. }
  21825. }
  21826. // indices
  21827. // 1. you need three indices to draw a single face
  21828. // 2. a single segment consists of two faces
  21829. // 3. so we need to generate six (2*3) indices per segment
  21830. for ( let iy = 0; iy < gridY; iy ++ ) {
  21831. for ( let ix = 0; ix < gridX; ix ++ ) {
  21832. const a = numberOfVertices + ix + gridX1 * iy;
  21833. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  21834. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  21835. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  21836. // faces
  21837. indices.push( a, b, d );
  21838. indices.push( b, c, d );
  21839. // increase counter
  21840. groupCount += 6;
  21841. }
  21842. }
  21843. // add a group to the geometry. this will ensure multi material support
  21844. scope.addGroup( groupStart, groupCount, materialIndex );
  21845. // calculate new start value for groups
  21846. groupStart += groupCount;
  21847. // update total number of vertices
  21848. numberOfVertices += vertexCounter;
  21849. }
  21850. }
  21851. copy( source ) {
  21852. super.copy( source );
  21853. this.parameters = Object.assign( {}, source.parameters );
  21854. return this;
  21855. }
  21856. /**
  21857. * Factory method for creating an instance of this class from the given
  21858. * JSON object.
  21859. *
  21860. * @param {Object} data - A JSON object representing the serialized geometry.
  21861. * @return {BoxGeometry} A new instance.
  21862. */
  21863. static fromJSON( data ) {
  21864. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  21865. }
  21866. }
  21867. /**
  21868. * A geometry class for representing a capsule.
  21869. *
  21870. * ```js
  21871. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  21872. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21873. * const capsule = new THREE.Mesh( geometry, material );
  21874. * scene.add( capsule );
  21875. * ```
  21876. *
  21877. * @augments BufferGeometry
  21878. * @demo scenes/geometry-browser.html#CapsuleGeometry
  21879. */
  21880. class CapsuleGeometry extends BufferGeometry {
  21881. /**
  21882. * Constructs a new capsule geometry.
  21883. *
  21884. * @param {number} [radius=1] - Radius of the capsule.
  21885. * @param {number} [height=1] - Height of the middle section.
  21886. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  21887. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  21888. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  21889. */
  21890. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  21891. super();
  21892. this.type = 'CapsuleGeometry';
  21893. /**
  21894. * Holds the constructor parameters that have been
  21895. * used to generate the geometry. Any modification
  21896. * after instantiation does not change the geometry.
  21897. *
  21898. * @type {Object}
  21899. */
  21900. this.parameters = {
  21901. radius: radius,
  21902. height: height,
  21903. capSegments: capSegments,
  21904. radialSegments: radialSegments,
  21905. heightSegments: heightSegments,
  21906. };
  21907. height = Math.max( 0, height );
  21908. capSegments = Math.max( 1, Math.floor( capSegments ) );
  21909. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  21910. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  21911. // buffers
  21912. const indices = [];
  21913. const vertices = [];
  21914. const normals = [];
  21915. const uvs = [];
  21916. // helper variables
  21917. const halfHeight = height / 2;
  21918. const capArcLength = ( Math.PI / 2 ) * radius;
  21919. const cylinderPartLength = height;
  21920. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  21921. const numVerticalSegments = capSegments * 2 + heightSegments;
  21922. const verticesPerRow = radialSegments + 1;
  21923. const normal = new Vector3();
  21924. const vertex = new Vector3();
  21925. // generate vertices, normals, and uvs
  21926. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  21927. let currentArcLength = 0;
  21928. let profileY = 0;
  21929. let profileRadius = 0;
  21930. let normalYComponent = 0;
  21931. if ( iy <= capSegments ) {
  21932. // bottom cap
  21933. const segmentProgress = iy / capSegments;
  21934. const angle = ( segmentProgress * Math.PI ) / 2;
  21935. profileY = - halfHeight - radius * Math.cos( angle );
  21936. profileRadius = radius * Math.sin( angle );
  21937. normalYComponent = - radius * Math.cos( angle );
  21938. currentArcLength = segmentProgress * capArcLength;
  21939. } else if ( iy <= capSegments + heightSegments ) {
  21940. // middle section
  21941. const segmentProgress = ( iy - capSegments ) / heightSegments;
  21942. profileY = - halfHeight + segmentProgress * height;
  21943. profileRadius = radius;
  21944. normalYComponent = 0;
  21945. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  21946. } else {
  21947. // top cap
  21948. const segmentProgress =
  21949. ( iy - capSegments - heightSegments ) / capSegments;
  21950. const angle = ( segmentProgress * Math.PI ) / 2;
  21951. profileY = halfHeight + radius * Math.sin( angle );
  21952. profileRadius = radius * Math.cos( angle );
  21953. normalYComponent = radius * Math.sin( angle );
  21954. currentArcLength =
  21955. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  21956. }
  21957. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  21958. // special case for the poles
  21959. let uOffset = 0;
  21960. if ( iy === 0 ) {
  21961. uOffset = 0.5 / radialSegments;
  21962. } else if ( iy === numVerticalSegments ) {
  21963. uOffset = -0.5 / radialSegments;
  21964. }
  21965. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  21966. const u = ix / radialSegments;
  21967. const theta = u * Math.PI * 2;
  21968. const sinTheta = Math.sin( theta );
  21969. const cosTheta = Math.cos( theta );
  21970. // vertex
  21971. vertex.x = - profileRadius * cosTheta;
  21972. vertex.y = profileY;
  21973. vertex.z = profileRadius * sinTheta;
  21974. vertices.push( vertex.x, vertex.y, vertex.z );
  21975. // normal
  21976. normal.set(
  21977. - profileRadius * cosTheta,
  21978. normalYComponent,
  21979. profileRadius * sinTheta
  21980. );
  21981. normal.normalize();
  21982. normals.push( normal.x, normal.y, normal.z );
  21983. // uv
  21984. uvs.push( u + uOffset, v );
  21985. }
  21986. if ( iy > 0 ) {
  21987. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  21988. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  21989. const i1 = prevIndexRow + ix;
  21990. const i2 = prevIndexRow + ix + 1;
  21991. const i3 = iy * verticesPerRow + ix;
  21992. const i4 = iy * verticesPerRow + ix + 1;
  21993. indices.push( i1, i2, i3 );
  21994. indices.push( i2, i4, i3 );
  21995. }
  21996. }
  21997. }
  21998. // build geometry
  21999. this.setIndex( indices );
  22000. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22001. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22002. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22003. }
  22004. copy( source ) {
  22005. super.copy( source );
  22006. this.parameters = Object.assign( {}, source.parameters );
  22007. return this;
  22008. }
  22009. /**
  22010. * Factory method for creating an instance of this class from the given
  22011. * JSON object.
  22012. *
  22013. * @param {Object} data - A JSON object representing the serialized geometry.
  22014. * @return {CapsuleGeometry} A new instance.
  22015. */
  22016. static fromJSON( data ) {
  22017. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22018. }
  22019. }
  22020. /**
  22021. * A simple shape of Euclidean geometry. It is constructed from a
  22022. * number of triangular segments that are oriented around a central point and
  22023. * extend as far out as a given radius. It is built counter-clockwise from a
  22024. * start angle and a given central angle. It can also be used to create
  22025. * regular polygons, where the number of segments determines the number of
  22026. * sides.
  22027. *
  22028. * ```js
  22029. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22030. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22031. * const circle = new THREE.Mesh( geometry, material );
  22032. * scene.add( circle )
  22033. * ```
  22034. *
  22035. * @augments BufferGeometry
  22036. * @demo scenes/geometry-browser.html#CircleGeometry
  22037. */
  22038. class CircleGeometry extends BufferGeometry {
  22039. /**
  22040. * Constructs a new circle geometry.
  22041. *
  22042. * @param {number} [radius=1] - Radius of the circle.
  22043. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22044. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22045. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22046. * of the circular sector in radians. The default value results in a complete circle.
  22047. */
  22048. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22049. super();
  22050. this.type = 'CircleGeometry';
  22051. /**
  22052. * Holds the constructor parameters that have been
  22053. * used to generate the geometry. Any modification
  22054. * after instantiation does not change the geometry.
  22055. *
  22056. * @type {Object}
  22057. */
  22058. this.parameters = {
  22059. radius: radius,
  22060. segments: segments,
  22061. thetaStart: thetaStart,
  22062. thetaLength: thetaLength
  22063. };
  22064. segments = Math.max( 3, segments );
  22065. // buffers
  22066. const indices = [];
  22067. const vertices = [];
  22068. const normals = [];
  22069. const uvs = [];
  22070. // helper variables
  22071. const vertex = new Vector3();
  22072. const uv = new Vector2();
  22073. // center point
  22074. vertices.push( 0, 0, 0 );
  22075. normals.push( 0, 0, 1 );
  22076. uvs.push( 0.5, 0.5 );
  22077. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22078. const segment = thetaStart + s / segments * thetaLength;
  22079. // vertex
  22080. vertex.x = radius * Math.cos( segment );
  22081. vertex.y = radius * Math.sin( segment );
  22082. vertices.push( vertex.x, vertex.y, vertex.z );
  22083. // normal
  22084. normals.push( 0, 0, 1 );
  22085. // uvs
  22086. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22087. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22088. uvs.push( uv.x, uv.y );
  22089. }
  22090. // indices
  22091. for ( let i = 1; i <= segments; i ++ ) {
  22092. indices.push( i, i + 1, 0 );
  22093. }
  22094. // build geometry
  22095. this.setIndex( indices );
  22096. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22097. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22098. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22099. }
  22100. copy( source ) {
  22101. super.copy( source );
  22102. this.parameters = Object.assign( {}, source.parameters );
  22103. return this;
  22104. }
  22105. /**
  22106. * Factory method for creating an instance of this class from the given
  22107. * JSON object.
  22108. *
  22109. * @param {Object} data - A JSON object representing the serialized geometry.
  22110. * @return {CircleGeometry} A new instance.
  22111. */
  22112. static fromJSON( data ) {
  22113. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22114. }
  22115. }
  22116. /**
  22117. * A geometry class for representing a cylinder.
  22118. *
  22119. * ```js
  22120. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22121. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22122. * const cylinder = new THREE.Mesh( geometry, material );
  22123. * scene.add( cylinder );
  22124. * ```
  22125. *
  22126. * @augments BufferGeometry
  22127. * @demo scenes/geometry-browser.html#CylinderGeometry
  22128. */
  22129. class CylinderGeometry extends BufferGeometry {
  22130. /**
  22131. * Constructs a new cylinder geometry.
  22132. *
  22133. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22134. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22135. * @param {number} [height=1] - Height of the cylinder.
  22136. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22137. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22138. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22139. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22140. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22141. * The default value results in a complete cylinder.
  22142. */
  22143. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22144. super();
  22145. this.type = 'CylinderGeometry';
  22146. /**
  22147. * Holds the constructor parameters that have been
  22148. * used to generate the geometry. Any modification
  22149. * after instantiation does not change the geometry.
  22150. *
  22151. * @type {Object}
  22152. */
  22153. this.parameters = {
  22154. radiusTop: radiusTop,
  22155. radiusBottom: radiusBottom,
  22156. height: height,
  22157. radialSegments: radialSegments,
  22158. heightSegments: heightSegments,
  22159. openEnded: openEnded,
  22160. thetaStart: thetaStart,
  22161. thetaLength: thetaLength
  22162. };
  22163. const scope = this;
  22164. radialSegments = Math.floor( radialSegments );
  22165. heightSegments = Math.floor( heightSegments );
  22166. // buffers
  22167. const indices = [];
  22168. const vertices = [];
  22169. const normals = [];
  22170. const uvs = [];
  22171. // helper variables
  22172. let index = 0;
  22173. const indexArray = [];
  22174. const halfHeight = height / 2;
  22175. let groupStart = 0;
  22176. // generate geometry
  22177. generateTorso();
  22178. if ( openEnded === false ) {
  22179. if ( radiusTop > 0 ) generateCap( true );
  22180. if ( radiusBottom > 0 ) generateCap( false );
  22181. }
  22182. // build geometry
  22183. this.setIndex( indices );
  22184. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22185. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22186. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22187. function generateTorso() {
  22188. const normal = new Vector3();
  22189. const vertex = new Vector3();
  22190. let groupCount = 0;
  22191. // this will be used to calculate the normal
  22192. const slope = ( radiusBottom - radiusTop ) / height;
  22193. // generate vertices, normals and uvs
  22194. for ( let y = 0; y <= heightSegments; y ++ ) {
  22195. const indexRow = [];
  22196. const v = y / heightSegments;
  22197. // calculate the radius of the current row
  22198. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22199. for ( let x = 0; x <= radialSegments; x ++ ) {
  22200. const u = x / radialSegments;
  22201. const theta = u * thetaLength + thetaStart;
  22202. const sinTheta = Math.sin( theta );
  22203. const cosTheta = Math.cos( theta );
  22204. // vertex
  22205. vertex.x = radius * sinTheta;
  22206. vertex.y = - v * height + halfHeight;
  22207. vertex.z = radius * cosTheta;
  22208. vertices.push( vertex.x, vertex.y, vertex.z );
  22209. // normal
  22210. normal.set( sinTheta, slope, cosTheta ).normalize();
  22211. normals.push( normal.x, normal.y, normal.z );
  22212. // uv
  22213. uvs.push( u, 1 - v );
  22214. // save index of vertex in respective row
  22215. indexRow.push( index ++ );
  22216. }
  22217. // now save vertices of the row in our index array
  22218. indexArray.push( indexRow );
  22219. }
  22220. // generate indices
  22221. for ( let x = 0; x < radialSegments; x ++ ) {
  22222. for ( let y = 0; y < heightSegments; y ++ ) {
  22223. // we use the index array to access the correct indices
  22224. const a = indexArray[ y ][ x ];
  22225. const b = indexArray[ y + 1 ][ x ];
  22226. const c = indexArray[ y + 1 ][ x + 1 ];
  22227. const d = indexArray[ y ][ x + 1 ];
  22228. // faces
  22229. if ( radiusTop > 0 || y !== 0 ) {
  22230. indices.push( a, b, d );
  22231. groupCount += 3;
  22232. }
  22233. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22234. indices.push( b, c, d );
  22235. groupCount += 3;
  22236. }
  22237. }
  22238. }
  22239. // add a group to the geometry. this will ensure multi material support
  22240. scope.addGroup( groupStart, groupCount, 0 );
  22241. // calculate new start value for groups
  22242. groupStart += groupCount;
  22243. }
  22244. function generateCap( top ) {
  22245. // save the index of the first center vertex
  22246. const centerIndexStart = index;
  22247. const uv = new Vector2();
  22248. const vertex = new Vector3();
  22249. let groupCount = 0;
  22250. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22251. const sign = ( top === true ) ? 1 : -1;
  22252. // first we generate the center vertex data of the cap.
  22253. // because the geometry needs one set of uvs per face,
  22254. // we must generate a center vertex per face/segment
  22255. for ( let x = 1; x <= radialSegments; x ++ ) {
  22256. // vertex
  22257. vertices.push( 0, halfHeight * sign, 0 );
  22258. // normal
  22259. normals.push( 0, sign, 0 );
  22260. // uv
  22261. uvs.push( 0.5, 0.5 );
  22262. // increase index
  22263. index ++;
  22264. }
  22265. // save the index of the last center vertex
  22266. const centerIndexEnd = index;
  22267. // now we generate the surrounding vertices, normals and uvs
  22268. for ( let x = 0; x <= radialSegments; x ++ ) {
  22269. const u = x / radialSegments;
  22270. const theta = u * thetaLength + thetaStart;
  22271. const cosTheta = Math.cos( theta );
  22272. const sinTheta = Math.sin( theta );
  22273. // vertex
  22274. vertex.x = radius * sinTheta;
  22275. vertex.y = halfHeight * sign;
  22276. vertex.z = radius * cosTheta;
  22277. vertices.push( vertex.x, vertex.y, vertex.z );
  22278. // normal
  22279. normals.push( 0, sign, 0 );
  22280. // uv
  22281. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22282. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22283. uvs.push( uv.x, uv.y );
  22284. // increase index
  22285. index ++;
  22286. }
  22287. // generate indices
  22288. for ( let x = 0; x < radialSegments; x ++ ) {
  22289. const c = centerIndexStart + x;
  22290. const i = centerIndexEnd + x;
  22291. if ( top === true ) {
  22292. // face top
  22293. indices.push( i, i + 1, c );
  22294. } else {
  22295. // face bottom
  22296. indices.push( i + 1, i, c );
  22297. }
  22298. groupCount += 3;
  22299. }
  22300. // add a group to the geometry. this will ensure multi material support
  22301. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22302. // calculate new start value for groups
  22303. groupStart += groupCount;
  22304. }
  22305. }
  22306. copy( source ) {
  22307. super.copy( source );
  22308. this.parameters = Object.assign( {}, source.parameters );
  22309. return this;
  22310. }
  22311. /**
  22312. * Factory method for creating an instance of this class from the given
  22313. * JSON object.
  22314. *
  22315. * @param {Object} data - A JSON object representing the serialized geometry.
  22316. * @return {CylinderGeometry} A new instance.
  22317. */
  22318. static fromJSON( data ) {
  22319. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22320. }
  22321. }
  22322. /**
  22323. * A geometry class for representing a cone.
  22324. *
  22325. * ```js
  22326. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22327. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22328. * const cone = new THREE.Mesh(geometry, material );
  22329. * scene.add( cone );
  22330. * ```
  22331. *
  22332. * @augments CylinderGeometry
  22333. * @demo scenes/geometry-browser.html#ConeGeometry
  22334. */
  22335. class ConeGeometry extends CylinderGeometry {
  22336. /**
  22337. * Constructs a new cone geometry.
  22338. *
  22339. * @param {number} [radius=1] - Radius of the cone base.
  22340. * @param {number} [height=1] - Height of the cone.
  22341. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22342. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22343. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22344. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22345. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22346. * The default value results in a complete cone.
  22347. */
  22348. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22349. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22350. this.type = 'ConeGeometry';
  22351. /**
  22352. * Holds the constructor parameters that have been
  22353. * used to generate the geometry. Any modification
  22354. * after instantiation does not change the geometry.
  22355. *
  22356. * @type {Object}
  22357. */
  22358. this.parameters = {
  22359. radius: radius,
  22360. height: height,
  22361. radialSegments: radialSegments,
  22362. heightSegments: heightSegments,
  22363. openEnded: openEnded,
  22364. thetaStart: thetaStart,
  22365. thetaLength: thetaLength
  22366. };
  22367. }
  22368. /**
  22369. * Factory method for creating an instance of this class from the given
  22370. * JSON object.
  22371. *
  22372. * @param {Object} data - A JSON object representing the serialized geometry.
  22373. * @return {ConeGeometry} A new instance.
  22374. */
  22375. static fromJSON( data ) {
  22376. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22377. }
  22378. }
  22379. /**
  22380. * A polyhedron is a solid in three dimensions with flat faces. This class
  22381. * will take an array of vertices, project them onto a sphere, and then
  22382. * divide them up to the desired level of detail.
  22383. *
  22384. * @augments BufferGeometry
  22385. */
  22386. class PolyhedronGeometry extends BufferGeometry {
  22387. /**
  22388. * Constructs a new polyhedron geometry.
  22389. *
  22390. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22391. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22392. * @param {number} [radius=1] - The radius of the shape.
  22393. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22394. */
  22395. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22396. super();
  22397. this.type = 'PolyhedronGeometry';
  22398. /**
  22399. * Holds the constructor parameters that have been
  22400. * used to generate the geometry. Any modification
  22401. * after instantiation does not change the geometry.
  22402. *
  22403. * @type {Object}
  22404. */
  22405. this.parameters = {
  22406. vertices: vertices,
  22407. indices: indices,
  22408. radius: radius,
  22409. detail: detail
  22410. };
  22411. // default buffer data
  22412. const vertexBuffer = [];
  22413. const uvBuffer = [];
  22414. // the subdivision creates the vertex buffer data
  22415. subdivide( detail );
  22416. // all vertices should lie on a conceptual sphere with a given radius
  22417. applyRadius( radius );
  22418. // finally, create the uv data
  22419. generateUVs();
  22420. // build non-indexed geometry
  22421. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22422. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22423. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22424. if ( detail === 0 ) {
  22425. this.computeVertexNormals(); // flat normals
  22426. } else {
  22427. this.normalizeNormals(); // smooth normals
  22428. }
  22429. // helper functions
  22430. function subdivide( detail ) {
  22431. const a = new Vector3();
  22432. const b = new Vector3();
  22433. const c = new Vector3();
  22434. // iterate over all faces and apply a subdivision with the given detail value
  22435. for ( let i = 0; i < indices.length; i += 3 ) {
  22436. // get the vertices of the face
  22437. getVertexByIndex( indices[ i + 0 ], a );
  22438. getVertexByIndex( indices[ i + 1 ], b );
  22439. getVertexByIndex( indices[ i + 2 ], c );
  22440. // perform subdivision
  22441. subdivideFace( a, b, c, detail );
  22442. }
  22443. }
  22444. function subdivideFace( a, b, c, detail ) {
  22445. const cols = detail + 1;
  22446. // we use this multidimensional array as a data structure for creating the subdivision
  22447. const v = [];
  22448. // construct all of the vertices for this subdivision
  22449. for ( let i = 0; i <= cols; i ++ ) {
  22450. v[ i ] = [];
  22451. const aj = a.clone().lerp( c, i / cols );
  22452. const bj = b.clone().lerp( c, i / cols );
  22453. const rows = cols - i;
  22454. for ( let j = 0; j <= rows; j ++ ) {
  22455. if ( j === 0 && i === cols ) {
  22456. v[ i ][ j ] = aj;
  22457. } else {
  22458. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22459. }
  22460. }
  22461. }
  22462. // construct all of the faces
  22463. for ( let i = 0; i < cols; i ++ ) {
  22464. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22465. const k = Math.floor( j / 2 );
  22466. if ( j % 2 === 0 ) {
  22467. pushVertex( v[ i ][ k + 1 ] );
  22468. pushVertex( v[ i + 1 ][ k ] );
  22469. pushVertex( v[ i ][ k ] );
  22470. } else {
  22471. pushVertex( v[ i ][ k + 1 ] );
  22472. pushVertex( v[ i + 1 ][ k + 1 ] );
  22473. pushVertex( v[ i + 1 ][ k ] );
  22474. }
  22475. }
  22476. }
  22477. }
  22478. function applyRadius( radius ) {
  22479. const vertex = new Vector3();
  22480. // iterate over the entire buffer and apply the radius to each vertex
  22481. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22482. vertex.x = vertexBuffer[ i + 0 ];
  22483. vertex.y = vertexBuffer[ i + 1 ];
  22484. vertex.z = vertexBuffer[ i + 2 ];
  22485. vertex.normalize().multiplyScalar( radius );
  22486. vertexBuffer[ i + 0 ] = vertex.x;
  22487. vertexBuffer[ i + 1 ] = vertex.y;
  22488. vertexBuffer[ i + 2 ] = vertex.z;
  22489. }
  22490. }
  22491. function generateUVs() {
  22492. const vertex = new Vector3();
  22493. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22494. vertex.x = vertexBuffer[ i + 0 ];
  22495. vertex.y = vertexBuffer[ i + 1 ];
  22496. vertex.z = vertexBuffer[ i + 2 ];
  22497. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22498. const v = inclination( vertex ) / Math.PI + 0.5;
  22499. uvBuffer.push( u, 1 - v );
  22500. }
  22501. correctUVs();
  22502. correctSeam();
  22503. }
  22504. function correctSeam() {
  22505. // handle case when face straddles the seam, see #3269
  22506. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22507. // uv data of a single face
  22508. const x0 = uvBuffer[ i + 0 ];
  22509. const x1 = uvBuffer[ i + 2 ];
  22510. const x2 = uvBuffer[ i + 4 ];
  22511. const max = Math.max( x0, x1, x2 );
  22512. const min = Math.min( x0, x1, x2 );
  22513. // 0.9 is somewhat arbitrary
  22514. if ( max > 0.9 && min < 0.1 ) {
  22515. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22516. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22517. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22518. }
  22519. }
  22520. }
  22521. function pushVertex( vertex ) {
  22522. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22523. }
  22524. function getVertexByIndex( index, vertex ) {
  22525. const stride = index * 3;
  22526. vertex.x = vertices[ stride + 0 ];
  22527. vertex.y = vertices[ stride + 1 ];
  22528. vertex.z = vertices[ stride + 2 ];
  22529. }
  22530. function correctUVs() {
  22531. const a = new Vector3();
  22532. const b = new Vector3();
  22533. const c = new Vector3();
  22534. const centroid = new Vector3();
  22535. const uvA = new Vector2();
  22536. const uvB = new Vector2();
  22537. const uvC = new Vector2();
  22538. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22539. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22540. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22541. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22542. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22543. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22544. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22545. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22546. const azi = azimuth( centroid );
  22547. correctUV( uvA, j + 0, a, azi );
  22548. correctUV( uvB, j + 2, b, azi );
  22549. correctUV( uvC, j + 4, c, azi );
  22550. }
  22551. }
  22552. function correctUV( uv, stride, vector, azimuth ) {
  22553. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22554. uvBuffer[ stride ] = uv.x - 1;
  22555. }
  22556. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22557. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22558. }
  22559. }
  22560. // Angle around the Y axis, counter-clockwise when looking from above.
  22561. function azimuth( vector ) {
  22562. return Math.atan2( vector.z, - vector.x );
  22563. }
  22564. // Angle above the XZ plane.
  22565. function inclination( vector ) {
  22566. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22567. }
  22568. }
  22569. copy( source ) {
  22570. super.copy( source );
  22571. this.parameters = Object.assign( {}, source.parameters );
  22572. return this;
  22573. }
  22574. /**
  22575. * Factory method for creating an instance of this class from the given
  22576. * JSON object.
  22577. *
  22578. * @param {Object} data - A JSON object representing the serialized geometry.
  22579. * @return {PolyhedronGeometry} A new instance.
  22580. */
  22581. static fromJSON( data ) {
  22582. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  22583. }
  22584. }
  22585. /**
  22586. * A geometry class for representing a dodecahedron.
  22587. *
  22588. * ```js
  22589. * const geometry = new THREE.DodecahedronGeometry();
  22590. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22591. * const dodecahedron = new THREE.Mesh( geometry, material );
  22592. * scene.add( dodecahedron );
  22593. * ```
  22594. *
  22595. * @augments PolyhedronGeometry
  22596. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  22597. */
  22598. class DodecahedronGeometry extends PolyhedronGeometry {
  22599. /**
  22600. * Constructs a new dodecahedron geometry.
  22601. *
  22602. * @param {number} [radius=1] - Radius of the dodecahedron.
  22603. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22604. */
  22605. constructor( radius = 1, detail = 0 ) {
  22606. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22607. const r = 1 / t;
  22608. const vertices = [
  22609. // (±1, ±1, ±1)
  22610. -1, -1, -1, -1, -1, 1,
  22611. -1, 1, -1, -1, 1, 1,
  22612. 1, -1, -1, 1, -1, 1,
  22613. 1, 1, -1, 1, 1, 1,
  22614. // (0, ±1/φ, ±φ)
  22615. 0, - r, - t, 0, - r, t,
  22616. 0, r, - t, 0, r, t,
  22617. // (±1/φ, ±φ, 0)
  22618. - r, - t, 0, - r, t, 0,
  22619. r, - t, 0, r, t, 0,
  22620. // (±φ, 0, ±1/φ)
  22621. - t, 0, - r, t, 0, - r,
  22622. - t, 0, r, t, 0, r
  22623. ];
  22624. const indices = [
  22625. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22626. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22627. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22628. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22629. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22630. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22631. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22632. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22633. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22634. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22635. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22636. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22637. ];
  22638. super( vertices, indices, radius, detail );
  22639. this.type = 'DodecahedronGeometry';
  22640. /**
  22641. * Holds the constructor parameters that have been
  22642. * used to generate the geometry. Any modification
  22643. * after instantiation does not change the geometry.
  22644. *
  22645. * @type {Object}
  22646. */
  22647. this.parameters = {
  22648. radius: radius,
  22649. detail: detail
  22650. };
  22651. }
  22652. /**
  22653. * Factory method for creating an instance of this class from the given
  22654. * JSON object.
  22655. *
  22656. * @param {Object} data - A JSON object representing the serialized geometry.
  22657. * @return {DodecahedronGeometry} A new instance.
  22658. */
  22659. static fromJSON( data ) {
  22660. return new DodecahedronGeometry( data.radius, data.detail );
  22661. }
  22662. }
  22663. const _v0 = /*@__PURE__*/ new Vector3();
  22664. const _v1$1 = /*@__PURE__*/ new Vector3();
  22665. const _normal = /*@__PURE__*/ new Vector3();
  22666. const _triangle = /*@__PURE__*/ new Triangle();
  22667. /**
  22668. * Can be used as a helper object to view the edges of a geometry.
  22669. *
  22670. * ```js
  22671. * const geometry = new THREE.BoxGeometry();
  22672. * const edges = new THREE.EdgesGeometry( geometry );
  22673. * const line = new THREE.LineSegments( edges );
  22674. * scene.add( line );
  22675. * ```
  22676. *
  22677. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22678. *
  22679. * @augments BufferGeometry
  22680. */
  22681. class EdgesGeometry extends BufferGeometry {
  22682. /**
  22683. * Constructs a new edges geometry.
  22684. *
  22685. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22686. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22687. * between the face normals of the adjoining faces exceeds this value.
  22688. */
  22689. constructor( geometry = null, thresholdAngle = 1 ) {
  22690. super();
  22691. this.type = 'EdgesGeometry';
  22692. /**
  22693. * Holds the constructor parameters that have been
  22694. * used to generate the geometry. Any modification
  22695. * after instantiation does not change the geometry.
  22696. *
  22697. * @type {Object}
  22698. */
  22699. this.parameters = {
  22700. geometry: geometry,
  22701. thresholdAngle: thresholdAngle
  22702. };
  22703. if ( geometry !== null ) {
  22704. const precisionPoints = 4;
  22705. const precision = Math.pow( 10, precisionPoints );
  22706. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22707. const indexAttr = geometry.getIndex();
  22708. const positionAttr = geometry.getAttribute( 'position' );
  22709. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22710. const indexArr = [ 0, 0, 0 ];
  22711. const vertKeys = [ 'a', 'b', 'c' ];
  22712. const hashes = new Array( 3 );
  22713. const edgeData = {};
  22714. const vertices = [];
  22715. for ( let i = 0; i < indexCount; i += 3 ) {
  22716. if ( indexAttr ) {
  22717. indexArr[ 0 ] = indexAttr.getX( i );
  22718. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22719. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22720. } else {
  22721. indexArr[ 0 ] = i;
  22722. indexArr[ 1 ] = i + 1;
  22723. indexArr[ 2 ] = i + 2;
  22724. }
  22725. const { a, b, c } = _triangle;
  22726. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22727. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22728. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22729. _triangle.getNormal( _normal );
  22730. // create hashes for the edge from the vertices
  22731. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22732. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22733. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22734. // skip degenerate triangles
  22735. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22736. continue;
  22737. }
  22738. // iterate over every edge
  22739. for ( let j = 0; j < 3; j ++ ) {
  22740. // get the first and next vertex making up the edge
  22741. const jNext = ( j + 1 ) % 3;
  22742. const vecHash0 = hashes[ j ];
  22743. const vecHash1 = hashes[ jNext ];
  22744. const v0 = _triangle[ vertKeys[ j ] ];
  22745. const v1 = _triangle[ vertKeys[ jNext ] ];
  22746. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22747. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22748. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22749. // if we found a sibling edge add it into the vertex array if
  22750. // it meets the angle threshold and delete the edge from the map.
  22751. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22752. vertices.push( v0.x, v0.y, v0.z );
  22753. vertices.push( v1.x, v1.y, v1.z );
  22754. }
  22755. edgeData[ reverseHash ] = null;
  22756. } else if ( ! ( hash in edgeData ) ) {
  22757. // if we've already got an edge here then skip adding a new one
  22758. edgeData[ hash ] = {
  22759. index0: indexArr[ j ],
  22760. index1: indexArr[ jNext ],
  22761. normal: _normal.clone(),
  22762. };
  22763. }
  22764. }
  22765. }
  22766. // iterate over all remaining, unmatched edges and add them to the vertex array
  22767. for ( const key in edgeData ) {
  22768. if ( edgeData[ key ] ) {
  22769. const { index0, index1 } = edgeData[ key ];
  22770. _v0.fromBufferAttribute( positionAttr, index0 );
  22771. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22772. vertices.push( _v0.x, _v0.y, _v0.z );
  22773. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22774. }
  22775. }
  22776. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22777. }
  22778. }
  22779. copy( source ) {
  22780. super.copy( source );
  22781. this.parameters = Object.assign( {}, source.parameters );
  22782. return this;
  22783. }
  22784. }
  22785. /**
  22786. * An abstract base class for creating an analytic curve object that contains methods
  22787. * for interpolation.
  22788. *
  22789. * @abstract
  22790. */
  22791. class Curve {
  22792. /**
  22793. * Constructs a new curve.
  22794. */
  22795. constructor() {
  22796. /**
  22797. * The type property is used for detecting the object type
  22798. * in context of serialization/deserialization.
  22799. *
  22800. * @type {string}
  22801. * @readonly
  22802. */
  22803. this.type = 'Curve';
  22804. /**
  22805. * This value determines the amount of divisions when calculating the
  22806. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  22807. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  22808. * recommended to increase the value of this property if the curve is very large.
  22809. *
  22810. * @type {number}
  22811. * @default 200
  22812. */
  22813. this.arcLengthDivisions = 200;
  22814. /**
  22815. * Must be set to `true` if the curve parameters have changed.
  22816. *
  22817. * @type {boolean}
  22818. * @default false
  22819. */
  22820. this.needsUpdate = false;
  22821. /**
  22822. * An internal cache that holds precomputed curve length values.
  22823. *
  22824. * @private
  22825. * @type {?Array<number>}
  22826. * @default null
  22827. */
  22828. this.cacheArcLengths = null;
  22829. }
  22830. /**
  22831. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22832. * for the given interpolation factor.
  22833. *
  22834. * @abstract
  22835. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22836. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22837. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22838. */
  22839. getPoint( /* t, optionalTarget */ ) {
  22840. warn( 'Curve: .getPoint() not implemented.' );
  22841. }
  22842. /**
  22843. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22844. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  22845. * of the curve which equidistant samples.
  22846. *
  22847. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22848. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22849. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22850. */
  22851. getPointAt( u, optionalTarget ) {
  22852. const t = this.getUtoTmapping( u );
  22853. return this.getPoint( t, optionalTarget );
  22854. }
  22855. /**
  22856. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  22857. * the curve shape.
  22858. *
  22859. * @param {number} [divisions=5] - The number of divisions.
  22860. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22861. */
  22862. getPoints( divisions = 5 ) {
  22863. const points = [];
  22864. for ( let d = 0; d <= divisions; d ++ ) {
  22865. points.push( this.getPoint( d / divisions ) );
  22866. }
  22867. return points;
  22868. }
  22869. // Get sequence of points using getPointAt( u )
  22870. /**
  22871. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  22872. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  22873. * curve.
  22874. *
  22875. * @param {number} [divisions=5] - The number of divisions.
  22876. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22877. */
  22878. getSpacedPoints( divisions = 5 ) {
  22879. const points = [];
  22880. for ( let d = 0; d <= divisions; d ++ ) {
  22881. points.push( this.getPointAt( d / divisions ) );
  22882. }
  22883. return points;
  22884. }
  22885. /**
  22886. * Returns the total arc length of the curve.
  22887. *
  22888. * @return {number} The length of the curve.
  22889. */
  22890. getLength() {
  22891. const lengths = this.getLengths();
  22892. return lengths[ lengths.length - 1 ];
  22893. }
  22894. /**
  22895. * Returns an array of cumulative segment lengths of the curve.
  22896. *
  22897. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  22898. * @return {Array<number>} An array holding the cumulative segment lengths.
  22899. */
  22900. getLengths( divisions = this.arcLengthDivisions ) {
  22901. if ( this.cacheArcLengths &&
  22902. ( this.cacheArcLengths.length === divisions + 1 ) &&
  22903. ! this.needsUpdate ) {
  22904. return this.cacheArcLengths;
  22905. }
  22906. this.needsUpdate = false;
  22907. const cache = [];
  22908. let current, last = this.getPoint( 0 );
  22909. let sum = 0;
  22910. cache.push( 0 );
  22911. for ( let p = 1; p <= divisions; p ++ ) {
  22912. current = this.getPoint( p / divisions );
  22913. sum += current.distanceTo( last );
  22914. cache.push( sum );
  22915. last = current;
  22916. }
  22917. this.cacheArcLengths = cache;
  22918. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22919. }
  22920. /**
  22921. * Update the cumulative segment distance cache. The method must be called
  22922. * every time curve parameters are changed. If an updated curve is part of a
  22923. * composed curve like {@link CurvePath}, this method must be called on the
  22924. * composed curve, too.
  22925. */
  22926. updateArcLengths() {
  22927. this.needsUpdate = true;
  22928. this.getLengths();
  22929. }
  22930. /**
  22931. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  22932. * interpolation factor in the same range that can be ued to sample equidistant points
  22933. * from a curve.
  22934. *
  22935. * @param {number} u - The interpolation factor.
  22936. * @param {?number} distance - An optional distance on the curve.
  22937. * @return {number} The updated interpolation factor.
  22938. */
  22939. getUtoTmapping( u, distance = null ) {
  22940. const arcLengths = this.getLengths();
  22941. let i = 0;
  22942. const il = arcLengths.length;
  22943. let targetArcLength; // The targeted u distance value to get
  22944. if ( distance ) {
  22945. targetArcLength = distance;
  22946. } else {
  22947. targetArcLength = u * arcLengths[ il - 1 ];
  22948. }
  22949. // binary search for the index with largest value smaller than target u distance
  22950. let low = 0, high = il - 1, comparison;
  22951. while ( low <= high ) {
  22952. 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
  22953. comparison = arcLengths[ i ] - targetArcLength;
  22954. if ( comparison < 0 ) {
  22955. low = i + 1;
  22956. } else if ( comparison > 0 ) {
  22957. high = i - 1;
  22958. } else {
  22959. high = i;
  22960. break;
  22961. // DONE
  22962. }
  22963. }
  22964. i = high;
  22965. if ( arcLengths[ i ] === targetArcLength ) {
  22966. return i / ( il - 1 );
  22967. }
  22968. // we could get finer grain at lengths, or use simple interpolation between two points
  22969. const lengthBefore = arcLengths[ i ];
  22970. const lengthAfter = arcLengths[ i + 1 ];
  22971. const segmentLength = lengthAfter - lengthBefore;
  22972. // determine where we are between the 'before' and 'after' points
  22973. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  22974. // add that fractional amount to t
  22975. const t = ( i + segmentFraction ) / ( il - 1 );
  22976. return t;
  22977. }
  22978. /**
  22979. * Returns a unit vector tangent for the given interpolation factor.
  22980. * If the derived curve does not implement its tangent derivation,
  22981. * two points a small delta apart will be used to find its gradient
  22982. * which seems to give a reasonable approximation.
  22983. *
  22984. * @param {number} t - The interpolation factor.
  22985. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22986. * @return {(Vector2|Vector3)} The tangent vector.
  22987. */
  22988. getTangent( t, optionalTarget ) {
  22989. const delta = 0.0001;
  22990. let t1 = t - delta;
  22991. let t2 = t + delta;
  22992. // Capping in case of danger
  22993. if ( t1 < 0 ) t1 = 0;
  22994. if ( t2 > 1 ) t2 = 1;
  22995. const pt1 = this.getPoint( t1 );
  22996. const pt2 = this.getPoint( t2 );
  22997. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  22998. tangent.copy( pt2 ).sub( pt1 ).normalize();
  22999. return tangent;
  23000. }
  23001. /**
  23002. * Same as {@link Curve#getTangent} but with equidistant samples.
  23003. *
  23004. * @param {number} u - The interpolation factor.
  23005. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23006. * @return {(Vector2|Vector3)} The tangent vector.
  23007. * @see {@link Curve#getPointAt}
  23008. */
  23009. getTangentAt( u, optionalTarget ) {
  23010. const t = this.getUtoTmapping( u );
  23011. return this.getTangent( t, optionalTarget );
  23012. }
  23013. /**
  23014. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23015. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23016. *
  23017. * @param {number} segments - The number of segments.
  23018. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23019. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23020. */
  23021. computeFrenetFrames( segments, closed = false ) {
  23022. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23023. const normal = new Vector3();
  23024. const tangents = [];
  23025. const normals = [];
  23026. const binormals = [];
  23027. const vec = new Vector3();
  23028. const mat = new Matrix4();
  23029. // compute the tangent vectors for each segment on the curve
  23030. for ( let i = 0; i <= segments; i ++ ) {
  23031. const u = i / segments;
  23032. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23033. }
  23034. // select an initial normal vector perpendicular to the first tangent vector,
  23035. // and in the direction of the minimum tangent xyz component
  23036. normals[ 0 ] = new Vector3();
  23037. binormals[ 0 ] = new Vector3();
  23038. let min = Number.MAX_VALUE;
  23039. const tx = Math.abs( tangents[ 0 ].x );
  23040. const ty = Math.abs( tangents[ 0 ].y );
  23041. const tz = Math.abs( tangents[ 0 ].z );
  23042. if ( tx <= min ) {
  23043. min = tx;
  23044. normal.set( 1, 0, 0 );
  23045. }
  23046. if ( ty <= min ) {
  23047. min = ty;
  23048. normal.set( 0, 1, 0 );
  23049. }
  23050. if ( tz <= min ) {
  23051. normal.set( 0, 0, 1 );
  23052. }
  23053. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23054. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23055. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23056. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23057. for ( let i = 1; i <= segments; i ++ ) {
  23058. normals[ i ] = normals[ i - 1 ].clone();
  23059. binormals[ i ] = binormals[ i - 1 ].clone();
  23060. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23061. if ( vec.length() > Number.EPSILON ) {
  23062. vec.normalize();
  23063. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23064. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23065. }
  23066. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23067. }
  23068. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23069. if ( closed === true ) {
  23070. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23071. theta /= segments;
  23072. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23073. theta = - theta;
  23074. }
  23075. for ( let i = 1; i <= segments; i ++ ) {
  23076. // twist a little...
  23077. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23078. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23079. }
  23080. }
  23081. return {
  23082. tangents: tangents,
  23083. normals: normals,
  23084. binormals: binormals
  23085. };
  23086. }
  23087. /**
  23088. * Returns a new curve with copied values from this instance.
  23089. *
  23090. * @return {Curve} A clone of this instance.
  23091. */
  23092. clone() {
  23093. return new this.constructor().copy( this );
  23094. }
  23095. /**
  23096. * Copies the values of the given curve to this instance.
  23097. *
  23098. * @param {Curve} source - The curve to copy.
  23099. * @return {Curve} A reference to this curve.
  23100. */
  23101. copy( source ) {
  23102. this.arcLengthDivisions = source.arcLengthDivisions;
  23103. return this;
  23104. }
  23105. /**
  23106. * Serializes the curve into JSON.
  23107. *
  23108. * @return {Object} A JSON object representing the serialized curve.
  23109. * @see {@link ObjectLoader#parse}
  23110. */
  23111. toJSON() {
  23112. const data = {
  23113. metadata: {
  23114. version: 4.7,
  23115. type: 'Curve',
  23116. generator: 'Curve.toJSON'
  23117. }
  23118. };
  23119. data.arcLengthDivisions = this.arcLengthDivisions;
  23120. data.type = this.type;
  23121. return data;
  23122. }
  23123. /**
  23124. * Deserializes the curve from the given JSON.
  23125. *
  23126. * @param {Object} json - The JSON holding the serialized curve.
  23127. * @return {Curve} A reference to this curve.
  23128. */
  23129. fromJSON( json ) {
  23130. this.arcLengthDivisions = json.arcLengthDivisions;
  23131. return this;
  23132. }
  23133. }
  23134. /**
  23135. * A curve representing an ellipse.
  23136. *
  23137. * ```js
  23138. * const curve = new THREE.EllipseCurve(
  23139. * 0, 0,
  23140. * 10, 10,
  23141. * 0, 2 * Math.PI,
  23142. * false,
  23143. * 0
  23144. * );
  23145. *
  23146. * const points = curve.getPoints( 50 );
  23147. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23148. *
  23149. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23150. *
  23151. * // Create the final object to add to the scene
  23152. * const ellipse = new THREE.Line( geometry, material );
  23153. * ```
  23154. *
  23155. * @augments Curve
  23156. */
  23157. class EllipseCurve extends Curve {
  23158. /**
  23159. * Constructs a new ellipse curve.
  23160. *
  23161. * @param {number} [aX=0] - The X center of the ellipse.
  23162. * @param {number} [aY=0] - The Y center of the ellipse.
  23163. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23164. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23165. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23166. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23167. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23168. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23169. */
  23170. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23171. super();
  23172. /**
  23173. * This flag can be used for type testing.
  23174. *
  23175. * @type {boolean}
  23176. * @readonly
  23177. * @default true
  23178. */
  23179. this.isEllipseCurve = true;
  23180. this.type = 'EllipseCurve';
  23181. /**
  23182. * The X center of the ellipse.
  23183. *
  23184. * @type {number}
  23185. * @default 0
  23186. */
  23187. this.aX = aX;
  23188. /**
  23189. * The Y center of the ellipse.
  23190. *
  23191. * @type {number}
  23192. * @default 0
  23193. */
  23194. this.aY = aY;
  23195. /**
  23196. * The radius of the ellipse in the x direction.
  23197. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23198. *
  23199. * @type {number}
  23200. * @default 1
  23201. */
  23202. this.xRadius = xRadius;
  23203. /**
  23204. * The radius of the ellipse in the y direction.
  23205. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23206. *
  23207. * @type {number}
  23208. * @default 1
  23209. */
  23210. this.yRadius = yRadius;
  23211. /**
  23212. * The start angle of the curve in radians starting from the positive X axis.
  23213. *
  23214. * @type {number}
  23215. * @default 0
  23216. */
  23217. this.aStartAngle = aStartAngle;
  23218. /**
  23219. * The end angle of the curve in radians starting from the positive X axis.
  23220. *
  23221. * @type {number}
  23222. * @default Math.PI*2
  23223. */
  23224. this.aEndAngle = aEndAngle;
  23225. /**
  23226. * Whether the ellipse is drawn clockwise or not.
  23227. *
  23228. * @type {boolean}
  23229. * @default false
  23230. */
  23231. this.aClockwise = aClockwise;
  23232. /**
  23233. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23234. *
  23235. * @type {number}
  23236. * @default 0
  23237. */
  23238. this.aRotation = aRotation;
  23239. }
  23240. /**
  23241. * Returns a point on the curve.
  23242. *
  23243. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23244. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23245. * @return {Vector2} The position on the curve.
  23246. */
  23247. getPoint( t, optionalTarget = new Vector2() ) {
  23248. const point = optionalTarget;
  23249. const twoPi = Math.PI * 2;
  23250. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23251. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23252. // ensures that deltaAngle is 0 .. 2 PI
  23253. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23254. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23255. if ( deltaAngle < Number.EPSILON ) {
  23256. if ( samePoints ) {
  23257. deltaAngle = 0;
  23258. } else {
  23259. deltaAngle = twoPi;
  23260. }
  23261. }
  23262. if ( this.aClockwise === true && ! samePoints ) {
  23263. if ( deltaAngle === twoPi ) {
  23264. deltaAngle = - twoPi;
  23265. } else {
  23266. deltaAngle = deltaAngle - twoPi;
  23267. }
  23268. }
  23269. const angle = this.aStartAngle + t * deltaAngle;
  23270. let x = this.aX + this.xRadius * Math.cos( angle );
  23271. let y = this.aY + this.yRadius * Math.sin( angle );
  23272. if ( this.aRotation !== 0 ) {
  23273. const cos = Math.cos( this.aRotation );
  23274. const sin = Math.sin( this.aRotation );
  23275. const tx = x - this.aX;
  23276. const ty = y - this.aY;
  23277. // Rotate the point about the center of the ellipse.
  23278. x = tx * cos - ty * sin + this.aX;
  23279. y = tx * sin + ty * cos + this.aY;
  23280. }
  23281. return point.set( x, y );
  23282. }
  23283. copy( source ) {
  23284. super.copy( source );
  23285. this.aX = source.aX;
  23286. this.aY = source.aY;
  23287. this.xRadius = source.xRadius;
  23288. this.yRadius = source.yRadius;
  23289. this.aStartAngle = source.aStartAngle;
  23290. this.aEndAngle = source.aEndAngle;
  23291. this.aClockwise = source.aClockwise;
  23292. this.aRotation = source.aRotation;
  23293. return this;
  23294. }
  23295. toJSON() {
  23296. const data = super.toJSON();
  23297. data.aX = this.aX;
  23298. data.aY = this.aY;
  23299. data.xRadius = this.xRadius;
  23300. data.yRadius = this.yRadius;
  23301. data.aStartAngle = this.aStartAngle;
  23302. data.aEndAngle = this.aEndAngle;
  23303. data.aClockwise = this.aClockwise;
  23304. data.aRotation = this.aRotation;
  23305. return data;
  23306. }
  23307. fromJSON( json ) {
  23308. super.fromJSON( json );
  23309. this.aX = json.aX;
  23310. this.aY = json.aY;
  23311. this.xRadius = json.xRadius;
  23312. this.yRadius = json.yRadius;
  23313. this.aStartAngle = json.aStartAngle;
  23314. this.aEndAngle = json.aEndAngle;
  23315. this.aClockwise = json.aClockwise;
  23316. this.aRotation = json.aRotation;
  23317. return this;
  23318. }
  23319. }
  23320. /**
  23321. * A curve representing an arc.
  23322. *
  23323. * @augments EllipseCurve
  23324. */
  23325. class ArcCurve extends EllipseCurve {
  23326. /**
  23327. * Constructs a new arc curve.
  23328. *
  23329. * @param {number} [aX=0] - The X center of the ellipse.
  23330. * @param {number} [aY=0] - The Y center of the ellipse.
  23331. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23332. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23333. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23334. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23335. */
  23336. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23337. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23338. /**
  23339. * This flag can be used for type testing.
  23340. *
  23341. * @type {boolean}
  23342. * @readonly
  23343. * @default true
  23344. */
  23345. this.isArcCurve = true;
  23346. this.type = 'ArcCurve';
  23347. }
  23348. }
  23349. function CubicPoly() {
  23350. /**
  23351. * Centripetal CatmullRom Curve - which is useful for avoiding
  23352. * cusps and self-intersections in non-uniform catmull rom curves.
  23353. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23354. *
  23355. * curve.type accepts centripetal(default), chordal and catmullrom
  23356. * curve.tension is used for catmullrom which defaults to 0.5
  23357. */
  23358. /*
  23359. Based on an optimized c++ solution in
  23360. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23361. - http://ideone.com/NoEbVM
  23362. This CubicPoly class could be used for reusing some variables and calculations,
  23363. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23364. which can be placed in CurveUtils.
  23365. */
  23366. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23367. /*
  23368. * Compute coefficients for a cubic polynomial
  23369. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23370. * such that
  23371. * p(0) = x0, p(1) = x1
  23372. * and
  23373. * p'(0) = t0, p'(1) = t1.
  23374. */
  23375. function init( x0, x1, t0, t1 ) {
  23376. c0 = x0;
  23377. c1 = t0;
  23378. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23379. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23380. }
  23381. return {
  23382. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23383. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23384. },
  23385. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23386. // compute tangents when parameterized in [t1,t2]
  23387. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23388. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23389. // rescale tangents for parametrization in [0,1]
  23390. t1 *= dt1;
  23391. t2 *= dt1;
  23392. init( x1, x2, t1, t2 );
  23393. },
  23394. calc: function ( t ) {
  23395. const t2 = t * t;
  23396. const t3 = t2 * t;
  23397. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23398. }
  23399. };
  23400. }
  23401. //
  23402. const tmp = /*@__PURE__*/ new Vector3();
  23403. const tmp2 = /*@__PURE__*/ new Vector3();
  23404. const px = /*@__PURE__*/ new CubicPoly();
  23405. const py = /*@__PURE__*/ new CubicPoly();
  23406. const pz = /*@__PURE__*/ new CubicPoly();
  23407. /**
  23408. * A curve representing a Catmull-Rom spline.
  23409. *
  23410. * ```js
  23411. * //Create a closed wavey loop
  23412. * const curve = new THREE.CatmullRomCurve3( [
  23413. * new THREE.Vector3( -10, 0, 10 ),
  23414. * new THREE.Vector3( -5, 5, 5 ),
  23415. * new THREE.Vector3( 0, 0, 0 ),
  23416. * new THREE.Vector3( 5, -5, 5 ),
  23417. * new THREE.Vector3( 10, 0, 10 )
  23418. * ] );
  23419. *
  23420. * const points = curve.getPoints( 50 );
  23421. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23422. *
  23423. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23424. *
  23425. * // Create the final object to add to the scene
  23426. * const curveObject = new THREE.Line( geometry, material );
  23427. * ```
  23428. *
  23429. * @augments Curve
  23430. */
  23431. class CatmullRomCurve3 extends Curve {
  23432. /**
  23433. * Constructs a new Catmull-Rom curve.
  23434. *
  23435. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23436. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23437. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23438. * @param {number} [tension=0.5] - Tension of the curve.
  23439. */
  23440. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23441. super();
  23442. /**
  23443. * This flag can be used for type testing.
  23444. *
  23445. * @type {boolean}
  23446. * @readonly
  23447. * @default true
  23448. */
  23449. this.isCatmullRomCurve3 = true;
  23450. this.type = 'CatmullRomCurve3';
  23451. /**
  23452. * An array of 3D points defining the curve.
  23453. *
  23454. * @type {Array<Vector3>}
  23455. */
  23456. this.points = points;
  23457. /**
  23458. * Whether the curve is closed or not.
  23459. *
  23460. * @type {boolean}
  23461. * @default false
  23462. */
  23463. this.closed = closed;
  23464. /**
  23465. * The curve type.
  23466. *
  23467. * @type {('centripetal'|'chordal'|'catmullrom')}
  23468. * @default 'centripetal'
  23469. */
  23470. this.curveType = curveType;
  23471. /**
  23472. * Tension of the curve.
  23473. *
  23474. * @type {number}
  23475. * @default 0.5
  23476. */
  23477. this.tension = tension;
  23478. }
  23479. /**
  23480. * Returns a point on the curve.
  23481. *
  23482. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23483. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23484. * @return {Vector3} The position on the curve.
  23485. */
  23486. getPoint( t, optionalTarget = new Vector3() ) {
  23487. const point = optionalTarget;
  23488. const points = this.points;
  23489. const l = points.length;
  23490. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23491. let intPoint = Math.floor( p );
  23492. let weight = p - intPoint;
  23493. if ( this.closed ) {
  23494. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23495. } else if ( weight === 0 && intPoint === l - 1 ) {
  23496. intPoint = l - 2;
  23497. weight = 1;
  23498. }
  23499. let p0, p3; // 4 points (p1 & p2 defined below)
  23500. if ( this.closed || intPoint > 0 ) {
  23501. p0 = points[ ( intPoint - 1 ) % l ];
  23502. } else {
  23503. // extrapolate first point
  23504. tmp2.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23505. p0 = tmp2;
  23506. }
  23507. const p1 = points[ intPoint % l ];
  23508. const p2 = points[ ( intPoint + 1 ) % l ];
  23509. if ( this.closed || intPoint + 2 < l ) {
  23510. p3 = points[ ( intPoint + 2 ) % l ];
  23511. } else {
  23512. // extrapolate last point
  23513. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23514. p3 = tmp;
  23515. }
  23516. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23517. // init Centripetal / Chordal Catmull-Rom
  23518. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23519. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23520. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23521. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23522. // safety check for repeated points
  23523. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23524. if ( dt0 < 1e-4 ) dt0 = dt1;
  23525. if ( dt2 < 1e-4 ) dt2 = dt1;
  23526. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23527. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23528. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23529. } else if ( this.curveType === 'catmullrom' ) {
  23530. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23531. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23532. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23533. }
  23534. point.set(
  23535. px.calc( weight ),
  23536. py.calc( weight ),
  23537. pz.calc( weight )
  23538. );
  23539. return point;
  23540. }
  23541. copy( source ) {
  23542. super.copy( source );
  23543. this.points = [];
  23544. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23545. const point = source.points[ i ];
  23546. this.points.push( point.clone() );
  23547. }
  23548. this.closed = source.closed;
  23549. this.curveType = source.curveType;
  23550. this.tension = source.tension;
  23551. return this;
  23552. }
  23553. toJSON() {
  23554. const data = super.toJSON();
  23555. data.points = [];
  23556. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23557. const point = this.points[ i ];
  23558. data.points.push( point.toArray() );
  23559. }
  23560. data.closed = this.closed;
  23561. data.curveType = this.curveType;
  23562. data.tension = this.tension;
  23563. return data;
  23564. }
  23565. fromJSON( json ) {
  23566. super.fromJSON( json );
  23567. this.points = [];
  23568. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23569. const point = json.points[ i ];
  23570. this.points.push( new Vector3().fromArray( point ) );
  23571. }
  23572. this.closed = json.closed;
  23573. this.curveType = json.curveType;
  23574. this.tension = json.tension;
  23575. return this;
  23576. }
  23577. }
  23578. /**
  23579. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  23580. *
  23581. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23582. *
  23583. * @module Interpolations
  23584. */
  23585. /**
  23586. * Computes a point on a Catmull-Rom spline.
  23587. *
  23588. * @param {number} t - The interpolation factor.
  23589. * @param {number} p0 - The first control point.
  23590. * @param {number} p1 - The second control point.
  23591. * @param {number} p2 - The third control point.
  23592. * @param {number} p3 - The fourth control point.
  23593. * @return {number} The calculated point on a Catmull-Rom spline.
  23594. */
  23595. function CatmullRom( t, p0, p1, p2, p3 ) {
  23596. const v0 = ( p2 - p0 ) * 0.5;
  23597. const v1 = ( p3 - p1 ) * 0.5;
  23598. const t2 = t * t;
  23599. const t3 = t * t2;
  23600. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23601. }
  23602. //
  23603. function QuadraticBezierP0( t, p ) {
  23604. const k = 1 - t;
  23605. return k * k * p;
  23606. }
  23607. function QuadraticBezierP1( t, p ) {
  23608. return 2 * ( 1 - t ) * t * p;
  23609. }
  23610. function QuadraticBezierP2( t, p ) {
  23611. return t * t * p;
  23612. }
  23613. /**
  23614. * Computes a point on a Quadratic Bezier curve.
  23615. *
  23616. * @param {number} t - The interpolation factor.
  23617. * @param {number} p0 - The first control point.
  23618. * @param {number} p1 - The second control point.
  23619. * @param {number} p2 - The third control point.
  23620. * @return {number} The calculated point on a Quadratic Bezier curve.
  23621. */
  23622. function QuadraticBezier( t, p0, p1, p2 ) {
  23623. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23624. QuadraticBezierP2( t, p2 );
  23625. }
  23626. //
  23627. function CubicBezierP0( t, p ) {
  23628. const k = 1 - t;
  23629. return k * k * k * p;
  23630. }
  23631. function CubicBezierP1( t, p ) {
  23632. const k = 1 - t;
  23633. return 3 * k * k * t * p;
  23634. }
  23635. function CubicBezierP2( t, p ) {
  23636. return 3 * ( 1 - t ) * t * t * p;
  23637. }
  23638. function CubicBezierP3( t, p ) {
  23639. return t * t * t * p;
  23640. }
  23641. /**
  23642. * Computes a point on a Cubic Bezier curve.
  23643. *
  23644. * @param {number} t - The interpolation factor.
  23645. * @param {number} p0 - The first control point.
  23646. * @param {number} p1 - The second control point.
  23647. * @param {number} p2 - The third control point.
  23648. * @param {number} p3 - The fourth control point.
  23649. * @return {number} The calculated point on a Cubic Bezier curve.
  23650. */
  23651. function CubicBezier( t, p0, p1, p2, p3 ) {
  23652. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23653. CubicBezierP3( t, p3 );
  23654. }
  23655. /**
  23656. * A curve representing a 2D Cubic Bezier curve.
  23657. *
  23658. * ```js
  23659. * const curve = new THREE.CubicBezierCurve(
  23660. * new THREE.Vector2( - 0, 0 ),
  23661. * new THREE.Vector2( - 5, 15 ),
  23662. * new THREE.Vector2( 20, 15 ),
  23663. * new THREE.Vector2( 10, 0 )
  23664. * );
  23665. *
  23666. * const points = curve.getPoints( 50 );
  23667. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23668. *
  23669. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23670. *
  23671. * // Create the final object to add to the scene
  23672. * const curveObject = new THREE.Line( geometry, material );
  23673. * ```
  23674. *
  23675. * @augments Curve
  23676. */
  23677. class CubicBezierCurve extends Curve {
  23678. /**
  23679. * Constructs a new Cubic Bezier curve.
  23680. *
  23681. * @param {Vector2} [v0] - The start point.
  23682. * @param {Vector2} [v1] - The first control point.
  23683. * @param {Vector2} [v2] - The second control point.
  23684. * @param {Vector2} [v3] - The end point.
  23685. */
  23686. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23687. super();
  23688. /**
  23689. * This flag can be used for type testing.
  23690. *
  23691. * @type {boolean}
  23692. * @readonly
  23693. * @default true
  23694. */
  23695. this.isCubicBezierCurve = true;
  23696. this.type = 'CubicBezierCurve';
  23697. /**
  23698. * The start point.
  23699. *
  23700. * @type {Vector2}
  23701. */
  23702. this.v0 = v0;
  23703. /**
  23704. * The first control point.
  23705. *
  23706. * @type {Vector2}
  23707. */
  23708. this.v1 = v1;
  23709. /**
  23710. * The second control point.
  23711. *
  23712. * @type {Vector2}
  23713. */
  23714. this.v2 = v2;
  23715. /**
  23716. * The end point.
  23717. *
  23718. * @type {Vector2}
  23719. */
  23720. this.v3 = v3;
  23721. }
  23722. /**
  23723. * Returns a point on the curve.
  23724. *
  23725. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23726. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23727. * @return {Vector2} The position on the curve.
  23728. */
  23729. getPoint( t, optionalTarget = new Vector2() ) {
  23730. const point = optionalTarget;
  23731. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23732. point.set(
  23733. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23734. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23735. );
  23736. return point;
  23737. }
  23738. copy( source ) {
  23739. super.copy( source );
  23740. this.v0.copy( source.v0 );
  23741. this.v1.copy( source.v1 );
  23742. this.v2.copy( source.v2 );
  23743. this.v3.copy( source.v3 );
  23744. return this;
  23745. }
  23746. toJSON() {
  23747. const data = super.toJSON();
  23748. data.v0 = this.v0.toArray();
  23749. data.v1 = this.v1.toArray();
  23750. data.v2 = this.v2.toArray();
  23751. data.v3 = this.v3.toArray();
  23752. return data;
  23753. }
  23754. fromJSON( json ) {
  23755. super.fromJSON( json );
  23756. this.v0.fromArray( json.v0 );
  23757. this.v1.fromArray( json.v1 );
  23758. this.v2.fromArray( json.v2 );
  23759. this.v3.fromArray( json.v3 );
  23760. return this;
  23761. }
  23762. }
  23763. /**
  23764. * A curve representing a 3D Cubic Bezier curve.
  23765. *
  23766. * @augments Curve
  23767. */
  23768. class CubicBezierCurve3 extends Curve {
  23769. /**
  23770. * Constructs a new Cubic Bezier curve.
  23771. *
  23772. * @param {Vector3} [v0] - The start point.
  23773. * @param {Vector3} [v1] - The first control point.
  23774. * @param {Vector3} [v2] - The second control point.
  23775. * @param {Vector3} [v3] - The end point.
  23776. */
  23777. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23778. super();
  23779. /**
  23780. * This flag can be used for type testing.
  23781. *
  23782. * @type {boolean}
  23783. * @readonly
  23784. * @default true
  23785. */
  23786. this.isCubicBezierCurve3 = true;
  23787. this.type = 'CubicBezierCurve3';
  23788. /**
  23789. * The start point.
  23790. *
  23791. * @type {Vector3}
  23792. */
  23793. this.v0 = v0;
  23794. /**
  23795. * The first control point.
  23796. *
  23797. * @type {Vector3}
  23798. */
  23799. this.v1 = v1;
  23800. /**
  23801. * The second control point.
  23802. *
  23803. * @type {Vector3}
  23804. */
  23805. this.v2 = v2;
  23806. /**
  23807. * The end point.
  23808. *
  23809. * @type {Vector3}
  23810. */
  23811. this.v3 = v3;
  23812. }
  23813. /**
  23814. * Returns a point on the curve.
  23815. *
  23816. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23817. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23818. * @return {Vector3} The position on the curve.
  23819. */
  23820. getPoint( t, optionalTarget = new Vector3() ) {
  23821. const point = optionalTarget;
  23822. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23823. point.set(
  23824. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23825. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23826. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23827. );
  23828. return point;
  23829. }
  23830. copy( source ) {
  23831. super.copy( source );
  23832. this.v0.copy( source.v0 );
  23833. this.v1.copy( source.v1 );
  23834. this.v2.copy( source.v2 );
  23835. this.v3.copy( source.v3 );
  23836. return this;
  23837. }
  23838. toJSON() {
  23839. const data = super.toJSON();
  23840. data.v0 = this.v0.toArray();
  23841. data.v1 = this.v1.toArray();
  23842. data.v2 = this.v2.toArray();
  23843. data.v3 = this.v3.toArray();
  23844. return data;
  23845. }
  23846. fromJSON( json ) {
  23847. super.fromJSON( json );
  23848. this.v0.fromArray( json.v0 );
  23849. this.v1.fromArray( json.v1 );
  23850. this.v2.fromArray( json.v2 );
  23851. this.v3.fromArray( json.v3 );
  23852. return this;
  23853. }
  23854. }
  23855. /**
  23856. * A curve representing a 2D line segment.
  23857. *
  23858. * @augments Curve
  23859. */
  23860. class LineCurve extends Curve {
  23861. /**
  23862. * Constructs a new line curve.
  23863. *
  23864. * @param {Vector2} [v1] - The start point.
  23865. * @param {Vector2} [v2] - The end point.
  23866. */
  23867. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  23868. super();
  23869. /**
  23870. * This flag can be used for type testing.
  23871. *
  23872. * @type {boolean}
  23873. * @readonly
  23874. * @default true
  23875. */
  23876. this.isLineCurve = true;
  23877. this.type = 'LineCurve';
  23878. /**
  23879. * The start point.
  23880. *
  23881. * @type {Vector2}
  23882. */
  23883. this.v1 = v1;
  23884. /**
  23885. * The end point.
  23886. *
  23887. * @type {Vector2}
  23888. */
  23889. this.v2 = v2;
  23890. }
  23891. /**
  23892. * Returns a point on the line.
  23893. *
  23894. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23895. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23896. * @return {Vector2} The position on the line.
  23897. */
  23898. getPoint( t, optionalTarget = new Vector2() ) {
  23899. const point = optionalTarget;
  23900. if ( t === 1 ) {
  23901. point.copy( this.v2 );
  23902. } else {
  23903. point.copy( this.v2 ).sub( this.v1 );
  23904. point.multiplyScalar( t ).add( this.v1 );
  23905. }
  23906. return point;
  23907. }
  23908. // Line curve is linear, so we can overwrite default getPointAt
  23909. getPointAt( u, optionalTarget ) {
  23910. return this.getPoint( u, optionalTarget );
  23911. }
  23912. getTangent( t, optionalTarget = new Vector2() ) {
  23913. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23914. }
  23915. getTangentAt( u, optionalTarget ) {
  23916. return this.getTangent( u, optionalTarget );
  23917. }
  23918. copy( source ) {
  23919. super.copy( source );
  23920. this.v1.copy( source.v1 );
  23921. this.v2.copy( source.v2 );
  23922. return this;
  23923. }
  23924. toJSON() {
  23925. const data = super.toJSON();
  23926. data.v1 = this.v1.toArray();
  23927. data.v2 = this.v2.toArray();
  23928. return data;
  23929. }
  23930. fromJSON( json ) {
  23931. super.fromJSON( json );
  23932. this.v1.fromArray( json.v1 );
  23933. this.v2.fromArray( json.v2 );
  23934. return this;
  23935. }
  23936. }
  23937. /**
  23938. * A curve representing a 3D line segment.
  23939. *
  23940. * @augments Curve
  23941. */
  23942. class LineCurve3 extends Curve {
  23943. /**
  23944. * Constructs a new line curve.
  23945. *
  23946. * @param {Vector3} [v1] - The start point.
  23947. * @param {Vector3} [v2] - The end point.
  23948. */
  23949. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  23950. super();
  23951. /**
  23952. * This flag can be used for type testing.
  23953. *
  23954. * @type {boolean}
  23955. * @readonly
  23956. * @default true
  23957. */
  23958. this.isLineCurve3 = true;
  23959. this.type = 'LineCurve3';
  23960. /**
  23961. * The start point.
  23962. *
  23963. * @type {Vector3}
  23964. */
  23965. this.v1 = v1;
  23966. /**
  23967. * The end point.
  23968. *
  23969. * @type {Vector2}
  23970. */
  23971. this.v2 = v2;
  23972. }
  23973. /**
  23974. * Returns a point on the line.
  23975. *
  23976. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23977. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23978. * @return {Vector3} The position on the line.
  23979. */
  23980. getPoint( t, optionalTarget = new Vector3() ) {
  23981. const point = optionalTarget;
  23982. if ( t === 1 ) {
  23983. point.copy( this.v2 );
  23984. } else {
  23985. point.copy( this.v2 ).sub( this.v1 );
  23986. point.multiplyScalar( t ).add( this.v1 );
  23987. }
  23988. return point;
  23989. }
  23990. // Line curve is linear, so we can overwrite default getPointAt
  23991. getPointAt( u, optionalTarget ) {
  23992. return this.getPoint( u, optionalTarget );
  23993. }
  23994. getTangent( t, optionalTarget = new Vector3() ) {
  23995. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23996. }
  23997. getTangentAt( u, optionalTarget ) {
  23998. return this.getTangent( u, optionalTarget );
  23999. }
  24000. copy( source ) {
  24001. super.copy( source );
  24002. this.v1.copy( source.v1 );
  24003. this.v2.copy( source.v2 );
  24004. return this;
  24005. }
  24006. toJSON() {
  24007. const data = super.toJSON();
  24008. data.v1 = this.v1.toArray();
  24009. data.v2 = this.v2.toArray();
  24010. return data;
  24011. }
  24012. fromJSON( json ) {
  24013. super.fromJSON( json );
  24014. this.v1.fromArray( json.v1 );
  24015. this.v2.fromArray( json.v2 );
  24016. return this;
  24017. }
  24018. }
  24019. /**
  24020. * A curve representing a 2D Quadratic Bezier curve.
  24021. *
  24022. * ```js
  24023. * const curve = new THREE.QuadraticBezierCurve(
  24024. * new THREE.Vector2( - 10, 0 ),
  24025. * new THREE.Vector2( 20, 15 ),
  24026. * new THREE.Vector2( 10, 0 )
  24027. * )
  24028. *
  24029. * const points = curve.getPoints( 50 );
  24030. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24031. *
  24032. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24033. *
  24034. * // Create the final object to add to the scene
  24035. * const curveObject = new THREE.Line( geometry, material );
  24036. * ```
  24037. *
  24038. * @augments Curve
  24039. */
  24040. class QuadraticBezierCurve extends Curve {
  24041. /**
  24042. * Constructs a new Quadratic Bezier curve.
  24043. *
  24044. * @param {Vector2} [v0] - The start point.
  24045. * @param {Vector2} [v1] - The control point.
  24046. * @param {Vector2} [v2] - The end point.
  24047. */
  24048. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24049. super();
  24050. /**
  24051. * This flag can be used for type testing.
  24052. *
  24053. * @type {boolean}
  24054. * @readonly
  24055. * @default true
  24056. */
  24057. this.isQuadraticBezierCurve = true;
  24058. this.type = 'QuadraticBezierCurve';
  24059. /**
  24060. * The start point.
  24061. *
  24062. * @type {Vector2}
  24063. */
  24064. this.v0 = v0;
  24065. /**
  24066. * The control point.
  24067. *
  24068. * @type {Vector2}
  24069. */
  24070. this.v1 = v1;
  24071. /**
  24072. * The end point.
  24073. *
  24074. * @type {Vector2}
  24075. */
  24076. this.v2 = v2;
  24077. }
  24078. /**
  24079. * Returns a point on the curve.
  24080. *
  24081. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24082. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24083. * @return {Vector2} The position on the curve.
  24084. */
  24085. getPoint( t, optionalTarget = new Vector2() ) {
  24086. const point = optionalTarget;
  24087. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24088. point.set(
  24089. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24090. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24091. );
  24092. return point;
  24093. }
  24094. copy( source ) {
  24095. super.copy( source );
  24096. this.v0.copy( source.v0 );
  24097. this.v1.copy( source.v1 );
  24098. this.v2.copy( source.v2 );
  24099. return this;
  24100. }
  24101. toJSON() {
  24102. const data = super.toJSON();
  24103. data.v0 = this.v0.toArray();
  24104. data.v1 = this.v1.toArray();
  24105. data.v2 = this.v2.toArray();
  24106. return data;
  24107. }
  24108. fromJSON( json ) {
  24109. super.fromJSON( json );
  24110. this.v0.fromArray( json.v0 );
  24111. this.v1.fromArray( json.v1 );
  24112. this.v2.fromArray( json.v2 );
  24113. return this;
  24114. }
  24115. }
  24116. /**
  24117. * A curve representing a 3D Quadratic Bezier curve.
  24118. *
  24119. * @augments Curve
  24120. */
  24121. class QuadraticBezierCurve3 extends Curve {
  24122. /**
  24123. * Constructs a new Quadratic Bezier curve.
  24124. *
  24125. * @param {Vector3} [v0] - The start point.
  24126. * @param {Vector3} [v1] - The control point.
  24127. * @param {Vector3} [v2] - The end point.
  24128. */
  24129. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24130. super();
  24131. /**
  24132. * This flag can be used for type testing.
  24133. *
  24134. * @type {boolean}
  24135. * @readonly
  24136. * @default true
  24137. */
  24138. this.isQuadraticBezierCurve3 = true;
  24139. this.type = 'QuadraticBezierCurve3';
  24140. /**
  24141. * The start point.
  24142. *
  24143. * @type {Vector3}
  24144. */
  24145. this.v0 = v0;
  24146. /**
  24147. * The control point.
  24148. *
  24149. * @type {Vector3}
  24150. */
  24151. this.v1 = v1;
  24152. /**
  24153. * The end point.
  24154. *
  24155. * @type {Vector3}
  24156. */
  24157. this.v2 = v2;
  24158. }
  24159. /**
  24160. * Returns a point on the curve.
  24161. *
  24162. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24163. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24164. * @return {Vector3} The position on the curve.
  24165. */
  24166. getPoint( t, optionalTarget = new Vector3() ) {
  24167. const point = optionalTarget;
  24168. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24169. point.set(
  24170. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24171. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24172. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24173. );
  24174. return point;
  24175. }
  24176. copy( source ) {
  24177. super.copy( source );
  24178. this.v0.copy( source.v0 );
  24179. this.v1.copy( source.v1 );
  24180. this.v2.copy( source.v2 );
  24181. return this;
  24182. }
  24183. toJSON() {
  24184. const data = super.toJSON();
  24185. data.v0 = this.v0.toArray();
  24186. data.v1 = this.v1.toArray();
  24187. data.v2 = this.v2.toArray();
  24188. return data;
  24189. }
  24190. fromJSON( json ) {
  24191. super.fromJSON( json );
  24192. this.v0.fromArray( json.v0 );
  24193. this.v1.fromArray( json.v1 );
  24194. this.v2.fromArray( json.v2 );
  24195. return this;
  24196. }
  24197. }
  24198. /**
  24199. * A curve representing a 2D spline curve.
  24200. *
  24201. * ```js
  24202. * // Create a sine-like wave
  24203. * const curve = new THREE.SplineCurve( [
  24204. * new THREE.Vector2( -10, 0 ),
  24205. * new THREE.Vector2( -5, 5 ),
  24206. * new THREE.Vector2( 0, 0 ),
  24207. * new THREE.Vector2( 5, -5 ),
  24208. * new THREE.Vector2( 10, 0 )
  24209. * ] );
  24210. *
  24211. * const points = curve.getPoints( 50 );
  24212. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24213. *
  24214. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24215. *
  24216. * // Create the final object to add to the scene
  24217. * const splineObject = new THREE.Line( geometry, material );
  24218. * ```
  24219. *
  24220. * @augments Curve
  24221. */
  24222. class SplineCurve extends Curve {
  24223. /**
  24224. * Constructs a new 2D spline curve.
  24225. *
  24226. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24227. */
  24228. constructor( points = [] ) {
  24229. super();
  24230. /**
  24231. * This flag can be used for type testing.
  24232. *
  24233. * @type {boolean}
  24234. * @readonly
  24235. * @default true
  24236. */
  24237. this.isSplineCurve = true;
  24238. this.type = 'SplineCurve';
  24239. /**
  24240. * An array of 2D points defining the curve.
  24241. *
  24242. * @type {Array<Vector2>}
  24243. */
  24244. this.points = points;
  24245. }
  24246. /**
  24247. * Returns a point on the curve.
  24248. *
  24249. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24250. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24251. * @return {Vector2} The position on the curve.
  24252. */
  24253. getPoint( t, optionalTarget = new Vector2() ) {
  24254. const point = optionalTarget;
  24255. const points = this.points;
  24256. const p = ( points.length - 1 ) * t;
  24257. const intPoint = Math.floor( p );
  24258. const weight = p - intPoint;
  24259. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24260. const p1 = points[ intPoint ];
  24261. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24262. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24263. point.set(
  24264. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24265. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24266. );
  24267. return point;
  24268. }
  24269. copy( source ) {
  24270. super.copy( source );
  24271. this.points = [];
  24272. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24273. const point = source.points[ i ];
  24274. this.points.push( point.clone() );
  24275. }
  24276. return this;
  24277. }
  24278. toJSON() {
  24279. const data = super.toJSON();
  24280. data.points = [];
  24281. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24282. const point = this.points[ i ];
  24283. data.points.push( point.toArray() );
  24284. }
  24285. return data;
  24286. }
  24287. fromJSON( json ) {
  24288. super.fromJSON( json );
  24289. this.points = [];
  24290. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24291. const point = json.points[ i ];
  24292. this.points.push( new Vector2().fromArray( point ) );
  24293. }
  24294. return this;
  24295. }
  24296. }
  24297. var Curves = /*#__PURE__*/Object.freeze({
  24298. __proto__: null,
  24299. ArcCurve: ArcCurve,
  24300. CatmullRomCurve3: CatmullRomCurve3,
  24301. CubicBezierCurve: CubicBezierCurve,
  24302. CubicBezierCurve3: CubicBezierCurve3,
  24303. EllipseCurve: EllipseCurve,
  24304. LineCurve: LineCurve,
  24305. LineCurve3: LineCurve3,
  24306. QuadraticBezierCurve: QuadraticBezierCurve,
  24307. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24308. SplineCurve: SplineCurve
  24309. });
  24310. /**
  24311. * A base class extending {@link Curve}. `CurvePath` is simply an
  24312. * array of connected curves, but retains the API of a curve.
  24313. *
  24314. * @augments Curve
  24315. */
  24316. class CurvePath extends Curve {
  24317. /**
  24318. * Constructs a new curve path.
  24319. */
  24320. constructor() {
  24321. super();
  24322. this.type = 'CurvePath';
  24323. /**
  24324. * An array of curves defining the
  24325. * path.
  24326. *
  24327. * @type {Array<Curve>}
  24328. */
  24329. this.curves = [];
  24330. /**
  24331. * Whether the path should automatically be closed
  24332. * by a line curve.
  24333. *
  24334. * @type {boolean}
  24335. * @default false
  24336. */
  24337. this.autoClose = false;
  24338. }
  24339. /**
  24340. * Adds a curve to this curve path.
  24341. *
  24342. * @param {Curve} curve - The curve to add.
  24343. */
  24344. add( curve ) {
  24345. this.curves.push( curve );
  24346. }
  24347. /**
  24348. * Adds a line curve to close the path.
  24349. *
  24350. * @return {CurvePath} A reference to this curve path.
  24351. */
  24352. closePath() {
  24353. // Add a line curve if start and end of lines are not connected
  24354. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24355. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24356. if ( ! startPoint.equals( endPoint ) ) {
  24357. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24358. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24359. }
  24360. return this;
  24361. }
  24362. /**
  24363. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24364. * for the given interpolation factor.
  24365. *
  24366. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24367. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24368. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24369. */
  24370. getPoint( t, optionalTarget ) {
  24371. // To get accurate point with reference to
  24372. // entire path distance at time t,
  24373. // following has to be done:
  24374. // 1. Length of each sub path have to be known
  24375. // 2. Locate and identify type of curve
  24376. // 3. Get t for the curve
  24377. // 4. Return curve.getPointAt(t')
  24378. const d = t * this.getLength();
  24379. const curveLengths = this.getCurveLengths();
  24380. let i = 0;
  24381. // To think about boundaries points.
  24382. while ( i < curveLengths.length ) {
  24383. if ( curveLengths[ i ] >= d ) {
  24384. const diff = curveLengths[ i ] - d;
  24385. const curve = this.curves[ i ];
  24386. const segmentLength = curve.getLength();
  24387. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24388. return curve.getPointAt( u, optionalTarget );
  24389. }
  24390. i ++;
  24391. }
  24392. return null;
  24393. // loop where sum != 0, sum > d , sum+1 <d
  24394. }
  24395. getLength() {
  24396. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24397. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24398. // getPoint() depends on getLength
  24399. const lens = this.getCurveLengths();
  24400. return lens[ lens.length - 1 ];
  24401. }
  24402. updateArcLengths() {
  24403. // cacheLengths must be recalculated.
  24404. this.needsUpdate = true;
  24405. this.cacheLengths = null;
  24406. this.getCurveLengths();
  24407. }
  24408. /**
  24409. * Returns list of cumulative curve lengths of the defined curves.
  24410. *
  24411. * @return {Array<number>} The curve lengths.
  24412. */
  24413. getCurveLengths() {
  24414. // Compute lengths and cache them
  24415. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24416. // We use cache values if curves and cache array are same length
  24417. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24418. return this.cacheLengths;
  24419. }
  24420. // Get length of sub-curve
  24421. // Push sums into cached array
  24422. const lengths = [];
  24423. let sums = 0;
  24424. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24425. sums += this.curves[ i ].getLength();
  24426. lengths.push( sums );
  24427. }
  24428. this.cacheLengths = lengths;
  24429. return lengths;
  24430. }
  24431. getSpacedPoints( divisions = 40 ) {
  24432. const points = [];
  24433. for ( let i = 0; i <= divisions; i ++ ) {
  24434. points.push( this.getPoint( i / divisions ) );
  24435. }
  24436. if ( this.autoClose ) {
  24437. points.push( points[ 0 ] );
  24438. }
  24439. return points;
  24440. }
  24441. getPoints( divisions = 12 ) {
  24442. const points = [];
  24443. let last;
  24444. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24445. const curve = curves[ i ];
  24446. const resolution = curve.isEllipseCurve ? divisions * 2
  24447. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24448. : curve.isSplineCurve ? divisions * curve.points.length
  24449. : divisions;
  24450. const pts = curve.getPoints( resolution );
  24451. for ( let j = 0; j < pts.length; j ++ ) {
  24452. const point = pts[ j ];
  24453. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24454. points.push( point );
  24455. last = point;
  24456. }
  24457. }
  24458. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24459. points.push( points[ 0 ] );
  24460. }
  24461. return points;
  24462. }
  24463. copy( source ) {
  24464. super.copy( source );
  24465. this.curves = [];
  24466. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24467. const curve = source.curves[ i ];
  24468. this.curves.push( curve.clone() );
  24469. }
  24470. this.autoClose = source.autoClose;
  24471. return this;
  24472. }
  24473. toJSON() {
  24474. const data = super.toJSON();
  24475. data.autoClose = this.autoClose;
  24476. data.curves = [];
  24477. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24478. const curve = this.curves[ i ];
  24479. data.curves.push( curve.toJSON() );
  24480. }
  24481. return data;
  24482. }
  24483. fromJSON( json ) {
  24484. super.fromJSON( json );
  24485. this.autoClose = json.autoClose;
  24486. this.curves = [];
  24487. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24488. const curve = json.curves[ i ];
  24489. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24490. }
  24491. return this;
  24492. }
  24493. }
  24494. /**
  24495. * A 2D path representation. The class provides methods for creating paths
  24496. * and contours of 2D shapes similar to the 2D Canvas API.
  24497. *
  24498. * ```js
  24499. * const path = new THREE.Path();
  24500. *
  24501. * path.lineTo( 0, 0.8 );
  24502. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24503. * path.lineTo( 1, 1 );
  24504. *
  24505. * const points = path.getPoints();
  24506. *
  24507. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24508. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24509. *
  24510. * const line = new THREE.Line( geometry, material );
  24511. * scene.add( line );
  24512. * ```
  24513. *
  24514. * @augments CurvePath
  24515. */
  24516. class Path extends CurvePath {
  24517. /**
  24518. * Constructs a new path.
  24519. *
  24520. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24521. */
  24522. constructor( points ) {
  24523. super();
  24524. this.type = 'Path';
  24525. /**
  24526. * The current offset of the path. Any new curve added will start here.
  24527. *
  24528. * @type {Vector2}
  24529. */
  24530. this.currentPoint = new Vector2();
  24531. if ( points ) {
  24532. this.setFromPoints( points );
  24533. }
  24534. }
  24535. /**
  24536. * Creates a path from the given list of points. The points are added
  24537. * to the path as instances of {@link LineCurve}.
  24538. *
  24539. * @param {Array<Vector2>} points - An array of 2D points.
  24540. * @return {Path} A reference to this path.
  24541. */
  24542. setFromPoints( points ) {
  24543. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24544. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24545. this.lineTo( points[ i ].x, points[ i ].y );
  24546. }
  24547. return this;
  24548. }
  24549. /**
  24550. * Moves {@link Path#currentPoint} to the given point.
  24551. *
  24552. * @param {number} x - The x coordinate.
  24553. * @param {number} y - The y coordinate.
  24554. * @return {Path} A reference to this path.
  24555. */
  24556. moveTo( x, y ) {
  24557. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24558. return this;
  24559. }
  24560. /**
  24561. * Adds an instance of {@link LineCurve} to the path by connecting
  24562. * the current point with the given one.
  24563. *
  24564. * @param {number} x - The x coordinate of the end point.
  24565. * @param {number} y - The y coordinate of the end point.
  24566. * @return {Path} A reference to this path.
  24567. */
  24568. lineTo( x, y ) {
  24569. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24570. this.curves.push( curve );
  24571. this.currentPoint.set( x, y );
  24572. return this;
  24573. }
  24574. /**
  24575. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24576. * the current point with the given one.
  24577. *
  24578. * @param {number} aCPx - The x coordinate of the control point.
  24579. * @param {number} aCPy - The y coordinate of the control point.
  24580. * @param {number} aX - The x coordinate of the end point.
  24581. * @param {number} aY - The y coordinate of the end point.
  24582. * @return {Path} A reference to this path.
  24583. */
  24584. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24585. const curve = new QuadraticBezierCurve(
  24586. this.currentPoint.clone(),
  24587. new Vector2( aCPx, aCPy ),
  24588. new Vector2( aX, aY )
  24589. );
  24590. this.curves.push( curve );
  24591. this.currentPoint.set( aX, aY );
  24592. return this;
  24593. }
  24594. /**
  24595. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24596. * the current point with the given one.
  24597. *
  24598. * @param {number} aCP1x - The x coordinate of the first control point.
  24599. * @param {number} aCP1y - The y coordinate of the first control point.
  24600. * @param {number} aCP2x - The x coordinate of the second control point.
  24601. * @param {number} aCP2y - The y coordinate of the second control point.
  24602. * @param {number} aX - The x coordinate of the end point.
  24603. * @param {number} aY - The y coordinate of the end point.
  24604. * @return {Path} A reference to this path.
  24605. */
  24606. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24607. const curve = new CubicBezierCurve(
  24608. this.currentPoint.clone(),
  24609. new Vector2( aCP1x, aCP1y ),
  24610. new Vector2( aCP2x, aCP2y ),
  24611. new Vector2( aX, aY )
  24612. );
  24613. this.curves.push( curve );
  24614. this.currentPoint.set( aX, aY );
  24615. return this;
  24616. }
  24617. /**
  24618. * Adds an instance of {@link SplineCurve} to the path by connecting
  24619. * the current point with the given list of points.
  24620. *
  24621. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24622. * @return {Path} A reference to this path.
  24623. */
  24624. splineThru( pts ) {
  24625. const npts = [ this.currentPoint.clone() ].concat( pts );
  24626. const curve = new SplineCurve( npts );
  24627. this.curves.push( curve );
  24628. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24629. return this;
  24630. }
  24631. /**
  24632. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24633. * to the current point.
  24634. *
  24635. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24636. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24637. * @param {number} [aRadius=1] - The radius of the arc.
  24638. * @param {number} [aStartAngle=0] - The start angle in radians.
  24639. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24640. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24641. * @return {Path} A reference to this path.
  24642. */
  24643. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24644. const x0 = this.currentPoint.x;
  24645. const y0 = this.currentPoint.y;
  24646. this.absarc( aX + x0, aY + y0, aRadius,
  24647. aStartAngle, aEndAngle, aClockwise );
  24648. return this;
  24649. }
  24650. /**
  24651. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24652. *
  24653. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24654. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24655. * @param {number} [aRadius=1] - The radius of the arc.
  24656. * @param {number} [aStartAngle=0] - The start angle in radians.
  24657. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24658. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24659. * @return {Path} A reference to this path.
  24660. */
  24661. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24662. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24663. return this;
  24664. }
  24665. /**
  24666. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24667. * to the current point
  24668. *
  24669. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24670. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24671. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24672. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24673. * @param {number} [aStartAngle=0] - The start angle in radians.
  24674. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24675. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24676. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24677. * @return {Path} A reference to this path.
  24678. */
  24679. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24680. const x0 = this.currentPoint.x;
  24681. const y0 = this.currentPoint.y;
  24682. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24683. return this;
  24684. }
  24685. /**
  24686. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24687. *
  24688. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24689. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24690. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24691. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24692. * @param {number} [aStartAngle=0] - The start angle in radians.
  24693. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24694. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24695. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24696. * @return {Path} A reference to this path.
  24697. */
  24698. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24699. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24700. if ( this.curves.length > 0 ) {
  24701. // if a previous curve is present, attempt to join
  24702. const firstPoint = curve.getPoint( 0 );
  24703. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24704. this.lineTo( firstPoint.x, firstPoint.y );
  24705. }
  24706. }
  24707. this.curves.push( curve );
  24708. const lastPoint = curve.getPoint( 1 );
  24709. this.currentPoint.copy( lastPoint );
  24710. return this;
  24711. }
  24712. copy( source ) {
  24713. super.copy( source );
  24714. this.currentPoint.copy( source.currentPoint );
  24715. return this;
  24716. }
  24717. toJSON() {
  24718. const data = super.toJSON();
  24719. data.currentPoint = this.currentPoint.toArray();
  24720. return data;
  24721. }
  24722. fromJSON( json ) {
  24723. super.fromJSON( json );
  24724. this.currentPoint.fromArray( json.currentPoint );
  24725. return this;
  24726. }
  24727. }
  24728. /**
  24729. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24730. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24731. * points, or to get triangulated faces.
  24732. *
  24733. * ```js
  24734. * const heartShape = new THREE.Shape();
  24735. *
  24736. * heartShape.moveTo( 25, 25 );
  24737. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24738. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24739. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24740. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24741. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24742. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24743. *
  24744. * const extrudeSettings = {
  24745. * depth: 8,
  24746. * bevelEnabled: true,
  24747. * bevelSegments: 2,
  24748. * steps: 2,
  24749. * bevelSize: 1,
  24750. * bevelThickness: 1
  24751. * };
  24752. *
  24753. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24754. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24755. * ```
  24756. *
  24757. * @augments Path
  24758. */
  24759. class Shape extends Path {
  24760. /**
  24761. * Constructs a new shape.
  24762. *
  24763. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24764. */
  24765. constructor( points ) {
  24766. super( points );
  24767. /**
  24768. * The UUID of the shape.
  24769. *
  24770. * @type {string}
  24771. * @readonly
  24772. */
  24773. this.uuid = generateUUID();
  24774. this.type = 'Shape';
  24775. /**
  24776. * Defines the holes in the shape. Hole definitions must use the
  24777. * opposite winding order (CW/CCW) than the outer shape.
  24778. *
  24779. * @type {Array<Path>}
  24780. * @readonly
  24781. */
  24782. this.holes = [];
  24783. }
  24784. /**
  24785. * Returns an array representing each contour of the holes
  24786. * as a list of 2D points.
  24787. *
  24788. * @param {number} divisions - The fineness of the result.
  24789. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24790. */
  24791. getPointsHoles( divisions ) {
  24792. const holesPts = [];
  24793. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24794. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24795. }
  24796. return holesPts;
  24797. }
  24798. // get points of shape and holes (keypoints based on segments parameter)
  24799. /**
  24800. * Returns an object that holds contour data for the shape and its holes as
  24801. * arrays of 2D points.
  24802. *
  24803. * @param {number} divisions - The fineness of the result.
  24804. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24805. */
  24806. extractPoints( divisions ) {
  24807. return {
  24808. shape: this.getPoints( divisions ),
  24809. holes: this.getPointsHoles( divisions )
  24810. };
  24811. }
  24812. copy( source ) {
  24813. super.copy( source );
  24814. this.holes = [];
  24815. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24816. const hole = source.holes[ i ];
  24817. this.holes.push( hole.clone() );
  24818. }
  24819. return this;
  24820. }
  24821. toJSON() {
  24822. const data = super.toJSON();
  24823. data.uuid = this.uuid;
  24824. data.holes = [];
  24825. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24826. const hole = this.holes[ i ];
  24827. data.holes.push( hole.toJSON() );
  24828. }
  24829. return data;
  24830. }
  24831. fromJSON( json ) {
  24832. super.fromJSON( json );
  24833. this.uuid = json.uuid;
  24834. this.holes = [];
  24835. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24836. const hole = json.holes[ i ];
  24837. this.holes.push( new Path().fromJSON( hole ) );
  24838. }
  24839. return this;
  24840. }
  24841. }
  24842. /* eslint-disable */
  24843. // copy of mapbox/earcut version 3.0.2
  24844. // https://github.com/mapbox/earcut/tree/v3.0.2
  24845. function earcut(data, holeIndices, dim = 2) {
  24846. const hasHoles = holeIndices && holeIndices.length;
  24847. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24848. let outerNode = linkedList(data, 0, outerLen, dim, true);
  24849. const triangles = [];
  24850. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24851. let minX, minY, invSize;
  24852. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  24853. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24854. if (data.length > 80 * dim) {
  24855. minX = data[0];
  24856. minY = data[1];
  24857. let maxX = minX;
  24858. let maxY = minY;
  24859. for (let i = dim; i < outerLen; i += dim) {
  24860. const x = data[i];
  24861. const y = data[i + 1];
  24862. if (x < minX) minX = x;
  24863. if (y < minY) minY = y;
  24864. if (x > maxX) maxX = x;
  24865. if (y > maxY) maxY = y;
  24866. }
  24867. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24868. invSize = Math.max(maxX - minX, maxY - minY);
  24869. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24870. }
  24871. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  24872. return triangles;
  24873. }
  24874. // create a circular doubly linked list from polygon points in the specified winding order
  24875. function linkedList(data, start, end, dim, clockwise) {
  24876. let last;
  24877. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  24878. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24879. } else {
  24880. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24881. }
  24882. if (last && equals(last, last.next)) {
  24883. removeNode(last);
  24884. last = last.next;
  24885. }
  24886. return last;
  24887. }
  24888. // eliminate colinear or duplicate points
  24889. function filterPoints(start, end) {
  24890. if (!start) return start;
  24891. if (!end) end = start;
  24892. let p = start,
  24893. again;
  24894. do {
  24895. again = false;
  24896. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24897. removeNode(p);
  24898. p = end = p.prev;
  24899. if (p === p.next) break;
  24900. again = true;
  24901. } else {
  24902. p = p.next;
  24903. }
  24904. } while (again || p !== end);
  24905. return end;
  24906. }
  24907. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24908. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  24909. if (!ear) return;
  24910. // interlink polygon nodes in z-order
  24911. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  24912. let stop = ear;
  24913. // iterate through ears, slicing them one by one
  24914. while (ear.prev !== ear.next) {
  24915. const prev = ear.prev;
  24916. const next = ear.next;
  24917. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  24918. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  24919. removeNode(ear);
  24920. // skipping the next vertex leads to less sliver triangles
  24921. ear = next.next;
  24922. stop = next.next;
  24923. continue;
  24924. }
  24925. ear = next;
  24926. // if we looped through the whole remaining polygon and can't find any more ears
  24927. if (ear === stop) {
  24928. // try filtering points and slicing again
  24929. if (!pass) {
  24930. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  24931. // if this didn't work, try curing all small self-intersections locally
  24932. } else if (pass === 1) {
  24933. ear = cureLocalIntersections(filterPoints(ear), triangles);
  24934. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  24935. // as a last resort, try splitting the remaining polygon into two
  24936. } else if (pass === 2) {
  24937. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  24938. }
  24939. break;
  24940. }
  24941. }
  24942. }
  24943. // check whether a polygon node forms a valid ear with adjacent nodes
  24944. function isEar(ear) {
  24945. const a = ear.prev,
  24946. b = ear,
  24947. c = ear.next;
  24948. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24949. // now make sure we don't have other points inside the potential ear
  24950. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24951. // triangle bbox
  24952. const x0 = Math.min(ax, bx, cx),
  24953. y0 = Math.min(ay, by, cy),
  24954. x1 = Math.max(ax, bx, cx),
  24955. y1 = Math.max(ay, by, cy);
  24956. let p = c.next;
  24957. while (p !== a) {
  24958. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  24959. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  24960. area(p.prev, p, p.next) >= 0) return false;
  24961. p = p.next;
  24962. }
  24963. return true;
  24964. }
  24965. function isEarHashed(ear, minX, minY, invSize) {
  24966. const a = ear.prev,
  24967. b = ear,
  24968. c = ear.next;
  24969. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24970. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24971. // triangle bbox
  24972. const x0 = Math.min(ax, bx, cx),
  24973. y0 = Math.min(ay, by, cy),
  24974. x1 = Math.max(ax, bx, cx),
  24975. y1 = Math.max(ay, by, cy);
  24976. // z-order range for the current triangle bbox;
  24977. const minZ = zOrder(x0, y0, minX, minY, invSize),
  24978. maxZ = zOrder(x1, y1, minX, minY, invSize);
  24979. let p = ear.prevZ,
  24980. n = ear.nextZ;
  24981. // look for points inside the triangle in both directions
  24982. while (p && p.z >= minZ && n && n.z <= maxZ) {
  24983. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24984. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24985. p = p.prevZ;
  24986. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24987. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24988. n = n.nextZ;
  24989. }
  24990. // look for remaining points in decreasing z-order
  24991. while (p && p.z >= minZ) {
  24992. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24993. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24994. p = p.prevZ;
  24995. }
  24996. // look for remaining points in increasing z-order
  24997. while (n && n.z <= maxZ) {
  24998. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24999. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25000. n = n.nextZ;
  25001. }
  25002. return true;
  25003. }
  25004. // go through all polygon nodes and cure small local self-intersections
  25005. function cureLocalIntersections(start, triangles) {
  25006. let p = start;
  25007. do {
  25008. const a = p.prev,
  25009. b = p.next.next;
  25010. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25011. triangles.push(a.i, p.i, b.i);
  25012. // remove two nodes involved
  25013. removeNode(p);
  25014. removeNode(p.next);
  25015. p = start = b;
  25016. }
  25017. p = p.next;
  25018. } while (p !== start);
  25019. return filterPoints(p);
  25020. }
  25021. // try splitting polygon into two and triangulate them independently
  25022. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25023. // look for a valid diagonal that divides the polygon into two
  25024. let a = start;
  25025. do {
  25026. let b = a.next.next;
  25027. while (b !== a.prev) {
  25028. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25029. // split the polygon in two by the diagonal
  25030. let c = splitPolygon(a, b);
  25031. // filter colinear points around the cuts
  25032. a = filterPoints(a, a.next);
  25033. c = filterPoints(c, c.next);
  25034. // run earcut on each half
  25035. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25036. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25037. return;
  25038. }
  25039. b = b.next;
  25040. }
  25041. a = a.next;
  25042. } while (a !== start);
  25043. }
  25044. // link every hole into the outer loop, producing a single-ring polygon without holes
  25045. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25046. const queue = [];
  25047. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25048. const start = holeIndices[i] * dim;
  25049. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25050. const list = linkedList(data, start, end, dim, false);
  25051. if (list === list.next) list.steiner = true;
  25052. queue.push(getLeftmost(list));
  25053. }
  25054. queue.sort(compareXYSlope);
  25055. // process holes from left to right
  25056. for (let i = 0; i < queue.length; i++) {
  25057. outerNode = eliminateHole(queue[i], outerNode);
  25058. }
  25059. return outerNode;
  25060. }
  25061. function compareXYSlope(a, b) {
  25062. let result = a.x - b.x;
  25063. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25064. // the bridge to the outer shell is always the point that they meet at.
  25065. if (result === 0) {
  25066. result = a.y - b.y;
  25067. if (result === 0) {
  25068. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25069. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25070. result = aSlope - bSlope;
  25071. }
  25072. }
  25073. return result;
  25074. }
  25075. // find a bridge between vertices that connects hole with an outer ring and link it
  25076. function eliminateHole(hole, outerNode) {
  25077. const bridge = findHoleBridge(hole, outerNode);
  25078. if (!bridge) {
  25079. return outerNode;
  25080. }
  25081. const bridgeReverse = splitPolygon(bridge, hole);
  25082. // filter collinear points around the cuts
  25083. filterPoints(bridgeReverse, bridgeReverse.next);
  25084. return filterPoints(bridge, bridge.next);
  25085. }
  25086. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25087. function findHoleBridge(hole, outerNode) {
  25088. let p = outerNode;
  25089. const hx = hole.x;
  25090. const hy = hole.y;
  25091. let qx = -Infinity;
  25092. let m;
  25093. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25094. // segment's endpoint with lesser x will be potential connection point
  25095. // unless they intersect at a vertex, then choose the vertex
  25096. if (equals(hole, p)) return p;
  25097. do {
  25098. if (equals(hole, p.next)) return p.next;
  25099. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25100. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25101. if (x <= hx && x > qx) {
  25102. qx = x;
  25103. m = p.x < p.next.x ? p : p.next;
  25104. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25105. }
  25106. }
  25107. p = p.next;
  25108. } while (p !== outerNode);
  25109. if (!m) return null;
  25110. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25111. // if there are no points found, we have a valid connection;
  25112. // otherwise choose the point of the minimum angle with the ray as connection point
  25113. const stop = m;
  25114. const mx = m.x;
  25115. const my = m.y;
  25116. let tanMin = Infinity;
  25117. p = m;
  25118. do {
  25119. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25120. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25121. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25122. if (locallyInside(p, hole) &&
  25123. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25124. m = p;
  25125. tanMin = tan;
  25126. }
  25127. }
  25128. p = p.next;
  25129. } while (p !== stop);
  25130. return m;
  25131. }
  25132. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25133. function sectorContainsSector(m, p) {
  25134. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25135. }
  25136. // interlink polygon nodes in z-order
  25137. function indexCurve(start, minX, minY, invSize) {
  25138. let p = start;
  25139. do {
  25140. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25141. p.prevZ = p.prev;
  25142. p.nextZ = p.next;
  25143. p = p.next;
  25144. } while (p !== start);
  25145. p.prevZ.nextZ = null;
  25146. p.prevZ = null;
  25147. sortLinked(p);
  25148. }
  25149. // Simon Tatham's linked list merge sort algorithm
  25150. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25151. function sortLinked(list) {
  25152. let numMerges;
  25153. let inSize = 1;
  25154. do {
  25155. let p = list;
  25156. let e;
  25157. list = null;
  25158. let tail = null;
  25159. numMerges = 0;
  25160. while (p) {
  25161. numMerges++;
  25162. let q = p;
  25163. let pSize = 0;
  25164. for (let i = 0; i < inSize; i++) {
  25165. pSize++;
  25166. q = q.nextZ;
  25167. if (!q) break;
  25168. }
  25169. let qSize = inSize;
  25170. while (pSize > 0 || (qSize > 0 && q)) {
  25171. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25172. e = p;
  25173. p = p.nextZ;
  25174. pSize--;
  25175. } else {
  25176. e = q;
  25177. q = q.nextZ;
  25178. qSize--;
  25179. }
  25180. if (tail) tail.nextZ = e;
  25181. else list = e;
  25182. e.prevZ = tail;
  25183. tail = e;
  25184. }
  25185. p = q;
  25186. }
  25187. tail.nextZ = null;
  25188. inSize *= 2;
  25189. } while (numMerges > 1);
  25190. return list;
  25191. }
  25192. // z-order of a point given coords and inverse of the longer side of data bbox
  25193. function zOrder(x, y, minX, minY, invSize) {
  25194. // coords are transformed into non-negative 15-bit integer range
  25195. x = (x - minX) * invSize | 0;
  25196. y = (y - minY) * invSize | 0;
  25197. x = (x | (x << 8)) & 0x00FF00FF;
  25198. x = (x | (x << 4)) & 0x0F0F0F0F;
  25199. x = (x | (x << 2)) & 0x33333333;
  25200. x = (x | (x << 1)) & 0x55555555;
  25201. y = (y | (y << 8)) & 0x00FF00FF;
  25202. y = (y | (y << 4)) & 0x0F0F0F0F;
  25203. y = (y | (y << 2)) & 0x33333333;
  25204. y = (y | (y << 1)) & 0x55555555;
  25205. return x | (y << 1);
  25206. }
  25207. // find the leftmost node of a polygon ring
  25208. function getLeftmost(start) {
  25209. let p = start,
  25210. leftmost = start;
  25211. do {
  25212. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25213. p = p.next;
  25214. } while (p !== start);
  25215. return leftmost;
  25216. }
  25217. // check if a point lies within a convex triangle
  25218. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25219. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25220. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25221. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25222. }
  25223. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25224. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25225. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25226. }
  25227. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25228. function isValidDiagonal(a, b) {
  25229. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25230. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25231. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25232. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25233. }
  25234. // signed area of a triangle
  25235. function area(p, q, r) {
  25236. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25237. }
  25238. // check if two points are equal
  25239. function equals(p1, p2) {
  25240. return p1.x === p2.x && p1.y === p2.y;
  25241. }
  25242. // check if two segments intersect
  25243. function intersects(p1, q1, p2, q2) {
  25244. const o1 = sign(area(p1, q1, p2));
  25245. const o2 = sign(area(p1, q1, q2));
  25246. const o3 = sign(area(p2, q2, p1));
  25247. const o4 = sign(area(p2, q2, q1));
  25248. if (o1 !== o2 && o3 !== o4) return true; // general case
  25249. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25250. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25251. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25252. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25253. return false;
  25254. }
  25255. // for collinear points p, q, r, check if point q lies on segment pr
  25256. function onSegment(p, q, r) {
  25257. 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);
  25258. }
  25259. function sign(num) {
  25260. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25261. }
  25262. // check if a polygon diagonal intersects any polygon segments
  25263. function intersectsPolygon(a, b) {
  25264. let p = a;
  25265. do {
  25266. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25267. intersects(p, p.next, a, b)) return true;
  25268. p = p.next;
  25269. } while (p !== a);
  25270. return false;
  25271. }
  25272. // check if a polygon diagonal is locally inside the polygon
  25273. function locallyInside(a, b) {
  25274. return area(a.prev, a, a.next) < 0 ?
  25275. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25276. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25277. }
  25278. // check if the middle point of a polygon diagonal is inside the polygon
  25279. function middleInside(a, b) {
  25280. let p = a;
  25281. let inside = false;
  25282. const px = (a.x + b.x) / 2;
  25283. const py = (a.y + b.y) / 2;
  25284. do {
  25285. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25286. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25287. inside = !inside;
  25288. p = p.next;
  25289. } while (p !== a);
  25290. return inside;
  25291. }
  25292. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25293. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25294. function splitPolygon(a, b) {
  25295. const a2 = createNode(a.i, a.x, a.y),
  25296. b2 = createNode(b.i, b.x, b.y),
  25297. an = a.next,
  25298. bp = b.prev;
  25299. a.next = b;
  25300. b.prev = a;
  25301. a2.next = an;
  25302. an.prev = a2;
  25303. b2.next = a2;
  25304. a2.prev = b2;
  25305. bp.next = b2;
  25306. b2.prev = bp;
  25307. return b2;
  25308. }
  25309. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25310. function insertNode(i, x, y, last) {
  25311. const p = createNode(i, x, y);
  25312. if (!last) {
  25313. p.prev = p;
  25314. p.next = p;
  25315. } else {
  25316. p.next = last.next;
  25317. p.prev = last;
  25318. last.next.prev = p;
  25319. last.next = p;
  25320. }
  25321. return p;
  25322. }
  25323. function removeNode(p) {
  25324. p.next.prev = p.prev;
  25325. p.prev.next = p.next;
  25326. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25327. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25328. }
  25329. function createNode(i, x, y) {
  25330. return {
  25331. i, // vertex index in coordinates array
  25332. x, y, // vertex coordinates
  25333. prev: null, // previous and next vertex nodes in a polygon ring
  25334. next: null,
  25335. z: 0, // z-order curve value
  25336. prevZ: null, // previous and next nodes in z-order
  25337. nextZ: null,
  25338. steiner: false // indicates whether this is a steiner point
  25339. };
  25340. }
  25341. function signedArea(data, start, end, dim) {
  25342. let sum = 0;
  25343. for (let i = start, j = end - dim; i < end; i += dim) {
  25344. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25345. j = i;
  25346. }
  25347. return sum;
  25348. }
  25349. /**
  25350. * An implementation of the earcut polygon triangulation algorithm.
  25351. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25352. *
  25353. * @see https://github.com/mapbox/earcut
  25354. */
  25355. class Earcut {
  25356. /**
  25357. * Triangulates the given shape definition by returning an array of triangles.
  25358. *
  25359. * @param {Array<number>} data - An array with 2D points.
  25360. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25361. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25362. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25363. * representing vertex indices.
  25364. */
  25365. static triangulate( data, holeIndices, dim = 2 ) {
  25366. return earcut( data, holeIndices, dim );
  25367. }
  25368. }
  25369. /**
  25370. * A class containing utility functions for shapes.
  25371. *
  25372. * @hideconstructor
  25373. */
  25374. class ShapeUtils {
  25375. /**
  25376. * Calculate area of a ( 2D ) contour polygon.
  25377. *
  25378. * @param {Array<Vector2>} contour - An array of 2D points.
  25379. * @return {number} The area.
  25380. */
  25381. static area( contour ) {
  25382. const n = contour.length;
  25383. let a = 0.0;
  25384. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25385. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25386. }
  25387. return a * 0.5;
  25388. }
  25389. /**
  25390. * Returns `true` if the given contour uses a clockwise winding order.
  25391. *
  25392. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25393. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25394. */
  25395. static isClockWise( pts ) {
  25396. return ShapeUtils.area( pts ) < 0;
  25397. }
  25398. /**
  25399. * Triangulates the given shape definition.
  25400. *
  25401. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25402. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25403. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25404. */
  25405. static triangulateShape( contour, holes ) {
  25406. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25407. const holeIndices = []; // array of hole indices
  25408. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25409. removeDupEndPts( contour );
  25410. addContour( vertices, contour );
  25411. //
  25412. let holeIndex = contour.length;
  25413. holes.forEach( removeDupEndPts );
  25414. for ( let i = 0; i < holes.length; i ++ ) {
  25415. holeIndices.push( holeIndex );
  25416. holeIndex += holes[ i ].length;
  25417. addContour( vertices, holes[ i ] );
  25418. }
  25419. //
  25420. const triangles = Earcut.triangulate( vertices, holeIndices );
  25421. //
  25422. for ( let i = 0; i < triangles.length; i += 3 ) {
  25423. faces.push( triangles.slice( i, i + 3 ) );
  25424. }
  25425. return faces;
  25426. }
  25427. }
  25428. function removeDupEndPts( points ) {
  25429. const l = points.length;
  25430. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25431. points.pop();
  25432. }
  25433. }
  25434. function addContour( vertices, contour ) {
  25435. for ( let i = 0; i < contour.length; i ++ ) {
  25436. vertices.push( contour[ i ].x );
  25437. vertices.push( contour[ i ].y );
  25438. }
  25439. }
  25440. /**
  25441. * Creates extruded geometry from a path shape.
  25442. *
  25443. * ```js
  25444. * const length = 12, width = 8;
  25445. *
  25446. * const shape = new THREE.Shape();
  25447. * shape.moveTo( 0,0 );
  25448. * shape.lineTo( 0, width );
  25449. * shape.lineTo( length, width );
  25450. * shape.lineTo( length, 0 );
  25451. * shape.lineTo( 0, 0 );
  25452. *
  25453. * const geometry = new THREE.ExtrudeGeometry( shape );
  25454. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25455. * const mesh = new THREE.Mesh( geometry, material ) ;
  25456. * scene.add( mesh );
  25457. * ```
  25458. *
  25459. * @augments BufferGeometry
  25460. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25461. */
  25462. class ExtrudeGeometry extends BufferGeometry {
  25463. /**
  25464. * Constructs a new extrude geometry.
  25465. *
  25466. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25467. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25468. */
  25469. 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 = {} ) {
  25470. super();
  25471. this.type = 'ExtrudeGeometry';
  25472. /**
  25473. * Holds the constructor parameters that have been
  25474. * used to generate the geometry. Any modification
  25475. * after instantiation does not change the geometry.
  25476. *
  25477. * @type {Object}
  25478. */
  25479. this.parameters = {
  25480. shapes: shapes,
  25481. options: options
  25482. };
  25483. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25484. const scope = this;
  25485. const verticesArray = [];
  25486. const uvArray = [];
  25487. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25488. const shape = shapes[ i ];
  25489. addShape( shape );
  25490. }
  25491. // build geometry
  25492. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25493. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25494. this.computeVertexNormals();
  25495. // functions
  25496. function addShape( shape ) {
  25497. const placeholder = [];
  25498. // options
  25499. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25500. const steps = options.steps !== undefined ? options.steps : 1;
  25501. const depth = options.depth !== undefined ? options.depth : 1;
  25502. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25503. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25504. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25505. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25506. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25507. const extrudePath = options.extrudePath;
  25508. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25509. //
  25510. let extrudePts, extrudeByPath = false;
  25511. let splineTube, binormal, normal, position2;
  25512. if ( extrudePath ) {
  25513. extrudePts = extrudePath.getSpacedPoints( steps );
  25514. extrudeByPath = true;
  25515. bevelEnabled = false; // bevels not supported for path extrusion
  25516. // SETUP TNB variables
  25517. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  25518. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  25519. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25520. binormal = new Vector3();
  25521. normal = new Vector3();
  25522. position2 = new Vector3();
  25523. }
  25524. // Safeguards if bevels are not enabled
  25525. if ( ! bevelEnabled ) {
  25526. bevelSegments = 0;
  25527. bevelThickness = 0;
  25528. bevelSize = 0;
  25529. bevelOffset = 0;
  25530. }
  25531. // Variables initialization
  25532. const shapePoints = shape.extractPoints( curveSegments );
  25533. let vertices = shapePoints.shape;
  25534. const holes = shapePoints.holes;
  25535. const reverse = ! ShapeUtils.isClockWise( vertices );
  25536. if ( reverse ) {
  25537. vertices = vertices.reverse();
  25538. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25539. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25540. const ahole = holes[ h ];
  25541. if ( ShapeUtils.isClockWise( ahole ) ) {
  25542. holes[ h ] = ahole.reverse();
  25543. }
  25544. }
  25545. }
  25546. /**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.
  25547. * @param {Array<Vector2>} points
  25548. */
  25549. function mergeOverlappingPoints( points ) {
  25550. const THRESHOLD = 1e-10;
  25551. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25552. let prevPos = points[ 0 ];
  25553. for ( let i = 1; i <= points.length; i ++ ) {
  25554. const currentIndex = i % points.length;
  25555. const currentPos = points[ currentIndex ];
  25556. const dx = currentPos.x - prevPos.x;
  25557. const dy = currentPos.y - prevPos.y;
  25558. const distSq = dx * dx + dy * dy;
  25559. const scalingFactorSqrt = Math.max(
  25560. Math.abs( currentPos.x ),
  25561. Math.abs( currentPos.y ),
  25562. Math.abs( prevPos.x ),
  25563. Math.abs( prevPos.y )
  25564. );
  25565. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25566. if ( distSq <= thresholdSqScaled ) {
  25567. points.splice( currentIndex, 1 );
  25568. i --;
  25569. continue;
  25570. }
  25571. prevPos = currentPos;
  25572. }
  25573. }
  25574. mergeOverlappingPoints( vertices );
  25575. holes.forEach( mergeOverlappingPoints );
  25576. const numHoles = holes.length;
  25577. /* Vertices */
  25578. const contour = vertices; // vertices has all points but contour has only points of circumference
  25579. for ( let h = 0; h < numHoles; h ++ ) {
  25580. const ahole = holes[ h ];
  25581. vertices = vertices.concat( ahole );
  25582. }
  25583. function scalePt2( pt, vec, size ) {
  25584. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  25585. return pt.clone().addScaledVector( vec, size );
  25586. }
  25587. const vlen = vertices.length;
  25588. // Find directions for point movement
  25589. function getBevelVec( inPt, inPrev, inNext ) {
  25590. // computes for inPt the corresponding point inPt' on a new contour
  25591. // shifted by 1 unit (length of normalized vector) to the left
  25592. // if we walk along contour clockwise, this new contour is outside the old one
  25593. //
  25594. // inPt' is the intersection of the two lines parallel to the two
  25595. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25596. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25597. // good reading for geometry algorithms (here: line-line intersection)
  25598. // http://geomalgorithms.com/a05-_intersect-1.html
  25599. const v_prev_x = inPt.x - inPrev.x,
  25600. v_prev_y = inPt.y - inPrev.y;
  25601. const v_next_x = inNext.x - inPt.x,
  25602. v_next_y = inNext.y - inPt.y;
  25603. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25604. // check for collinear edges
  25605. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25606. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25607. // not collinear
  25608. // length of vectors for normalizing
  25609. const v_prev_len = Math.sqrt( v_prev_lensq );
  25610. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25611. // shift adjacent points by unit vectors to the left
  25612. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25613. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25614. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25615. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25616. // scaling factor for v_prev to intersection point
  25617. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25618. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25619. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25620. // vector from inPt to intersection point
  25621. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25622. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25623. // Don't normalize!, otherwise sharp corners become ugly
  25624. // but prevent crazy spikes
  25625. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25626. if ( v_trans_lensq <= 2 ) {
  25627. return new Vector2( v_trans_x, v_trans_y );
  25628. } else {
  25629. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25630. }
  25631. } else {
  25632. // handle special case of collinear edges
  25633. let direction_eq = false; // assumes: opposite
  25634. if ( v_prev_x > Number.EPSILON ) {
  25635. if ( v_next_x > Number.EPSILON ) {
  25636. direction_eq = true;
  25637. }
  25638. } else {
  25639. if ( v_prev_x < - Number.EPSILON ) {
  25640. if ( v_next_x < - Number.EPSILON ) {
  25641. direction_eq = true;
  25642. }
  25643. } else {
  25644. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25645. direction_eq = true;
  25646. }
  25647. }
  25648. }
  25649. if ( direction_eq ) {
  25650. // log("Warning: lines are a straight sequence");
  25651. v_trans_x = - v_prev_y;
  25652. v_trans_y = v_prev_x;
  25653. shrink_by = Math.sqrt( v_prev_lensq );
  25654. } else {
  25655. // log("Warning: lines are a straight spike");
  25656. v_trans_x = v_prev_x;
  25657. v_trans_y = v_prev_y;
  25658. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25659. }
  25660. }
  25661. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25662. }
  25663. const contourMovements = [];
  25664. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25665. if ( j === il ) j = 0;
  25666. if ( k === il ) k = 0;
  25667. // (j)---(i)---(k)
  25668. // log('i,j,k', i, j , k)
  25669. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25670. }
  25671. const holesMovements = [];
  25672. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25673. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25674. const ahole = holes[ h ];
  25675. oneHoleMovements = [];
  25676. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25677. if ( j === il ) j = 0;
  25678. if ( k === il ) k = 0;
  25679. // (j)---(i)---(k)
  25680. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25681. }
  25682. holesMovements.push( oneHoleMovements );
  25683. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25684. }
  25685. let faces;
  25686. if ( bevelSegments === 0 ) {
  25687. faces = ShapeUtils.triangulateShape( contour, holes );
  25688. } else {
  25689. const contractedContourVertices = [];
  25690. const expandedHoleVertices = [];
  25691. // Loop bevelSegments, 1 for the front, 1 for the back
  25692. for ( let b = 0; b < bevelSegments; b ++ ) {
  25693. //for ( b = bevelSegments; b > 0; b -- ) {
  25694. const t = b / bevelSegments;
  25695. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25696. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25697. // contract shape
  25698. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25699. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25700. v( vert.x, vert.y, - z );
  25701. if ( t === 0 ) contractedContourVertices.push( vert );
  25702. }
  25703. // expand holes
  25704. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25705. const ahole = holes[ h ];
  25706. oneHoleMovements = holesMovements[ h ];
  25707. const oneHoleVertices = [];
  25708. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25709. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25710. v( vert.x, vert.y, - z );
  25711. if ( t === 0 ) oneHoleVertices.push( vert );
  25712. }
  25713. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25714. }
  25715. }
  25716. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25717. }
  25718. const flen = faces.length;
  25719. const bs = bevelSize + bevelOffset;
  25720. // Back facing vertices
  25721. for ( let i = 0; i < vlen; i ++ ) {
  25722. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25723. if ( ! extrudeByPath ) {
  25724. v( vert.x, vert.y, 0 );
  25725. } else {
  25726. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25727. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25728. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25729. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25730. v( position2.x, position2.y, position2.z );
  25731. }
  25732. }
  25733. // Add stepped vertices...
  25734. // Including front facing vertices
  25735. for ( let s = 1; s <= steps; s ++ ) {
  25736. for ( let i = 0; i < vlen; i ++ ) {
  25737. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25738. if ( ! extrudeByPath ) {
  25739. v( vert.x, vert.y, depth / steps * s );
  25740. } else {
  25741. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25742. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25743. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25744. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25745. v( position2.x, position2.y, position2.z );
  25746. }
  25747. }
  25748. }
  25749. // Add bevel segments planes
  25750. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25751. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25752. const t = b / bevelSegments;
  25753. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25754. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25755. // contract shape
  25756. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25757. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25758. v( vert.x, vert.y, depth + z );
  25759. }
  25760. // expand holes
  25761. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25762. const ahole = holes[ h ];
  25763. oneHoleMovements = holesMovements[ h ];
  25764. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25765. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25766. if ( ! extrudeByPath ) {
  25767. v( vert.x, vert.y, depth + z );
  25768. } else {
  25769. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25770. }
  25771. }
  25772. }
  25773. }
  25774. /* Faces */
  25775. // Top and bottom faces
  25776. buildLidFaces();
  25777. // Sides faces
  25778. buildSideFaces();
  25779. ///// Internal functions
  25780. function buildLidFaces() {
  25781. const start = verticesArray.length / 3;
  25782. if ( bevelEnabled ) {
  25783. let layer = 0; // steps + 1
  25784. let offset = vlen * layer;
  25785. // Bottom faces
  25786. for ( let i = 0; i < flen; i ++ ) {
  25787. const face = faces[ i ];
  25788. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25789. }
  25790. layer = steps + bevelSegments * 2;
  25791. offset = vlen * layer;
  25792. // Top faces
  25793. for ( let i = 0; i < flen; i ++ ) {
  25794. const face = faces[ i ];
  25795. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25796. }
  25797. } else {
  25798. // Bottom faces
  25799. for ( let i = 0; i < flen; i ++ ) {
  25800. const face = faces[ i ];
  25801. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25802. }
  25803. // Top faces
  25804. for ( let i = 0; i < flen; i ++ ) {
  25805. const face = faces[ i ];
  25806. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25807. }
  25808. }
  25809. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25810. }
  25811. // Create faces for the z-sides of the shape
  25812. function buildSideFaces() {
  25813. const start = verticesArray.length / 3;
  25814. let layeroffset = 0;
  25815. sidewalls( contour, layeroffset );
  25816. layeroffset += contour.length;
  25817. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25818. const ahole = holes[ h ];
  25819. sidewalls( ahole, layeroffset );
  25820. //, true
  25821. layeroffset += ahole.length;
  25822. }
  25823. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25824. }
  25825. function sidewalls( contour, layeroffset ) {
  25826. let i = contour.length;
  25827. while ( -- i >= 0 ) {
  25828. const j = i;
  25829. let k = i - 1;
  25830. if ( k < 0 ) k = contour.length - 1;
  25831. //log('b', i,j, i-1, k,vertices.length);
  25832. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25833. const slen1 = vlen * s;
  25834. const slen2 = vlen * ( s + 1 );
  25835. const a = layeroffset + j + slen1,
  25836. b = layeroffset + k + slen1,
  25837. c = layeroffset + k + slen2,
  25838. d = layeroffset + j + slen2;
  25839. f4( a, b, c, d );
  25840. }
  25841. }
  25842. }
  25843. function v( x, y, z ) {
  25844. placeholder.push( x );
  25845. placeholder.push( y );
  25846. placeholder.push( z );
  25847. }
  25848. function f3( a, b, c ) {
  25849. addVertex( a );
  25850. addVertex( b );
  25851. addVertex( c );
  25852. const nextIndex = verticesArray.length / 3;
  25853. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25854. addUV( uvs[ 0 ] );
  25855. addUV( uvs[ 1 ] );
  25856. addUV( uvs[ 2 ] );
  25857. }
  25858. function f4( a, b, c, d ) {
  25859. addVertex( a );
  25860. addVertex( b );
  25861. addVertex( d );
  25862. addVertex( b );
  25863. addVertex( c );
  25864. addVertex( d );
  25865. const nextIndex = verticesArray.length / 3;
  25866. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25867. addUV( uvs[ 0 ] );
  25868. addUV( uvs[ 1 ] );
  25869. addUV( uvs[ 3 ] );
  25870. addUV( uvs[ 1 ] );
  25871. addUV( uvs[ 2 ] );
  25872. addUV( uvs[ 3 ] );
  25873. }
  25874. function addVertex( index ) {
  25875. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25876. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25877. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25878. }
  25879. function addUV( vector2 ) {
  25880. uvArray.push( vector2.x );
  25881. uvArray.push( vector2.y );
  25882. }
  25883. }
  25884. }
  25885. copy( source ) {
  25886. super.copy( source );
  25887. this.parameters = Object.assign( {}, source.parameters );
  25888. return this;
  25889. }
  25890. toJSON() {
  25891. const data = super.toJSON();
  25892. const shapes = this.parameters.shapes;
  25893. const options = this.parameters.options;
  25894. return toJSON$1( shapes, options, data );
  25895. }
  25896. /**
  25897. * Factory method for creating an instance of this class from the given
  25898. * JSON object.
  25899. *
  25900. * @param {Object} data - A JSON object representing the serialized geometry.
  25901. * @param {Array<Shape>} shapes - An array of shapes.
  25902. * @return {ExtrudeGeometry} A new instance.
  25903. */
  25904. static fromJSON( data, shapes ) {
  25905. const geometryShapes = [];
  25906. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25907. const shape = shapes[ data.shapes[ j ] ];
  25908. geometryShapes.push( shape );
  25909. }
  25910. const extrudePath = data.options.extrudePath;
  25911. if ( extrudePath !== undefined ) {
  25912. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25913. }
  25914. return new ExtrudeGeometry( geometryShapes, data.options );
  25915. }
  25916. }
  25917. const WorldUVGenerator = {
  25918. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  25919. const a_x = vertices[ indexA * 3 ];
  25920. const a_y = vertices[ indexA * 3 + 1 ];
  25921. const b_x = vertices[ indexB * 3 ];
  25922. const b_y = vertices[ indexB * 3 + 1 ];
  25923. const c_x = vertices[ indexC * 3 ];
  25924. const c_y = vertices[ indexC * 3 + 1 ];
  25925. return [
  25926. new Vector2( a_x, a_y ),
  25927. new Vector2( b_x, b_y ),
  25928. new Vector2( c_x, c_y )
  25929. ];
  25930. },
  25931. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  25932. const a_x = vertices[ indexA * 3 ];
  25933. const a_y = vertices[ indexA * 3 + 1 ];
  25934. const a_z = vertices[ indexA * 3 + 2 ];
  25935. const b_x = vertices[ indexB * 3 ];
  25936. const b_y = vertices[ indexB * 3 + 1 ];
  25937. const b_z = vertices[ indexB * 3 + 2 ];
  25938. const c_x = vertices[ indexC * 3 ];
  25939. const c_y = vertices[ indexC * 3 + 1 ];
  25940. const c_z = vertices[ indexC * 3 + 2 ];
  25941. const d_x = vertices[ indexD * 3 ];
  25942. const d_y = vertices[ indexD * 3 + 1 ];
  25943. const d_z = vertices[ indexD * 3 + 2 ];
  25944. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  25945. return [
  25946. new Vector2( a_x, 1 - a_z ),
  25947. new Vector2( b_x, 1 - b_z ),
  25948. new Vector2( c_x, 1 - c_z ),
  25949. new Vector2( d_x, 1 - d_z )
  25950. ];
  25951. } else {
  25952. return [
  25953. new Vector2( a_y, 1 - a_z ),
  25954. new Vector2( b_y, 1 - b_z ),
  25955. new Vector2( c_y, 1 - c_z ),
  25956. new Vector2( d_y, 1 - d_z )
  25957. ];
  25958. }
  25959. }
  25960. };
  25961. function toJSON$1( shapes, options, data ) {
  25962. data.shapes = [];
  25963. if ( Array.isArray( shapes ) ) {
  25964. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25965. const shape = shapes[ i ];
  25966. data.shapes.push( shape.uuid );
  25967. }
  25968. } else {
  25969. data.shapes.push( shapes.uuid );
  25970. }
  25971. data.options = Object.assign( {}, options );
  25972. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  25973. return data;
  25974. }
  25975. /**
  25976. * A geometry class for representing an icosahedron.
  25977. *
  25978. * ```js
  25979. * const geometry = new THREE.IcosahedronGeometry();
  25980. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25981. * const icosahedron = new THREE.Mesh( geometry, material );
  25982. * scene.add( icosahedron );
  25983. * ```
  25984. *
  25985. * @augments PolyhedronGeometry
  25986. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  25987. */
  25988. class IcosahedronGeometry extends PolyhedronGeometry {
  25989. /**
  25990. * Constructs a new icosahedron geometry.
  25991. *
  25992. * @param {number} [radius=1] - Radius of the icosahedron.
  25993. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  25994. */
  25995. constructor( radius = 1, detail = 0 ) {
  25996. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  25997. const vertices = [
  25998. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  25999. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26000. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26001. ];
  26002. const indices = [
  26003. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26004. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26005. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26006. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26007. ];
  26008. super( vertices, indices, radius, detail );
  26009. this.type = 'IcosahedronGeometry';
  26010. /**
  26011. * Holds the constructor parameters that have been
  26012. * used to generate the geometry. Any modification
  26013. * after instantiation does not change the geometry.
  26014. *
  26015. * @type {Object}
  26016. */
  26017. this.parameters = {
  26018. radius: radius,
  26019. detail: detail
  26020. };
  26021. }
  26022. /**
  26023. * Factory method for creating an instance of this class from the given
  26024. * JSON object.
  26025. *
  26026. * @param {Object} data - A JSON object representing the serialized geometry.
  26027. * @return {IcosahedronGeometry} A new instance.
  26028. */
  26029. static fromJSON( data ) {
  26030. return new IcosahedronGeometry( data.radius, data.detail );
  26031. }
  26032. }
  26033. /**
  26034. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26035. *
  26036. * ```js
  26037. * const points = [];
  26038. * for ( let i = 0; i < 10; i ++ ) {
  26039. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26040. * }
  26041. * const geometry = new THREE.LatheGeometry( points );
  26042. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26043. * const lathe = new THREE.Mesh( geometry, material );
  26044. * scene.add( lathe );
  26045. * ```
  26046. *
  26047. * @augments BufferGeometry
  26048. * @demo scenes/geometry-browser.html#LatheGeometry
  26049. */
  26050. class LatheGeometry extends BufferGeometry {
  26051. /**
  26052. * Constructs a new lathe geometry.
  26053. *
  26054. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26055. * must be greater than zero.
  26056. * @param {number} [segments=12] - The number of circumference segments to generate.
  26057. * @param {number} [phiStart=0] - The starting angle in radians.
  26058. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26059. * closed lathe, less than 2PI is a portion.
  26060. */
  26061. 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 ) {
  26062. super();
  26063. this.type = 'LatheGeometry';
  26064. /**
  26065. * Holds the constructor parameters that have been
  26066. * used to generate the geometry. Any modification
  26067. * after instantiation does not change the geometry.
  26068. *
  26069. * @type {Object}
  26070. */
  26071. this.parameters = {
  26072. points: points,
  26073. segments: segments,
  26074. phiStart: phiStart,
  26075. phiLength: phiLength
  26076. };
  26077. segments = Math.floor( segments );
  26078. // clamp phiLength so it's in range of [ 0, 2PI ]
  26079. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26080. // buffers
  26081. const indices = [];
  26082. const vertices = [];
  26083. const uvs = [];
  26084. const initNormals = [];
  26085. const normals = [];
  26086. // helper variables
  26087. const inverseSegments = 1.0 / segments;
  26088. const vertex = new Vector3();
  26089. const uv = new Vector2();
  26090. const normal = new Vector3();
  26091. const curNormal = new Vector3();
  26092. const prevNormal = new Vector3();
  26093. let dx = 0;
  26094. let dy = 0;
  26095. // pre-compute normals for initial "meridian"
  26096. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26097. switch ( j ) {
  26098. case 0: // special handling for 1st vertex on path
  26099. dx = points[ j + 1 ].x - points[ j ].x;
  26100. dy = points[ j + 1 ].y - points[ j ].y;
  26101. normal.x = dy * 1.0;
  26102. normal.y = - dx;
  26103. normal.z = dy * 0.0;
  26104. prevNormal.copy( normal );
  26105. normal.normalize();
  26106. initNormals.push( normal.x, normal.y, normal.z );
  26107. break;
  26108. case ( points.length - 1 ): // special handling for last Vertex on path
  26109. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26110. break;
  26111. default: // default handling for all vertices in between
  26112. dx = points[ j + 1 ].x - points[ j ].x;
  26113. dy = points[ j + 1 ].y - points[ j ].y;
  26114. normal.x = dy * 1.0;
  26115. normal.y = - dx;
  26116. normal.z = dy * 0.0;
  26117. curNormal.copy( normal );
  26118. normal.x += prevNormal.x;
  26119. normal.y += prevNormal.y;
  26120. normal.z += prevNormal.z;
  26121. normal.normalize();
  26122. initNormals.push( normal.x, normal.y, normal.z );
  26123. prevNormal.copy( curNormal );
  26124. }
  26125. }
  26126. // generate vertices, uvs and normals
  26127. for ( let i = 0; i <= segments; i ++ ) {
  26128. const phi = phiStart + i * inverseSegments * phiLength;
  26129. const sin = Math.sin( phi );
  26130. const cos = Math.cos( phi );
  26131. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26132. // vertex
  26133. vertex.x = points[ j ].x * sin;
  26134. vertex.y = points[ j ].y;
  26135. vertex.z = points[ j ].x * cos;
  26136. vertices.push( vertex.x, vertex.y, vertex.z );
  26137. // uv
  26138. uv.x = i / segments;
  26139. uv.y = j / ( points.length - 1 );
  26140. uvs.push( uv.x, uv.y );
  26141. // normal
  26142. const x = initNormals[ 3 * j + 0 ] * sin;
  26143. const y = initNormals[ 3 * j + 1 ];
  26144. const z = initNormals[ 3 * j + 0 ] * cos;
  26145. normals.push( x, y, z );
  26146. }
  26147. }
  26148. // indices
  26149. for ( let i = 0; i < segments; i ++ ) {
  26150. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26151. const base = j + i * points.length;
  26152. const a = base;
  26153. const b = base + points.length;
  26154. const c = base + points.length + 1;
  26155. const d = base + 1;
  26156. // faces
  26157. indices.push( a, b, d );
  26158. indices.push( c, d, b );
  26159. }
  26160. }
  26161. // build geometry
  26162. this.setIndex( indices );
  26163. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26164. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26165. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26166. }
  26167. copy( source ) {
  26168. super.copy( source );
  26169. this.parameters = Object.assign( {}, source.parameters );
  26170. return this;
  26171. }
  26172. /**
  26173. * Factory method for creating an instance of this class from the given
  26174. * JSON object.
  26175. *
  26176. * @param {Object} data - A JSON object representing the serialized geometry.
  26177. * @return {LatheGeometry} A new instance.
  26178. */
  26179. static fromJSON( data ) {
  26180. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26181. }
  26182. }
  26183. /**
  26184. * A geometry class for representing an octahedron.
  26185. *
  26186. * ```js
  26187. * const geometry = new THREE.OctahedronGeometry();
  26188. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26189. * const octahedron = new THREE.Mesh( geometry, material );
  26190. * scene.add( octahedron );
  26191. * ```
  26192. *
  26193. * @augments PolyhedronGeometry
  26194. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26195. */
  26196. class OctahedronGeometry extends PolyhedronGeometry {
  26197. /**
  26198. * Constructs a new octahedron geometry.
  26199. *
  26200. * @param {number} [radius=1] - Radius of the octahedron.
  26201. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26202. */
  26203. constructor( radius = 1, detail = 0 ) {
  26204. const vertices = [
  26205. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26206. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26207. ];
  26208. const indices = [
  26209. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26210. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26211. 1, 3, 4, 1, 4, 2
  26212. ];
  26213. super( vertices, indices, radius, detail );
  26214. this.type = 'OctahedronGeometry';
  26215. /**
  26216. * Holds the constructor parameters that have been
  26217. * used to generate the geometry. Any modification
  26218. * after instantiation does not change the geometry.
  26219. *
  26220. * @type {Object}
  26221. */
  26222. this.parameters = {
  26223. radius: radius,
  26224. detail: detail
  26225. };
  26226. }
  26227. /**
  26228. * Factory method for creating an instance of this class from the given
  26229. * JSON object.
  26230. *
  26231. * @param {Object} data - A JSON object representing the serialized geometry.
  26232. * @return {OctahedronGeometry} A new instance.
  26233. */
  26234. static fromJSON( data ) {
  26235. return new OctahedronGeometry( data.radius, data.detail );
  26236. }
  26237. }
  26238. /**
  26239. * A geometry class for representing a plane.
  26240. *
  26241. * ```js
  26242. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26243. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26244. * const plane = new THREE.Mesh( geometry, material );
  26245. * scene.add( plane );
  26246. * ```
  26247. *
  26248. * @augments BufferGeometry
  26249. * @demo scenes/geometry-browser.html#PlaneGeometry
  26250. */
  26251. class PlaneGeometry extends BufferGeometry {
  26252. /**
  26253. * Constructs a new plane geometry.
  26254. *
  26255. * @param {number} [width=1] - The width along the X axis.
  26256. * @param {number} [height=1] - The height along the Y axis
  26257. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26258. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26259. */
  26260. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26261. super();
  26262. this.type = 'PlaneGeometry';
  26263. /**
  26264. * Holds the constructor parameters that have been
  26265. * used to generate the geometry. Any modification
  26266. * after instantiation does not change the geometry.
  26267. *
  26268. * @type {Object}
  26269. */
  26270. this.parameters = {
  26271. width: width,
  26272. height: height,
  26273. widthSegments: widthSegments,
  26274. heightSegments: heightSegments
  26275. };
  26276. const width_half = width / 2;
  26277. const height_half = height / 2;
  26278. const gridX = Math.floor( widthSegments );
  26279. const gridY = Math.floor( heightSegments );
  26280. const gridX1 = gridX + 1;
  26281. const gridY1 = gridY + 1;
  26282. const segment_width = width / gridX;
  26283. const segment_height = height / gridY;
  26284. //
  26285. const indices = [];
  26286. const vertices = [];
  26287. const normals = [];
  26288. const uvs = [];
  26289. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26290. const y = iy * segment_height - height_half;
  26291. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26292. const x = ix * segment_width - width_half;
  26293. vertices.push( x, - y, 0 );
  26294. normals.push( 0, 0, 1 );
  26295. uvs.push( ix / gridX );
  26296. uvs.push( 1 - ( iy / gridY ) );
  26297. }
  26298. }
  26299. for ( let iy = 0; iy < gridY; iy ++ ) {
  26300. for ( let ix = 0; ix < gridX; ix ++ ) {
  26301. const a = ix + gridX1 * iy;
  26302. const b = ix + gridX1 * ( iy + 1 );
  26303. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26304. const d = ( ix + 1 ) + gridX1 * iy;
  26305. indices.push( a, b, d );
  26306. indices.push( b, c, d );
  26307. }
  26308. }
  26309. this.setIndex( indices );
  26310. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26311. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26312. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26313. }
  26314. copy( source ) {
  26315. super.copy( source );
  26316. this.parameters = Object.assign( {}, source.parameters );
  26317. return this;
  26318. }
  26319. /**
  26320. * Factory method for creating an instance of this class from the given
  26321. * JSON object.
  26322. *
  26323. * @param {Object} data - A JSON object representing the serialized geometry.
  26324. * @return {PlaneGeometry} A new instance.
  26325. */
  26326. static fromJSON( data ) {
  26327. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26328. }
  26329. }
  26330. /**
  26331. * A class for generating a two-dimensional ring geometry.
  26332. *
  26333. * ```js
  26334. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26335. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26336. * const mesh = new THREE.Mesh( geometry, material );
  26337. * scene.add( mesh );
  26338. * ```
  26339. *
  26340. * @augments BufferGeometry
  26341. * @demo scenes/geometry-browser.html#RingGeometry
  26342. */
  26343. class RingGeometry extends BufferGeometry {
  26344. /**
  26345. * Constructs a new ring geometry.
  26346. *
  26347. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26348. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26349. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26350. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26351. * @param {number} [thetaStart=0] - Starting angle in radians.
  26352. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26353. */
  26354. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26355. super();
  26356. this.type = 'RingGeometry';
  26357. /**
  26358. * Holds the constructor parameters that have been
  26359. * used to generate the geometry. Any modification
  26360. * after instantiation does not change the geometry.
  26361. *
  26362. * @type {Object}
  26363. */
  26364. this.parameters = {
  26365. innerRadius: innerRadius,
  26366. outerRadius: outerRadius,
  26367. thetaSegments: thetaSegments,
  26368. phiSegments: phiSegments,
  26369. thetaStart: thetaStart,
  26370. thetaLength: thetaLength
  26371. };
  26372. thetaSegments = Math.max( 3, thetaSegments );
  26373. phiSegments = Math.max( 1, phiSegments );
  26374. // buffers
  26375. const indices = [];
  26376. const vertices = [];
  26377. const normals = [];
  26378. const uvs = [];
  26379. // some helper variables
  26380. let radius = innerRadius;
  26381. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26382. const vertex = new Vector3();
  26383. const uv = new Vector2();
  26384. // generate vertices, normals and uvs
  26385. for ( let j = 0; j <= phiSegments; j ++ ) {
  26386. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26387. // values are generate from the inside of the ring to the outside
  26388. const segment = thetaStart + i / thetaSegments * thetaLength;
  26389. // vertex
  26390. vertex.x = radius * Math.cos( segment );
  26391. vertex.y = radius * Math.sin( segment );
  26392. vertices.push( vertex.x, vertex.y, vertex.z );
  26393. // normal
  26394. normals.push( 0, 0, 1 );
  26395. // uv
  26396. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26397. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26398. uvs.push( uv.x, uv.y );
  26399. }
  26400. // increase the radius for next row of vertices
  26401. radius += radiusStep;
  26402. }
  26403. // indices
  26404. for ( let j = 0; j < phiSegments; j ++ ) {
  26405. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26406. for ( let i = 0; i < thetaSegments; i ++ ) {
  26407. const segment = i + thetaSegmentLevel;
  26408. const a = segment;
  26409. const b = segment + thetaSegments + 1;
  26410. const c = segment + thetaSegments + 2;
  26411. const d = segment + 1;
  26412. // faces
  26413. indices.push( a, b, d );
  26414. indices.push( b, c, d );
  26415. }
  26416. }
  26417. // build geometry
  26418. this.setIndex( indices );
  26419. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26420. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26421. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26422. }
  26423. copy( source ) {
  26424. super.copy( source );
  26425. this.parameters = Object.assign( {}, source.parameters );
  26426. return this;
  26427. }
  26428. /**
  26429. * Factory method for creating an instance of this class from the given
  26430. * JSON object.
  26431. *
  26432. * @param {Object} data - A JSON object representing the serialized geometry.
  26433. * @return {RingGeometry} A new instance.
  26434. */
  26435. static fromJSON( data ) {
  26436. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26437. }
  26438. }
  26439. /**
  26440. * Creates an one-sided polygonal geometry from one or more path shapes.
  26441. *
  26442. * ```js
  26443. * const arcShape = new THREE.Shape()
  26444. * .moveTo( 5, 1 )
  26445. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26446. *
  26447. * const geometry = new THREE.ShapeGeometry( arcShape );
  26448. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26449. * const mesh = new THREE.Mesh( geometry, material ) ;
  26450. * scene.add( mesh );
  26451. * ```
  26452. *
  26453. * @augments BufferGeometry
  26454. * @demo scenes/geometry-browser.html#ShapeGeometry
  26455. */
  26456. class ShapeGeometry extends BufferGeometry {
  26457. /**
  26458. * Constructs a new shape geometry.
  26459. *
  26460. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26461. * @param {number} [curveSegments=12] - Number of segments per shape.
  26462. */
  26463. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26464. super();
  26465. this.type = 'ShapeGeometry';
  26466. /**
  26467. * Holds the constructor parameters that have been
  26468. * used to generate the geometry. Any modification
  26469. * after instantiation does not change the geometry.
  26470. *
  26471. * @type {Object}
  26472. */
  26473. this.parameters = {
  26474. shapes: shapes,
  26475. curveSegments: curveSegments
  26476. };
  26477. // buffers
  26478. const indices = [];
  26479. const vertices = [];
  26480. const normals = [];
  26481. const uvs = [];
  26482. // helper variables
  26483. let groupStart = 0;
  26484. let groupCount = 0;
  26485. // allow single and array values for "shapes" parameter
  26486. if ( Array.isArray( shapes ) === false ) {
  26487. addShape( shapes );
  26488. } else {
  26489. for ( let i = 0; i < shapes.length; i ++ ) {
  26490. addShape( shapes[ i ] );
  26491. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26492. groupStart += groupCount;
  26493. groupCount = 0;
  26494. }
  26495. }
  26496. // build geometry
  26497. this.setIndex( indices );
  26498. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26499. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26500. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26501. // helper functions
  26502. function addShape( shape ) {
  26503. const indexOffset = vertices.length / 3;
  26504. const points = shape.extractPoints( curveSegments );
  26505. let shapeVertices = points.shape;
  26506. const shapeHoles = points.holes;
  26507. // check direction of vertices
  26508. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26509. shapeVertices = shapeVertices.reverse();
  26510. }
  26511. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26512. const shapeHole = shapeHoles[ i ];
  26513. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26514. shapeHoles[ i ] = shapeHole.reverse();
  26515. }
  26516. }
  26517. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26518. // join vertices of inner and outer paths to a single array
  26519. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26520. const shapeHole = shapeHoles[ i ];
  26521. shapeVertices = shapeVertices.concat( shapeHole );
  26522. }
  26523. // vertices, normals, uvs
  26524. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26525. const vertex = shapeVertices[ i ];
  26526. vertices.push( vertex.x, vertex.y, 0 );
  26527. normals.push( 0, 0, 1 );
  26528. uvs.push( vertex.x, vertex.y ); // world uvs
  26529. }
  26530. // indices
  26531. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26532. const face = faces[ i ];
  26533. const a = face[ 0 ] + indexOffset;
  26534. const b = face[ 1 ] + indexOffset;
  26535. const c = face[ 2 ] + indexOffset;
  26536. indices.push( a, b, c );
  26537. groupCount += 3;
  26538. }
  26539. }
  26540. }
  26541. copy( source ) {
  26542. super.copy( source );
  26543. this.parameters = Object.assign( {}, source.parameters );
  26544. return this;
  26545. }
  26546. toJSON() {
  26547. const data = super.toJSON();
  26548. const shapes = this.parameters.shapes;
  26549. return toJSON( shapes, data );
  26550. }
  26551. /**
  26552. * Factory method for creating an instance of this class from the given
  26553. * JSON object.
  26554. *
  26555. * @param {Object} data - A JSON object representing the serialized geometry.
  26556. * @param {Array<Shape>} shapes - An array of shapes.
  26557. * @return {ShapeGeometry} A new instance.
  26558. */
  26559. static fromJSON( data, shapes ) {
  26560. const geometryShapes = [];
  26561. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26562. const shape = shapes[ data.shapes[ j ] ];
  26563. geometryShapes.push( shape );
  26564. }
  26565. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26566. }
  26567. }
  26568. function toJSON( shapes, data ) {
  26569. data.shapes = [];
  26570. if ( Array.isArray( shapes ) ) {
  26571. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26572. const shape = shapes[ i ];
  26573. data.shapes.push( shape.uuid );
  26574. }
  26575. } else {
  26576. data.shapes.push( shapes.uuid );
  26577. }
  26578. return data;
  26579. }
  26580. /**
  26581. * A class for generating a sphere geometry.
  26582. *
  26583. * ```js
  26584. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26585. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26586. * const sphere = new THREE.Mesh( geometry, material );
  26587. * scene.add( sphere );
  26588. * ```
  26589. *
  26590. * @augments BufferGeometry
  26591. * @demo scenes/geometry-browser.html#SphereGeometry
  26592. */
  26593. class SphereGeometry extends BufferGeometry {
  26594. /**
  26595. * Constructs a new sphere geometry.
  26596. *
  26597. * @param {number} [radius=1] - The sphere radius.
  26598. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26599. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26600. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26601. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26602. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26603. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26604. */
  26605. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26606. super();
  26607. this.type = 'SphereGeometry';
  26608. /**
  26609. * Holds the constructor parameters that have been
  26610. * used to generate the geometry. Any modification
  26611. * after instantiation does not change the geometry.
  26612. *
  26613. * @type {Object}
  26614. */
  26615. this.parameters = {
  26616. radius: radius,
  26617. widthSegments: widthSegments,
  26618. heightSegments: heightSegments,
  26619. phiStart: phiStart,
  26620. phiLength: phiLength,
  26621. thetaStart: thetaStart,
  26622. thetaLength: thetaLength
  26623. };
  26624. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26625. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26626. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26627. let index = 0;
  26628. const grid = [];
  26629. const vertex = new Vector3();
  26630. const normal = new Vector3();
  26631. // buffers
  26632. const indices = [];
  26633. const vertices = [];
  26634. const normals = [];
  26635. const uvs = [];
  26636. // generate vertices, normals and uvs
  26637. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26638. const verticesRow = [];
  26639. const v = iy / heightSegments;
  26640. const theta = thetaStart + v * thetaLength;
  26641. const y = radius * Math.cos( theta );
  26642. const ringRadius = Math.sqrt( radius * radius - y * y );
  26643. // special case for the poles
  26644. let uOffset = 0;
  26645. if ( iy === 0 && thetaStart === 0 ) {
  26646. uOffset = 0.5 / widthSegments;
  26647. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26648. uOffset = -0.5 / widthSegments;
  26649. }
  26650. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26651. const u = ix / widthSegments;
  26652. const phi = phiStart + u * phiLength;
  26653. // vertex
  26654. vertex.x = - ringRadius * Math.cos( phi );
  26655. vertex.y = y;
  26656. vertex.z = ringRadius * Math.sin( phi );
  26657. vertices.push( vertex.x, vertex.y, vertex.z );
  26658. // normal
  26659. normal.copy( vertex ).normalize();
  26660. normals.push( normal.x, normal.y, normal.z );
  26661. // uv
  26662. uvs.push( u + uOffset, 1 - v );
  26663. verticesRow.push( index ++ );
  26664. }
  26665. grid.push( verticesRow );
  26666. }
  26667. // indices
  26668. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26669. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26670. const a = grid[ iy ][ ix + 1 ];
  26671. const b = grid[ iy ][ ix ];
  26672. const c = grid[ iy + 1 ][ ix ];
  26673. const d = grid[ iy + 1 ][ ix + 1 ];
  26674. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26675. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26676. }
  26677. }
  26678. // build geometry
  26679. this.setIndex( indices );
  26680. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26681. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26682. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26683. }
  26684. copy( source ) {
  26685. super.copy( source );
  26686. this.parameters = Object.assign( {}, source.parameters );
  26687. return this;
  26688. }
  26689. /**
  26690. * Factory method for creating an instance of this class from the given
  26691. * JSON object.
  26692. *
  26693. * @param {Object} data - A JSON object representing the serialized geometry.
  26694. * @return {SphereGeometry} A new instance.
  26695. */
  26696. static fromJSON( data ) {
  26697. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26698. }
  26699. }
  26700. /**
  26701. * A geometry class for representing an tetrahedron.
  26702. *
  26703. * ```js
  26704. * const geometry = new THREE.TetrahedronGeometry();
  26705. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26706. * const tetrahedron = new THREE.Mesh( geometry, material );
  26707. * scene.add( tetrahedron );
  26708. * ```
  26709. *
  26710. * @augments PolyhedronGeometry
  26711. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  26712. */
  26713. class TetrahedronGeometry extends PolyhedronGeometry {
  26714. /**
  26715. * Constructs a new tetrahedron geometry.
  26716. *
  26717. * @param {number} [radius=1] - Radius of the tetrahedron.
  26718. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26719. */
  26720. constructor( radius = 1, detail = 0 ) {
  26721. const vertices = [
  26722. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26723. ];
  26724. const indices = [
  26725. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26726. ];
  26727. super( vertices, indices, radius, detail );
  26728. this.type = 'TetrahedronGeometry';
  26729. /**
  26730. * Holds the constructor parameters that have been
  26731. * used to generate the geometry. Any modification
  26732. * after instantiation does not change the geometry.
  26733. *
  26734. * @type {Object}
  26735. */
  26736. this.parameters = {
  26737. radius: radius,
  26738. detail: detail
  26739. };
  26740. }
  26741. /**
  26742. * Factory method for creating an instance of this class from the given
  26743. * JSON object.
  26744. *
  26745. * @param {Object} data - A JSON object representing the serialized geometry.
  26746. * @return {TetrahedronGeometry} A new instance.
  26747. */
  26748. static fromJSON( data ) {
  26749. return new TetrahedronGeometry( data.radius, data.detail );
  26750. }
  26751. }
  26752. /**
  26753. * A geometry class for representing an torus.
  26754. *
  26755. * ```js
  26756. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26757. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26758. * const torus = new THREE.Mesh( geometry, material );
  26759. * scene.add( torus );
  26760. * ```
  26761. *
  26762. * @augments BufferGeometry
  26763. * @demo scenes/geometry-browser.html#TorusGeometry
  26764. */
  26765. class TorusGeometry extends BufferGeometry {
  26766. /**
  26767. * Constructs a new torus geometry.
  26768. *
  26769. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26770. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26771. * @param {number} [radialSegments=12] - The number of radial segments.
  26772. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26773. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26774. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  26775. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  26776. */
  26777. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26778. super();
  26779. this.type = 'TorusGeometry';
  26780. /**
  26781. * Holds the constructor parameters that have been
  26782. * used to generate the geometry. Any modification
  26783. * after instantiation does not change the geometry.
  26784. *
  26785. * @type {Object}
  26786. */
  26787. this.parameters = {
  26788. radius: radius,
  26789. tube: tube,
  26790. radialSegments: radialSegments,
  26791. tubularSegments: tubularSegments,
  26792. arc: arc,
  26793. thetaStart: thetaStart,
  26794. thetaLength: thetaLength,
  26795. };
  26796. radialSegments = Math.floor( radialSegments );
  26797. tubularSegments = Math.floor( tubularSegments );
  26798. // buffers
  26799. const indices = [];
  26800. const vertices = [];
  26801. const normals = [];
  26802. const uvs = [];
  26803. // helper variables
  26804. const center = new Vector3();
  26805. const vertex = new Vector3();
  26806. const normal = new Vector3();
  26807. // generate vertices, normals and uvs
  26808. for ( let j = 0; j <= radialSegments; j ++ ) {
  26809. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  26810. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26811. const u = i / tubularSegments * arc;
  26812. // vertex
  26813. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26814. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26815. vertex.z = tube * Math.sin( v );
  26816. vertices.push( vertex.x, vertex.y, vertex.z );
  26817. // normal
  26818. center.x = radius * Math.cos( u );
  26819. center.y = radius * Math.sin( u );
  26820. normal.subVectors( vertex, center ).normalize();
  26821. normals.push( normal.x, normal.y, normal.z );
  26822. // uv
  26823. uvs.push( i / tubularSegments );
  26824. uvs.push( j / radialSegments );
  26825. }
  26826. }
  26827. // generate indices
  26828. for ( let j = 1; j <= radialSegments; j ++ ) {
  26829. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26830. // indices
  26831. const a = ( tubularSegments + 1 ) * j + i - 1;
  26832. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26833. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26834. const d = ( tubularSegments + 1 ) * j + i;
  26835. // faces
  26836. indices.push( a, b, d );
  26837. indices.push( b, c, d );
  26838. }
  26839. }
  26840. // build geometry
  26841. this.setIndex( indices );
  26842. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26843. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26844. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26845. }
  26846. copy( source ) {
  26847. super.copy( source );
  26848. this.parameters = Object.assign( {}, source.parameters );
  26849. return this;
  26850. }
  26851. /**
  26852. * Factory method for creating an instance of this class from the given
  26853. * JSON object.
  26854. *
  26855. * @param {Object} data - A JSON object representing the serialized geometry.
  26856. * @return {TorusGeometry} A new instance.
  26857. */
  26858. static fromJSON( data ) {
  26859. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26860. }
  26861. }
  26862. /**
  26863. * Creates a torus knot, the particular shape of which is defined by a pair
  26864. * of coprime integers, p and q. If p and q are not coprime, the result will
  26865. * be a torus link.
  26866. *
  26867. * ```js
  26868. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26869. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26870. * const torusKnot = new THREE.Mesh( geometry, material );
  26871. * scene.add( torusKnot );
  26872. * ```
  26873. *
  26874. * @augments BufferGeometry
  26875. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  26876. */
  26877. class TorusKnotGeometry extends BufferGeometry {
  26878. /**
  26879. * Constructs a new torus knot geometry.
  26880. *
  26881. * @param {number} [radius=1] - Radius of the torus knot.
  26882. * @param {number} [tube=0.4] - Radius of the tube.
  26883. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26884. * @param {number} [radialSegments=8] - The number of radial segments.
  26885. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26886. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26887. */
  26888. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26889. super();
  26890. this.type = 'TorusKnotGeometry';
  26891. /**
  26892. * Holds the constructor parameters that have been
  26893. * used to generate the geometry. Any modification
  26894. * after instantiation does not change the geometry.
  26895. *
  26896. * @type {Object}
  26897. */
  26898. this.parameters = {
  26899. radius: radius,
  26900. tube: tube,
  26901. tubularSegments: tubularSegments,
  26902. radialSegments: radialSegments,
  26903. p: p,
  26904. q: q
  26905. };
  26906. tubularSegments = Math.floor( tubularSegments );
  26907. radialSegments = Math.floor( radialSegments );
  26908. // buffers
  26909. const indices = [];
  26910. const vertices = [];
  26911. const normals = [];
  26912. const uvs = [];
  26913. // helper variables
  26914. const vertex = new Vector3();
  26915. const normal = new Vector3();
  26916. const P1 = new Vector3();
  26917. const P2 = new Vector3();
  26918. const B = new Vector3();
  26919. const T = new Vector3();
  26920. const N = new Vector3();
  26921. // generate vertices, normals and uvs
  26922. for ( let i = 0; i <= tubularSegments; ++ i ) {
  26923. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  26924. const u = i / tubularSegments * p * Math.PI * 2;
  26925. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  26926. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26927. calculatePositionOnCurve( u, p, q, radius, P1 );
  26928. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  26929. // calculate orthonormal basis
  26930. T.subVectors( P2, P1 );
  26931. N.addVectors( P2, P1 );
  26932. B.crossVectors( T, N );
  26933. N.crossVectors( B, T );
  26934. // normalize B, N. T can be ignored, we don't use it
  26935. B.normalize();
  26936. N.normalize();
  26937. for ( let j = 0; j <= radialSegments; ++ j ) {
  26938. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26939. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26940. const v = j / radialSegments * Math.PI * 2;
  26941. const cx = - tube * Math.cos( v );
  26942. const cy = tube * Math.sin( v );
  26943. // now calculate the final vertex position.
  26944. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  26945. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  26946. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  26947. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  26948. vertices.push( vertex.x, vertex.y, vertex.z );
  26949. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  26950. normal.subVectors( vertex, P1 ).normalize();
  26951. normals.push( normal.x, normal.y, normal.z );
  26952. // uv
  26953. uvs.push( i / tubularSegments );
  26954. uvs.push( j / radialSegments );
  26955. }
  26956. }
  26957. // generate indices
  26958. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26959. for ( let i = 1; i <= radialSegments; i ++ ) {
  26960. // indices
  26961. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26962. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26963. const c = ( radialSegments + 1 ) * j + i;
  26964. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26965. // faces
  26966. indices.push( a, b, d );
  26967. indices.push( b, c, d );
  26968. }
  26969. }
  26970. // build geometry
  26971. this.setIndex( indices );
  26972. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26973. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26974. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26975. // this function calculates the current position on the torus curve
  26976. function calculatePositionOnCurve( u, p, q, radius, position ) {
  26977. const cu = Math.cos( u );
  26978. const su = Math.sin( u );
  26979. const quOverP = q / p * u;
  26980. const cs = Math.cos( quOverP );
  26981. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  26982. position.y = radius * ( 2 + cs ) * su * 0.5;
  26983. position.z = radius * Math.sin( quOverP ) * 0.5;
  26984. }
  26985. }
  26986. copy( source ) {
  26987. super.copy( source );
  26988. this.parameters = Object.assign( {}, source.parameters );
  26989. return this;
  26990. }
  26991. /**
  26992. * Factory method for creating an instance of this class from the given
  26993. * JSON object.
  26994. *
  26995. * @param {Object} data - A JSON object representing the serialized geometry.
  26996. * @return {TorusKnotGeometry} A new instance.
  26997. */
  26998. static fromJSON( data ) {
  26999. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27000. }
  27001. }
  27002. /**
  27003. * Creates a tube that extrudes along a 3D curve.
  27004. *
  27005. * ```js
  27006. * class CustomSinCurve extends THREE.Curve {
  27007. *
  27008. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27009. *
  27010. * const tx = t * 3 - 1.5;
  27011. * const ty = Math.sin( 2 * Math.PI * t );
  27012. * const tz = 0;
  27013. *
  27014. * return optionalTarget.set( tx, ty, tz );
  27015. * }
  27016. *
  27017. * }
  27018. *
  27019. * const path = new CustomSinCurve( 10 );
  27020. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27021. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27022. * const mesh = new THREE.Mesh( geometry, material );
  27023. * scene.add( mesh );
  27024. * ```
  27025. *
  27026. * @augments BufferGeometry
  27027. * @demo scenes/geometry-browser.html#TubeGeometry
  27028. */
  27029. class TubeGeometry extends BufferGeometry {
  27030. /**
  27031. * Constructs a new tube geometry.
  27032. *
  27033. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27034. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27035. * @param {number} [radius=1] -The radius of the tube.
  27036. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27037. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27038. */
  27039. 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 ) {
  27040. super();
  27041. this.type = 'TubeGeometry';
  27042. /**
  27043. * Holds the constructor parameters that have been
  27044. * used to generate the geometry. Any modification
  27045. * after instantiation does not change the geometry.
  27046. *
  27047. * @type {Object}
  27048. */
  27049. this.parameters = {
  27050. path: path,
  27051. tubularSegments: tubularSegments,
  27052. radius: radius,
  27053. radialSegments: radialSegments,
  27054. closed: closed
  27055. };
  27056. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27057. // expose internals
  27058. this.tangents = frames.tangents;
  27059. this.normals = frames.normals;
  27060. this.binormals = frames.binormals;
  27061. // helper variables
  27062. const vertex = new Vector3();
  27063. const normal = new Vector3();
  27064. const uv = new Vector2();
  27065. let P = new Vector3();
  27066. // buffer
  27067. const vertices = [];
  27068. const normals = [];
  27069. const uvs = [];
  27070. const indices = [];
  27071. // create buffer data
  27072. generateBufferData();
  27073. // build geometry
  27074. this.setIndex( indices );
  27075. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27076. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27077. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27078. // functions
  27079. function generateBufferData() {
  27080. for ( let i = 0; i < tubularSegments; i ++ ) {
  27081. generateSegment( i );
  27082. }
  27083. // if the geometry is not closed, generate the last row of vertices and normals
  27084. // at the regular position on the given path
  27085. //
  27086. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27087. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27088. // uvs are generated in a separate function.
  27089. // this makes it easy compute correct values for closed geometries
  27090. generateUVs();
  27091. // finally create faces
  27092. generateIndices();
  27093. }
  27094. function generateSegment( i ) {
  27095. // we use getPointAt to sample evenly distributed points from the given path
  27096. P = path.getPointAt( i / tubularSegments, P );
  27097. // retrieve corresponding normal and binormal
  27098. const N = frames.normals[ i ];
  27099. const B = frames.binormals[ i ];
  27100. // generate normals and vertices for the current segment
  27101. for ( let j = 0; j <= radialSegments; j ++ ) {
  27102. const v = j / radialSegments * Math.PI * 2;
  27103. const sin = Math.sin( v );
  27104. const cos = - Math.cos( v );
  27105. // normal
  27106. normal.x = ( cos * N.x + sin * B.x );
  27107. normal.y = ( cos * N.y + sin * B.y );
  27108. normal.z = ( cos * N.z + sin * B.z );
  27109. normal.normalize();
  27110. normals.push( normal.x, normal.y, normal.z );
  27111. // vertex
  27112. vertex.x = P.x + radius * normal.x;
  27113. vertex.y = P.y + radius * normal.y;
  27114. vertex.z = P.z + radius * normal.z;
  27115. vertices.push( vertex.x, vertex.y, vertex.z );
  27116. }
  27117. }
  27118. function generateIndices() {
  27119. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27120. for ( let i = 1; i <= radialSegments; i ++ ) {
  27121. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27122. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27123. const c = ( radialSegments + 1 ) * j + i;
  27124. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27125. // faces
  27126. indices.push( a, b, d );
  27127. indices.push( b, c, d );
  27128. }
  27129. }
  27130. }
  27131. function generateUVs() {
  27132. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27133. for ( let j = 0; j <= radialSegments; j ++ ) {
  27134. uv.x = i / tubularSegments;
  27135. uv.y = j / radialSegments;
  27136. uvs.push( uv.x, uv.y );
  27137. }
  27138. }
  27139. }
  27140. }
  27141. copy( source ) {
  27142. super.copy( source );
  27143. this.parameters = Object.assign( {}, source.parameters );
  27144. return this;
  27145. }
  27146. toJSON() {
  27147. const data = super.toJSON();
  27148. data.path = this.parameters.path.toJSON();
  27149. return data;
  27150. }
  27151. /**
  27152. * Factory method for creating an instance of this class from the given
  27153. * JSON object.
  27154. *
  27155. * @param {Object} data - A JSON object representing the serialized geometry.
  27156. * @return {TubeGeometry} A new instance.
  27157. */
  27158. static fromJSON( data ) {
  27159. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27160. // User defined curves or instances of CurvePath will not be deserialized.
  27161. return new TubeGeometry(
  27162. new Curves[ data.path.type ]().fromJSON( data.path ),
  27163. data.tubularSegments,
  27164. data.radius,
  27165. data.radialSegments,
  27166. data.closed
  27167. );
  27168. }
  27169. }
  27170. /**
  27171. * Can be used as a helper object to visualize a geometry as a wireframe.
  27172. *
  27173. * ```js
  27174. * const geometry = new THREE.SphereGeometry();
  27175. *
  27176. * const wireframe = new THREE.WireframeGeometry( geometry );
  27177. *
  27178. * const line = new THREE.LineSegments( wireframe );
  27179. * line.material.depthWrite = false;
  27180. * line.material.opacity = 0.25;
  27181. * line.material.transparent = true;
  27182. *
  27183. * scene.add( line );
  27184. * ```
  27185. *
  27186. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27187. *
  27188. * @augments BufferGeometry
  27189. */
  27190. class WireframeGeometry extends BufferGeometry {
  27191. /**
  27192. * Constructs a new wireframe geometry.
  27193. *
  27194. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27195. */
  27196. constructor( geometry = null ) {
  27197. super();
  27198. this.type = 'WireframeGeometry';
  27199. /**
  27200. * Holds the constructor parameters that have been
  27201. * used to generate the geometry. Any modification
  27202. * after instantiation does not change the geometry.
  27203. *
  27204. * @type {Object}
  27205. */
  27206. this.parameters = {
  27207. geometry: geometry
  27208. };
  27209. if ( geometry !== null ) {
  27210. // buffer
  27211. const vertices = [];
  27212. const edges = new Set();
  27213. // helper variables
  27214. const start = new Vector3();
  27215. const end = new Vector3();
  27216. if ( geometry.index !== null ) {
  27217. // indexed BufferGeometry
  27218. const position = geometry.attributes.position;
  27219. const indices = geometry.index;
  27220. let groups = geometry.groups;
  27221. if ( groups.length === 0 ) {
  27222. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27223. }
  27224. // create a data structure that contains all edges without duplicates
  27225. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27226. const group = groups[ o ];
  27227. const groupStart = group.start;
  27228. const groupCount = group.count;
  27229. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27230. for ( let j = 0; j < 3; j ++ ) {
  27231. const index1 = indices.getX( i + j );
  27232. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27233. start.fromBufferAttribute( position, index1 );
  27234. end.fromBufferAttribute( position, index2 );
  27235. if ( isUniqueEdge( start, end, edges ) === true ) {
  27236. vertices.push( start.x, start.y, start.z );
  27237. vertices.push( end.x, end.y, end.z );
  27238. }
  27239. }
  27240. }
  27241. }
  27242. } else {
  27243. // non-indexed BufferGeometry
  27244. const position = geometry.attributes.position;
  27245. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27246. for ( let j = 0; j < 3; j ++ ) {
  27247. // three edges per triangle, an edge is represented as (index1, index2)
  27248. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27249. const index1 = 3 * i + j;
  27250. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27251. start.fromBufferAttribute( position, index1 );
  27252. end.fromBufferAttribute( position, index2 );
  27253. if ( isUniqueEdge( start, end, edges ) === true ) {
  27254. vertices.push( start.x, start.y, start.z );
  27255. vertices.push( end.x, end.y, end.z );
  27256. }
  27257. }
  27258. }
  27259. }
  27260. // build geometry
  27261. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27262. }
  27263. }
  27264. copy( source ) {
  27265. super.copy( source );
  27266. this.parameters = Object.assign( {}, source.parameters );
  27267. return this;
  27268. }
  27269. }
  27270. function isUniqueEdge( start, end, edges ) {
  27271. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27272. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27273. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27274. return false;
  27275. } else {
  27276. edges.add( hash1 );
  27277. edges.add( hash2 );
  27278. return true;
  27279. }
  27280. }
  27281. var Geometries = /*#__PURE__*/Object.freeze({
  27282. __proto__: null,
  27283. BoxGeometry: BoxGeometry,
  27284. CapsuleGeometry: CapsuleGeometry,
  27285. CircleGeometry: CircleGeometry,
  27286. ConeGeometry: ConeGeometry,
  27287. CylinderGeometry: CylinderGeometry,
  27288. DodecahedronGeometry: DodecahedronGeometry,
  27289. EdgesGeometry: EdgesGeometry,
  27290. ExtrudeGeometry: ExtrudeGeometry,
  27291. IcosahedronGeometry: IcosahedronGeometry,
  27292. LatheGeometry: LatheGeometry,
  27293. OctahedronGeometry: OctahedronGeometry,
  27294. PlaneGeometry: PlaneGeometry,
  27295. PolyhedronGeometry: PolyhedronGeometry,
  27296. RingGeometry: RingGeometry,
  27297. ShapeGeometry: ShapeGeometry,
  27298. SphereGeometry: SphereGeometry,
  27299. TetrahedronGeometry: TetrahedronGeometry,
  27300. TorusGeometry: TorusGeometry,
  27301. TorusKnotGeometry: TorusKnotGeometry,
  27302. TubeGeometry: TubeGeometry,
  27303. WireframeGeometry: WireframeGeometry
  27304. });
  27305. /**
  27306. * This material can receive shadows, but otherwise is completely transparent.
  27307. *
  27308. * ```js
  27309. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27310. * geometry.rotateX( - Math.PI / 2 );
  27311. *
  27312. * const material = new THREE.ShadowMaterial();
  27313. * material.opacity = 0.2;
  27314. *
  27315. * const plane = new THREE.Mesh( geometry, material );
  27316. * plane.position.y = -200;
  27317. * plane.receiveShadow = true;
  27318. * scene.add( plane );
  27319. * ```
  27320. *
  27321. * @augments Material
  27322. */
  27323. class ShadowMaterial extends Material {
  27324. /**
  27325. * Constructs a new shadow material.
  27326. *
  27327. * @param {Object} [parameters] - An object with one or more properties
  27328. * defining the material's appearance. Any property of the material
  27329. * (including any property from inherited materials) can be passed
  27330. * in here. Color values can be passed any type of value accepted
  27331. * by {@link Color#set}.
  27332. */
  27333. constructor( parameters ) {
  27334. super();
  27335. /**
  27336. * This flag can be used for type testing.
  27337. *
  27338. * @type {boolean}
  27339. * @readonly
  27340. * @default true
  27341. */
  27342. this.isShadowMaterial = true;
  27343. this.type = 'ShadowMaterial';
  27344. /**
  27345. * Color of the material.
  27346. *
  27347. * @type {Color}
  27348. * @default (0,0,0)
  27349. */
  27350. this.color = new Color( 0x000000 );
  27351. /**
  27352. * Overwritten since shadow materials are transparent
  27353. * by default.
  27354. *
  27355. * @type {boolean}
  27356. * @default true
  27357. */
  27358. this.transparent = true;
  27359. /**
  27360. * Whether the material is affected by fog or not.
  27361. *
  27362. * @type {boolean}
  27363. * @default true
  27364. */
  27365. this.fog = true;
  27366. this.setValues( parameters );
  27367. }
  27368. copy( source ) {
  27369. super.copy( source );
  27370. this.color.copy( source.color );
  27371. this.fog = source.fog;
  27372. return this;
  27373. }
  27374. }
  27375. /**
  27376. * Provides utility functions for managing uniforms.
  27377. *
  27378. * @module UniformsUtils
  27379. */
  27380. /**
  27381. * Clones the given uniform definitions by performing a deep-copy. That means
  27382. * if the value of a uniform refers to an object like a Vector3 or Texture,
  27383. * the cloned uniform will refer to a new object reference.
  27384. *
  27385. * @param {Object} src - An object representing uniform definitions.
  27386. * @return {Object} The cloned uniforms.
  27387. */
  27388. function cloneUniforms( src ) {
  27389. const dst = {};
  27390. for ( const u in src ) {
  27391. dst[ u ] = {};
  27392. for ( const p in src[ u ] ) {
  27393. const property = src[ u ][ p ];
  27394. if ( isThreeObject( property ) ) {
  27395. if ( property.isRenderTargetTexture ) {
  27396. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  27397. dst[ u ][ p ] = null;
  27398. } else {
  27399. dst[ u ][ p ] = property.clone();
  27400. }
  27401. } else if ( Array.isArray( property ) ) {
  27402. if ( isThreeObject( property[ 0 ] ) ) {
  27403. const clonedProperty = [];
  27404. for ( let i = 0, l = property.length; i < l; i ++ ) {
  27405. clonedProperty[ i ] = property[ i ].clone();
  27406. }
  27407. dst[ u ][ p ] = clonedProperty;
  27408. } else {
  27409. dst[ u ][ p ] = property.slice();
  27410. }
  27411. } else {
  27412. dst[ u ][ p ] = property;
  27413. }
  27414. }
  27415. }
  27416. return dst;
  27417. }
  27418. /**
  27419. * Merges the given uniform definitions into a single object. Since the
  27420. * method internally uses cloneUniforms(), it performs a deep-copy when
  27421. * producing the merged uniform definitions.
  27422. *
  27423. * @param {Array} uniforms - An array of objects containing uniform definitions.
  27424. * @return {Object} The merged uniforms.
  27425. */
  27426. function mergeUniforms( uniforms ) {
  27427. const merged = {};
  27428. for ( let u = 0; u < uniforms.length; u ++ ) {
  27429. const tmp = cloneUniforms( uniforms[ u ] );
  27430. for ( const p in tmp ) {
  27431. merged[ p ] = tmp[ p ];
  27432. }
  27433. }
  27434. return merged;
  27435. }
  27436. function isThreeObject( property ) {
  27437. return ( property && ( property.isColor ||
  27438. property.isMatrix3 || property.isMatrix4 ||
  27439. property.isVector2 || property.isVector3 || property.isVector4 ||
  27440. property.isTexture || property.isQuaternion ) );
  27441. }
  27442. function cloneUniformsGroups( src ) {
  27443. const dst = [];
  27444. for ( let u = 0; u < src.length; u ++ ) {
  27445. dst.push( src[ u ].clone() );
  27446. }
  27447. return dst;
  27448. }
  27449. function getUnlitUniformColorSpace( renderer ) {
  27450. const currentRenderTarget = renderer.getRenderTarget();
  27451. if ( currentRenderTarget === null ) {
  27452. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  27453. return renderer.outputColorSpace;
  27454. }
  27455. // https://github.com/mrdoob/three.js/issues/27868
  27456. if ( currentRenderTarget.isXRRenderTarget === true ) {
  27457. return currentRenderTarget.texture.colorSpace;
  27458. }
  27459. return ColorManagement.workingColorSpace;
  27460. }
  27461. // Legacy
  27462. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  27463. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  27464. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  27465. /**
  27466. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  27467. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  27468. * effect not included with any of the built-in materials.
  27469. *
  27470. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  27471. *
  27472. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  27473. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  27474. * you don't want that, use {@link RawShaderMaterial} instead.
  27475. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  27476. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  27477. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  27478. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  27479. * - The loop variable has to be *i*.
  27480. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  27481. * value of *i* for the given iteration and can be used in preprocessor
  27482. * statements.
  27483. *
  27484. * ```js
  27485. * const material = new THREE.ShaderMaterial( {
  27486. * uniforms: {
  27487. * time: { value: 1.0 },
  27488. * resolution: { value: new THREE.Vector2() }
  27489. * },
  27490. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  27491. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  27492. * } );
  27493. * ```
  27494. *
  27495. * @augments Material
  27496. */
  27497. class ShaderMaterial extends Material {
  27498. /**
  27499. * Constructs a new shader material.
  27500. *
  27501. * @param {Object} [parameters] - An object with one or more properties
  27502. * defining the material's appearance. Any property of the material
  27503. * (including any property from inherited materials) can be passed
  27504. * in here. Color values can be passed any type of value accepted
  27505. * by {@link Color#set}.
  27506. */
  27507. constructor( parameters ) {
  27508. super();
  27509. /**
  27510. * This flag can be used for type testing.
  27511. *
  27512. * @type {boolean}
  27513. * @readonly
  27514. * @default true
  27515. */
  27516. this.isShaderMaterial = true;
  27517. this.type = 'ShaderMaterial';
  27518. /**
  27519. * Defines custom constants using `#define` directives within the GLSL code
  27520. * for both the vertex shader and the fragment shader; each key/value pair
  27521. * yields another directive.
  27522. * ```js
  27523. * defines: {
  27524. * FOO: 15,
  27525. * BAR: true
  27526. * }
  27527. * ```
  27528. * Yields the lines:
  27529. * ```
  27530. * #define FOO 15
  27531. * #define BAR true
  27532. * ```
  27533. *
  27534. * @type {Object}
  27535. */
  27536. this.defines = {};
  27537. /**
  27538. * An object of the form:
  27539. * ```js
  27540. * {
  27541. * "uniform1": { value: 1.0 },
  27542. * "uniform2": { value: 2 }
  27543. * }
  27544. * ```
  27545. * specifying the uniforms to be passed to the shader code; keys are uniform
  27546. * names, values are definitions of the form
  27547. * ```
  27548. * {
  27549. * value: 1.0
  27550. * }
  27551. * ```
  27552. * where `value` is the value of the uniform. Names must match the name of
  27553. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  27554. * on every frame, so updating the value of the uniform will immediately
  27555. * update the value available to the GLSL code.
  27556. *
  27557. * @type {Object}
  27558. */
  27559. this.uniforms = {};
  27560. /**
  27561. * An array holding uniforms groups for configuring UBOs.
  27562. *
  27563. * @type {Array<UniformsGroup>}
  27564. */
  27565. this.uniformsGroups = [];
  27566. /**
  27567. * Vertex shader GLSL code. This is the actual code for the shader.
  27568. *
  27569. * @type {string}
  27570. */
  27571. this.vertexShader = default_vertex;
  27572. /**
  27573. * Fragment shader GLSL code. This is the actual code for the shader.
  27574. *
  27575. * @type {string}
  27576. */
  27577. this.fragmentShader = default_fragment;
  27578. /**
  27579. * Controls line thickness or lines.
  27580. *
  27581. * WebGL and WebGPU ignore this setting and always render line primitives with a
  27582. * width of one pixel.
  27583. *
  27584. * @type {number}
  27585. * @default 1
  27586. */
  27587. this.linewidth = 1;
  27588. /**
  27589. * Renders the geometry as a wireframe.
  27590. *
  27591. * @type {boolean}
  27592. * @default false
  27593. */
  27594. this.wireframe = false;
  27595. /**
  27596. * Controls the thickness of the wireframe.
  27597. *
  27598. * WebGL and WebGPU ignore this property and always render
  27599. * 1 pixel wide lines.
  27600. *
  27601. * @type {number}
  27602. * @default 1
  27603. */
  27604. this.wireframeLinewidth = 1;
  27605. /**
  27606. * Defines whether the material color is affected by global fog settings; `true`
  27607. * to pass fog uniforms to the shader.
  27608. *
  27609. * Setting this property to `true` requires the definition of fog uniforms. It is
  27610. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  27611. * with predefined fog uniforms.
  27612. *
  27613. * ```js
  27614. * const material = new ShaderMaterial( {
  27615. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  27616. * vertexShader: vertexShader,
  27617. * fragmentShader: fragmentShader,
  27618. * fog: true
  27619. * } );
  27620. * ```
  27621. *
  27622. * @type {boolean}
  27623. * @default false
  27624. */
  27625. this.fog = false;
  27626. /**
  27627. * Defines whether this material uses lighting; `true` to pass uniform data
  27628. * related to lighting to this shader.
  27629. *
  27630. * @type {boolean}
  27631. * @default false
  27632. */
  27633. this.lights = false;
  27634. /**
  27635. * Defines whether this material supports clipping; `true` to let the renderer
  27636. * pass the clippingPlanes uniform.
  27637. *
  27638. * @type {boolean}
  27639. * @default false
  27640. */
  27641. this.clipping = false;
  27642. /**
  27643. * Overwritten and set to `true` by default.
  27644. *
  27645. * @type {boolean}
  27646. * @default true
  27647. */
  27648. this.forceSinglePass = true;
  27649. /**
  27650. * This object allows to enable certain WebGL 2 extensions.
  27651. *
  27652. * - clipCullDistance: set to `true` to use vertex shader clipping
  27653. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  27654. *
  27655. * @type {{clipCullDistance:false,multiDraw:false}}
  27656. */
  27657. this.extensions = {
  27658. clipCullDistance: false, // set to use vertex shader clipping
  27659. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  27660. };
  27661. /**
  27662. * When the rendered geometry doesn't include these attributes but the
  27663. * material does, these default values will be passed to the shaders. This
  27664. * avoids errors when buffer data is missing.
  27665. *
  27666. * - color: [ 1, 1, 1 ]
  27667. * - uv: [ 0, 0 ]
  27668. * - uv1: [ 0, 0 ]
  27669. *
  27670. * @type {Object}
  27671. */
  27672. this.defaultAttributeValues = {
  27673. 'color': [ 1, 1, 1 ],
  27674. 'uv': [ 0, 0 ],
  27675. 'uv1': [ 0, 0 ]
  27676. };
  27677. /**
  27678. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  27679. * to bind a generic vertex index to an attribute variable.
  27680. *
  27681. * @type {string|undefined}
  27682. * @default undefined
  27683. */
  27684. this.index0AttributeName = undefined;
  27685. /**
  27686. * Can be used to force a uniform update while changing uniforms in
  27687. * {@link Object3D#onBeforeRender}.
  27688. *
  27689. * @type {boolean}
  27690. * @default false
  27691. */
  27692. this.uniformsNeedUpdate = false;
  27693. /**
  27694. * Defines the GLSL version of custom shader code.
  27695. *
  27696. * @type {?(GLSL1|GLSL3)}
  27697. * @default null
  27698. */
  27699. this.glslVersion = null;
  27700. if ( parameters !== undefined ) {
  27701. this.setValues( parameters );
  27702. }
  27703. }
  27704. copy( source ) {
  27705. super.copy( source );
  27706. this.fragmentShader = source.fragmentShader;
  27707. this.vertexShader = source.vertexShader;
  27708. this.uniforms = cloneUniforms( source.uniforms );
  27709. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  27710. this.defines = Object.assign( {}, source.defines );
  27711. this.wireframe = source.wireframe;
  27712. this.wireframeLinewidth = source.wireframeLinewidth;
  27713. this.fog = source.fog;
  27714. this.lights = source.lights;
  27715. this.clipping = source.clipping;
  27716. this.extensions = Object.assign( {}, source.extensions );
  27717. this.glslVersion = source.glslVersion;
  27718. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  27719. this.index0AttributeName = source.index0AttributeName;
  27720. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  27721. return this;
  27722. }
  27723. toJSON( meta ) {
  27724. const data = super.toJSON( meta );
  27725. data.glslVersion = this.glslVersion;
  27726. data.uniforms = {};
  27727. for ( const name in this.uniforms ) {
  27728. const uniform = this.uniforms[ name ];
  27729. const value = uniform.value;
  27730. if ( value && value.isTexture ) {
  27731. data.uniforms[ name ] = {
  27732. type: 't',
  27733. value: value.toJSON( meta ).uuid
  27734. };
  27735. } else if ( value && value.isColor ) {
  27736. data.uniforms[ name ] = {
  27737. type: 'c',
  27738. value: value.getHex()
  27739. };
  27740. } else if ( value && value.isVector2 ) {
  27741. data.uniforms[ name ] = {
  27742. type: 'v2',
  27743. value: value.toArray()
  27744. };
  27745. } else if ( value && value.isVector3 ) {
  27746. data.uniforms[ name ] = {
  27747. type: 'v3',
  27748. value: value.toArray()
  27749. };
  27750. } else if ( value && value.isVector4 ) {
  27751. data.uniforms[ name ] = {
  27752. type: 'v4',
  27753. value: value.toArray()
  27754. };
  27755. } else if ( value && value.isMatrix3 ) {
  27756. data.uniforms[ name ] = {
  27757. type: 'm3',
  27758. value: value.toArray()
  27759. };
  27760. } else if ( value && value.isMatrix4 ) {
  27761. data.uniforms[ name ] = {
  27762. type: 'm4',
  27763. value: value.toArray()
  27764. };
  27765. } else {
  27766. data.uniforms[ name ] = {
  27767. value: value
  27768. };
  27769. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  27770. }
  27771. }
  27772. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  27773. data.vertexShader = this.vertexShader;
  27774. data.fragmentShader = this.fragmentShader;
  27775. data.lights = this.lights;
  27776. data.clipping = this.clipping;
  27777. const extensions = {};
  27778. for ( const key in this.extensions ) {
  27779. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  27780. }
  27781. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  27782. return data;
  27783. }
  27784. /**
  27785. * Deserializes the material from the given JSON.
  27786. *
  27787. * @param {Object} json - The JSON holding the serialized material.
  27788. * @param {Object<string,Texture>} textures - A dictionary holding textures referenced by the material.
  27789. * @return {ShaderMaterial} A reference to this material.
  27790. */
  27791. fromJSON( json, textures ) {
  27792. super.fromJSON( json, textures );
  27793. if ( json.uniforms !== undefined ) {
  27794. for ( const name in json.uniforms ) {
  27795. const uniform = json.uniforms[ name ];
  27796. this.uniforms[ name ] = {};
  27797. switch ( uniform.type ) {
  27798. case 't':
  27799. this.uniforms[ name ].value = textures[ uniform.value ] || null;
  27800. break;
  27801. case 'c':
  27802. this.uniforms[ name ].value = new Color().setHex( uniform.value );
  27803. break;
  27804. case 'v2':
  27805. this.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  27806. break;
  27807. case 'v3':
  27808. this.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  27809. break;
  27810. case 'v4':
  27811. this.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  27812. break;
  27813. case 'm3':
  27814. this.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  27815. break;
  27816. case 'm4':
  27817. this.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  27818. break;
  27819. default:
  27820. this.uniforms[ name ].value = uniform.value;
  27821. }
  27822. }
  27823. }
  27824. if ( json.defines !== undefined ) this.defines = json.defines;
  27825. if ( json.vertexShader !== undefined ) this.vertexShader = json.vertexShader;
  27826. if ( json.fragmentShader !== undefined ) this.fragmentShader = json.fragmentShader;
  27827. if ( json.glslVersion !== undefined ) this.glslVersion = json.glslVersion;
  27828. if ( json.extensions !== undefined ) {
  27829. for ( const key in json.extensions ) {
  27830. this.extensions[ key ] = json.extensions[ key ];
  27831. }
  27832. }
  27833. if ( json.lights !== undefined ) this.lights = json.lights;
  27834. if ( json.clipping !== undefined ) this.clipping = json.clipping;
  27835. return this;
  27836. }
  27837. }
  27838. /**
  27839. * This class works just like {@link ShaderMaterial}, except that definitions
  27840. * of built-in uniforms and attributes are not automatically prepended to the
  27841. * GLSL shader code.
  27842. *
  27843. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27844. *
  27845. * @augments ShaderMaterial
  27846. */
  27847. class RawShaderMaterial extends ShaderMaterial {
  27848. /**
  27849. * Constructs a new raw shader material.
  27850. *
  27851. * @param {Object} [parameters] - An object with one or more properties
  27852. * defining the material's appearance. Any property of the material
  27853. * (including any property from inherited materials) can be passed
  27854. * in here. Color values can be passed any type of value accepted
  27855. * by {@link Color#set}.
  27856. */
  27857. constructor( parameters ) {
  27858. super( parameters );
  27859. /**
  27860. * This flag can be used for type testing.
  27861. *
  27862. * @type {boolean}
  27863. * @readonly
  27864. * @default true
  27865. */
  27866. this.isRawShaderMaterial = true;
  27867. this.type = 'RawShaderMaterial';
  27868. }
  27869. }
  27870. /**
  27871. * A standard physically based material, using Metallic-Roughness workflow.
  27872. *
  27873. * Physically based rendering (PBR) has recently become the standard in many
  27874. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27875. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27876. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27877. *
  27878. * This approach differs from older approaches in that instead of using
  27879. * approximations for the way in which light interacts with a surface, a
  27880. * physically correct model is used. The idea is that, instead of tweaking
  27881. * materials to look good under specific lighting, a material can be created
  27882. * that will react 'correctly' under all lighting scenarios.
  27883. *
  27884. * In practice this gives a more accurate and realistic looking result than
  27885. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27886. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27887. * shading.
  27888. *
  27889. * Note that for best results you should always specify an environment map when using this material.
  27890. *
  27891. * For a non-technical introduction to the concept of PBR and how to set up a
  27892. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27893. *
  27894. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27895. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27896. *
  27897. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27898. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27899. * (pdf), by Brent Burley.
  27900. *
  27901. * @augments Material
  27902. * @demo scenes/material-browser.html#MeshStandardMaterial
  27903. */
  27904. class MeshStandardMaterial extends Material {
  27905. /**
  27906. * Constructs a new mesh standard material.
  27907. *
  27908. * @param {Object} [parameters] - An object with one or more properties
  27909. * defining the material's appearance. Any property of the material
  27910. * (including any property from inherited materials) can be passed
  27911. * in here. Color values can be passed any type of value accepted
  27912. * by {@link Color#set}.
  27913. */
  27914. constructor( parameters ) {
  27915. super();
  27916. /**
  27917. * This flag can be used for type testing.
  27918. *
  27919. * @type {boolean}
  27920. * @readonly
  27921. * @default true
  27922. */
  27923. this.isMeshStandardMaterial = true;
  27924. this.type = 'MeshStandardMaterial';
  27925. this.defines = { 'STANDARD': '' };
  27926. /**
  27927. * Color of the material.
  27928. *
  27929. * @type {Color}
  27930. * @default (1,1,1)
  27931. */
  27932. this.color = new Color( 0xffffff ); // diffuse
  27933. /**
  27934. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27935. * means fully diffuse. If `roughnessMap` is also provided,
  27936. * both values are multiplied.
  27937. *
  27938. * @type {number}
  27939. * @default 1
  27940. */
  27941. this.roughness = 1.0;
  27942. /**
  27943. * How much the material is like a metal. Non-metallic materials such as wood
  27944. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27945. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27946. * If `metalnessMap` is also provided, both values are multiplied.
  27947. *
  27948. * @type {number}
  27949. * @default 0
  27950. */
  27951. this.metalness = 0.0;
  27952. /**
  27953. * The color map. May optionally include an alpha channel, typically combined
  27954. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27955. * color is modulated by the diffuse `color`.
  27956. *
  27957. * `map` represents color data, and the texture must be assigned a
  27958. * {@link Texture#colorSpace}. Most `map` textures set
  27959. * `texture.colorSpace = SRGBColorSpace`.
  27960. *
  27961. * @type {?Texture}
  27962. * @default null
  27963. */
  27964. this.map = null;
  27965. /**
  27966. * The light map. Requires a second set of UVs.
  27967. *
  27968. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  27969. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  27970. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  27971. * such as `.exr` or `.hdr`.
  27972. *
  27973. * @type {?Texture}
  27974. * @default null
  27975. */
  27976. this.lightMap = null;
  27977. /**
  27978. * Intensity of the baked light.
  27979. *
  27980. * @type {number}
  27981. * @default 1
  27982. */
  27983. this.lightMapIntensity = 1.0;
  27984. /**
  27985. * The red channel of this texture is used as the ambient occlusion map.
  27986. * Requires a second set of UVs.
  27987. *
  27988. * `aoMap` represents non-color data. Any texture assigned must have
  27989. * `texture.colorSpace = NoColorSpace` (default).
  27990. *
  27991. * @type {?Texture}
  27992. * @default null
  27993. */
  27994. this.aoMap = null;
  27995. /**
  27996. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27997. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27998. * red channel is also `1`, ambient light is fully occluded on a surface.
  27999. *
  28000. * @type {number}
  28001. * @default 1
  28002. */
  28003. this.aoMapIntensity = 1.0;
  28004. /**
  28005. * Emissive (light) color of the material, essentially a solid color
  28006. * unaffected by other lighting.
  28007. *
  28008. * @type {Color}
  28009. * @default (0,0,0)
  28010. */
  28011. this.emissive = new Color( 0x000000 );
  28012. /**
  28013. * Intensity of the emissive light. Modulates the emissive color.
  28014. *
  28015. * @type {number}
  28016. * @default 1
  28017. */
  28018. this.emissiveIntensity = 1.0;
  28019. /**
  28020. * Set emissive (glow) map. The emissive map color is modulated by the
  28021. * emissive color and the emissive intensity. If you have an emissive map,
  28022. * be sure to set the emissive color to something other than black.
  28023. *
  28024. * `emissiveMap` represents color data, and the texture must be assigned a
  28025. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  28026. * `texture.colorSpace = SRGBColorSpace`.
  28027. *
  28028. * @type {?Texture}
  28029. * @default null
  28030. */
  28031. this.emissiveMap = null;
  28032. /**
  28033. * The texture to create a bump map. The black and white values map to the
  28034. * perceived depth in relation to the lights. Bump doesn't actually affect
  28035. * the geometry of the object, only the lighting. If a normal map is defined
  28036. * this will be ignored.
  28037. *
  28038. * `bumpMap` represents non-color data. Any texture assigned must have
  28039. * `texture.colorSpace = NoColorSpace` (default).
  28040. *
  28041. * @type {?Texture}
  28042. * @default null
  28043. */
  28044. this.bumpMap = null;
  28045. /**
  28046. * How much the bump map affects the material. Typical range is `[0,1]`.
  28047. *
  28048. * @type {number}
  28049. * @default 1
  28050. */
  28051. this.bumpScale = 1;
  28052. /**
  28053. * The texture to create a normal map. The RGB values affect the surface
  28054. * normal for each pixel fragment and change the way the color is lit. Normal
  28055. * maps do not change the actual shape of the surface, only the lighting. In
  28056. * case the material has a normal map authored using the left handed
  28057. * convention, the `y` component of `normalScale` should be negated to compensate
  28058. * for the different handedness.
  28059. *
  28060. * `normalMap` represents non-color data. Any texture assigned must have
  28061. * `texture.colorSpace = NoColorSpace` (default).
  28062. *
  28063. * @type {?Texture}
  28064. * @default null
  28065. */
  28066. this.normalMap = null;
  28067. /**
  28068. * The type of normal map.
  28069. *
  28070. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28071. * @default TangentSpaceNormalMap
  28072. */
  28073. this.normalMapType = TangentSpaceNormalMap;
  28074. /**
  28075. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28076. *
  28077. * @type {Vector2}
  28078. * @default (1,1)
  28079. */
  28080. this.normalScale = new Vector2( 1, 1 );
  28081. /**
  28082. * The displacement map affects the position of the mesh's vertices. Unlike
  28083. * other maps which only affect the light and shade of the material the
  28084. * displaced vertices can cast shadows, block other objects, and otherwise
  28085. * act as real geometry. The displacement texture is an image where the value
  28086. * of each pixel (white being the highest) is mapped against, and
  28087. * repositions, the vertices of the mesh. For best results, pair a
  28088. * displacement map with a matching normal map, since the renderer can
  28089. * not recompute surface normals from the displaced vertices.
  28090. *
  28091. * `displacementMap` represents non-color data. Any texture assigned must have
  28092. * `texture.colorSpace = NoColorSpace` (default).
  28093. *
  28094. * @type {?Texture}
  28095. * @default null
  28096. */
  28097. this.displacementMap = null;
  28098. /**
  28099. * How much the displacement map affects the mesh (where black is no
  28100. * displacement, and white is maximum displacement). Without a displacement
  28101. * map set, this value is not applied.
  28102. *
  28103. * @type {number}
  28104. * @default 0
  28105. */
  28106. this.displacementScale = 1;
  28107. /**
  28108. * The offset of the displacement map's values on the mesh's vertices.
  28109. * The bias is added to the scaled sample of the displacement map.
  28110. * Without a displacement map set, this value is not applied.
  28111. *
  28112. * @type {number}
  28113. * @default 0
  28114. */
  28115. this.displacementBias = 0;
  28116. /**
  28117. * The green channel of this texture is used to alter the roughness of the
  28118. * material.
  28119. *
  28120. * `roughnessMap` represents non-color data. Any texture assigned must have
  28121. * `texture.colorSpace = NoColorSpace` (default).
  28122. *
  28123. * @type {?Texture}
  28124. * @default null
  28125. */
  28126. this.roughnessMap = null;
  28127. /**
  28128. * The blue channel of this texture is used to alter the metalness of the
  28129. * material.
  28130. *
  28131. * `metalnessMap` represents non-color data. Any texture assigned must have
  28132. * `texture.colorSpace = NoColorSpace` (default).
  28133. *
  28134. * @type {?Texture}
  28135. * @default null
  28136. */
  28137. this.metalnessMap = null;
  28138. /**
  28139. * The alpha map is a grayscale texture that controls the opacity across the
  28140. * surface (black: fully transparent; white: fully opaque).
  28141. *
  28142. * Only the color of the texture is used, ignoring the alpha channel if one
  28143. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28144. * when sampling this texture due to the extra bit of precision provided for
  28145. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28146. * luminance/alpha textures will also still work as expected.
  28147. *
  28148. * `alphaMap` represents non-color data. Any texture assigned must have
  28149. * `texture.colorSpace = NoColorSpace` (default).
  28150. *
  28151. * @type {?Texture}
  28152. * @default null
  28153. */
  28154. this.alphaMap = null;
  28155. /**
  28156. * The environment map. To ensure a physically correct rendering, environment maps
  28157. * are internally pre-processed with {@link PMREMGenerator}.
  28158. *
  28159. * `envMap` represents luminance data, and the texture must be assigned
  28160. * a {@link Texture#colorSpace}. Most `envMap` textures set
  28161. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  28162. * such as `.exr` or `.hdr`.
  28163. *
  28164. * @type {?Texture}
  28165. * @default null
  28166. */
  28167. this.envMap = null;
  28168. /**
  28169. * The rotation of the environment map in radians.
  28170. *
  28171. * @type {Euler}
  28172. * @default (0,0,0)
  28173. */
  28174. this.envMapRotation = new Euler();
  28175. /**
  28176. * Scales the effect of the environment map by multiplying its color.
  28177. *
  28178. * @type {number}
  28179. * @default 1
  28180. */
  28181. this.envMapIntensity = 1.0;
  28182. /**
  28183. * Renders the geometry as a wireframe.
  28184. *
  28185. * @type {boolean}
  28186. * @default false
  28187. */
  28188. this.wireframe = false;
  28189. /**
  28190. * Controls the thickness of the wireframe.
  28191. *
  28192. * Can only be used with {@link SVGRenderer}.
  28193. *
  28194. * @type {number}
  28195. * @default 1
  28196. */
  28197. this.wireframeLinewidth = 1;
  28198. /**
  28199. * Defines appearance of wireframe ends.
  28200. *
  28201. * Can only be used with {@link SVGRenderer}.
  28202. *
  28203. * @type {('round'|'bevel'|'miter')}
  28204. * @default 'round'
  28205. */
  28206. this.wireframeLinecap = 'round';
  28207. /**
  28208. * Defines appearance of wireframe joints.
  28209. *
  28210. * Can only be used with {@link SVGRenderer}.
  28211. *
  28212. * @type {('round'|'bevel'|'miter')}
  28213. * @default 'round'
  28214. */
  28215. this.wireframeLinejoin = 'round';
  28216. /**
  28217. * Whether the material is rendered with flat shading or not.
  28218. *
  28219. * @type {boolean}
  28220. * @default false
  28221. */
  28222. this.flatShading = false;
  28223. /**
  28224. * Whether the material is affected by fog or not.
  28225. *
  28226. * @type {boolean}
  28227. * @default true
  28228. */
  28229. this.fog = true;
  28230. this.setValues( parameters );
  28231. }
  28232. copy( source ) {
  28233. super.copy( source );
  28234. this.defines = { 'STANDARD': '' };
  28235. this.color.copy( source.color );
  28236. this.roughness = source.roughness;
  28237. this.metalness = source.metalness;
  28238. this.map = source.map;
  28239. this.lightMap = source.lightMap;
  28240. this.lightMapIntensity = source.lightMapIntensity;
  28241. this.aoMap = source.aoMap;
  28242. this.aoMapIntensity = source.aoMapIntensity;
  28243. this.emissive.copy( source.emissive );
  28244. this.emissiveMap = source.emissiveMap;
  28245. this.emissiveIntensity = source.emissiveIntensity;
  28246. this.bumpMap = source.bumpMap;
  28247. this.bumpScale = source.bumpScale;
  28248. this.normalMap = source.normalMap;
  28249. this.normalMapType = source.normalMapType;
  28250. this.normalScale.copy( source.normalScale );
  28251. this.displacementMap = source.displacementMap;
  28252. this.displacementScale = source.displacementScale;
  28253. this.displacementBias = source.displacementBias;
  28254. this.roughnessMap = source.roughnessMap;
  28255. this.metalnessMap = source.metalnessMap;
  28256. this.alphaMap = source.alphaMap;
  28257. this.envMap = source.envMap;
  28258. this.envMapRotation.copy( source.envMapRotation );
  28259. this.envMapIntensity = source.envMapIntensity;
  28260. this.wireframe = source.wireframe;
  28261. this.wireframeLinewidth = source.wireframeLinewidth;
  28262. this.wireframeLinecap = source.wireframeLinecap;
  28263. this.wireframeLinejoin = source.wireframeLinejoin;
  28264. this.flatShading = source.flatShading;
  28265. this.fog = source.fog;
  28266. return this;
  28267. }
  28268. }
  28269. /**
  28270. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28271. * physically-based rendering properties:
  28272. *
  28273. * - Anisotropy: Ability to represent the anisotropic property of materials
  28274. * as observable with brushed metals.
  28275. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28276. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28277. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28278. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28279. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28280. * wings of many insects.
  28281. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28282. * transparent materials are less reflective. Physically-based transmission provides a more
  28283. * realistic option for thin, transparent surfaces like glass.
  28284. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28285. * - Sheen: Can be used for representing cloth and fabric materials.
  28286. *
  28287. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28288. * higher performance cost, per pixel, than other three.js materials. Most
  28289. * effects are disabled by default, and add cost as they are enabled. For
  28290. * best results, always specify an environment map when using this material.
  28291. *
  28292. * @augments MeshStandardMaterial
  28293. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28294. */
  28295. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28296. /**
  28297. * Constructs a new mesh physical material.
  28298. *
  28299. * @param {Object} [parameters] - An object with one or more properties
  28300. * defining the material's appearance. Any property of the material
  28301. * (including any property from inherited materials) can be passed
  28302. * in here. Color values can be passed any type of value accepted
  28303. * by {@link Color#set}.
  28304. */
  28305. constructor( parameters ) {
  28306. super();
  28307. /**
  28308. * This flag can be used for type testing.
  28309. *
  28310. * @type {boolean}
  28311. * @readonly
  28312. * @default true
  28313. */
  28314. this.isMeshPhysicalMaterial = true;
  28315. this.defines = {
  28316. 'STANDARD': '',
  28317. 'PHYSICAL': ''
  28318. };
  28319. this.type = 'MeshPhysicalMaterial';
  28320. /**
  28321. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28322. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28323. * property provides additional rotation to the vectors in the texture.
  28324. *
  28325. * @type {number}
  28326. * @default 1
  28327. */
  28328. this.anisotropyRotation = 0;
  28329. /**
  28330. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28331. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28332. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28333. *
  28334. * `anisotropyMap` represents non-color data. Any texture assigned must have
  28335. * `texture.colorSpace = NoColorSpace` (default).
  28336. *
  28337. * @type {?Texture}
  28338. * @default null
  28339. */
  28340. this.anisotropyMap = null;
  28341. /**
  28342. * The red channel of this texture is multiplied against `clearcoat`,
  28343. * for per-pixel control over a coating's intensity.
  28344. *
  28345. * `clearcoatMap` represents non-color data. Any texture assigned must have
  28346. * `texture.colorSpace = NoColorSpace` (default).
  28347. *
  28348. * @type {?Texture}
  28349. * @default null
  28350. */
  28351. this.clearcoatMap = null;
  28352. /**
  28353. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28354. *
  28355. * @type {number}
  28356. * @default 0
  28357. */
  28358. this.clearcoatRoughness = 0.0;
  28359. /**
  28360. * The green channel of this texture is multiplied against
  28361. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28362. *
  28363. * `clearcoatRoughnessMap` represents non-color data. Any texture assigned must have
  28364. * `texture.colorSpace = NoColorSpace` (default).
  28365. *
  28366. * @type {?Texture}
  28367. * @default null
  28368. */
  28369. this.clearcoatRoughnessMap = null;
  28370. /**
  28371. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28372. * `(0,0)` to `(1,1)`.
  28373. *
  28374. * @type {Vector2}
  28375. * @default (1,1)
  28376. */
  28377. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28378. /**
  28379. * Can be used to enable independent normals for the clear coat layer.
  28380. *
  28381. * `clearcoatNormalMap` represents non-color data. Any texture assigned must have
  28382. * `texture.colorSpace = NoColorSpace` (default).
  28383. *
  28384. * @type {?Texture}
  28385. * @default null
  28386. */
  28387. this.clearcoatNormalMap = null;
  28388. /**
  28389. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28390. *
  28391. * @type {number}
  28392. * @default 1.5
  28393. */
  28394. this.ior = 1.5;
  28395. /**
  28396. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28397. * corresponds to an index-of-refraction of `1.5`.
  28398. *
  28399. * This models the reflectivity of non-metallic materials. It has no effect
  28400. * when `metalness` is `1.0`
  28401. *
  28402. * @name MeshPhysicalMaterial#reflectivity
  28403. * @type {number}
  28404. * @default 0.5
  28405. */
  28406. Object.defineProperty( this, 'reflectivity', {
  28407. get: function () {
  28408. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28409. },
  28410. set: function ( reflectivity ) {
  28411. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28412. }
  28413. } );
  28414. /**
  28415. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28416. * control over iridescence.
  28417. *
  28418. * `iridescenceMap` represents non-color data. Any texture assigned must have
  28419. * `texture.colorSpace = NoColorSpace` (default).
  28420. *
  28421. * @type {?Texture}
  28422. * @default null
  28423. */
  28424. this.iridescenceMap = null;
  28425. /**
  28426. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28427. * Between `1.0` to `2.333`.
  28428. *
  28429. * @type {number}
  28430. * @default 1.3
  28431. */
  28432. this.iridescenceIOR = 1.3;
  28433. /**
  28434. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28435. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28436. *
  28437. * @type {Array<number,number>}
  28438. * @default [100,400]
  28439. */
  28440. this.iridescenceThicknessRange = [ 100, 400 ];
  28441. /**
  28442. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28443. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28444. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28445. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28446. * - Values in-between will linearly interpolate between the elements of the array.
  28447. *
  28448. * `iridescenceThicknessMap` represents non-color data. Any texture assigned must have
  28449. * `texture.colorSpace = NoColorSpace` (default).
  28450. *
  28451. * @type {?Texture}
  28452. * @default null
  28453. */
  28454. this.iridescenceThicknessMap = null;
  28455. /**
  28456. * The sheen tint.
  28457. *
  28458. * @type {Color}
  28459. * @default (0,0,0)
  28460. */
  28461. this.sheenColor = new Color( 0x000000 );
  28462. /**
  28463. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28464. * over sheen tint.
  28465. *
  28466. * `sheenColorMap` represents color data, and the texture must be assigned a
  28467. * {@link Texture#colorSpace}. Most `sheenColorMap` textures set
  28468. * `texture.colorSpace = SRGBColorSpace`.
  28469. *
  28470. * @type {?Texture}
  28471. * @default null
  28472. */
  28473. this.sheenColorMap = null;
  28474. /**
  28475. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28476. *
  28477. * @type {number}
  28478. * @default 1
  28479. */
  28480. this.sheenRoughness = 1.0;
  28481. /**
  28482. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28483. * over sheen roughness.
  28484. *
  28485. * `sheenRoughnessMap` represents non-color data. Any texture assigned must have
  28486. * `texture.colorSpace = NoColorSpace` (default).
  28487. *
  28488. * @type {?Texture}
  28489. * @default null
  28490. */
  28491. this.sheenRoughnessMap = null;
  28492. /**
  28493. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28494. * optical transparency.
  28495. *
  28496. * `transmissionMap` represents non-color data. Any texture assigned must have
  28497. * `texture.colorSpace = NoColorSpace` (default).
  28498. *
  28499. * @type {?Texture}
  28500. * @default null
  28501. */
  28502. this.transmissionMap = null;
  28503. /**
  28504. * The thickness of the volume beneath the surface. The value is given in the
  28505. * coordinate space of the mesh. If the value is `0` the material is
  28506. * thin-walled. Otherwise the material is a volume boundary.
  28507. *
  28508. * @type {number}
  28509. * @default 0
  28510. */
  28511. this.thickness = 0;
  28512. /**
  28513. * A texture that defines the thickness, stored in the green channel. This will
  28514. * be multiplied by `thickness`.
  28515. *
  28516. * `thicknessMap` represents non-color data. Any texture assigned must have
  28517. * `texture.colorSpace = NoColorSpace` (default).
  28518. *
  28519. * @type {?Texture}
  28520. * @default null
  28521. */
  28522. this.thicknessMap = null;
  28523. /**
  28524. * Density of the medium given as the average distance that light travels in
  28525. * the medium before interacting with a particle. The value is given in world
  28526. * space units, and must be greater than zero.
  28527. *
  28528. * @type {number}
  28529. * @default Infinity
  28530. */
  28531. this.attenuationDistance = Infinity;
  28532. /**
  28533. * The color that white light turns into due to absorption when reaching the
  28534. * attenuation distance.
  28535. *
  28536. * @type {Color}
  28537. * @default (1,1,1)
  28538. */
  28539. this.attenuationColor = new Color( 1, 1, 1 );
  28540. /**
  28541. * A float that scales the amount of specular reflection for non-metals only.
  28542. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28543. *
  28544. * @type {number}
  28545. * @default 1
  28546. */
  28547. this.specularIntensity = 1.0;
  28548. /**
  28549. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28550. * for per-pixel control over specular intensity.
  28551. *
  28552. * `specularIntensityMap` represents non-color data. Any texture assigned must have
  28553. * `texture.colorSpace = NoColorSpace` (default).
  28554. *
  28555. * @type {?Texture}
  28556. * @default null
  28557. */
  28558. this.specularIntensityMap = null;
  28559. /**
  28560. * Tints the specular reflection at normal incidence for non-metals only.
  28561. *
  28562. * @type {Color}
  28563. * @default (1,1,1)
  28564. */
  28565. this.specularColor = new Color( 1, 1, 1 );
  28566. /**
  28567. * The RGB channels of this texture are multiplied against `specularColor`,
  28568. * for per-pixel control over specular color.
  28569. *
  28570. * `specularColorMap` represents color data, and the texture must be assigned a
  28571. * {@link Texture#colorSpace}. Most `specularColorMap` textures set
  28572. * `texture.colorSpace = SRGBColorSpace`.
  28573. *
  28574. * @type {?Texture}
  28575. * @default null
  28576. */
  28577. this.specularColorMap = null;
  28578. this._anisotropy = 0;
  28579. this._clearcoat = 0;
  28580. this._dispersion = 0;
  28581. this._iridescence = 0;
  28582. this._sheen = 0.0;
  28583. this._transmission = 0;
  28584. this.setValues( parameters );
  28585. }
  28586. /**
  28587. * The anisotropy strength, from `0.0` to `1.0`.
  28588. *
  28589. * @type {number}
  28590. * @default 0
  28591. */
  28592. get anisotropy() {
  28593. return this._anisotropy;
  28594. }
  28595. set anisotropy( value ) {
  28596. if ( this._anisotropy > 0 !== value > 0 ) {
  28597. this.version ++;
  28598. }
  28599. this._anisotropy = value;
  28600. }
  28601. /**
  28602. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28603. * clear coat related properties to enable multilayer materials that have a
  28604. * thin translucent layer over the base layer.
  28605. *
  28606. * @type {number}
  28607. * @default 0
  28608. */
  28609. get clearcoat() {
  28610. return this._clearcoat;
  28611. }
  28612. set clearcoat( value ) {
  28613. if ( this._clearcoat > 0 !== value > 0 ) {
  28614. this.version ++;
  28615. }
  28616. this._clearcoat = value;
  28617. }
  28618. /**
  28619. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28620. * the surface and the viewer, from `0.0` to `1.0`.
  28621. *
  28622. * @type {number}
  28623. * @default 0
  28624. */
  28625. get iridescence() {
  28626. return this._iridescence;
  28627. }
  28628. set iridescence( value ) {
  28629. if ( this._iridescence > 0 !== value > 0 ) {
  28630. this.version ++;
  28631. }
  28632. this._iridescence = value;
  28633. }
  28634. /**
  28635. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28636. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28637. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28638. *
  28639. * @type {number}
  28640. * @default 0
  28641. */
  28642. get dispersion() {
  28643. return this._dispersion;
  28644. }
  28645. set dispersion( value ) {
  28646. if ( this._dispersion > 0 !== value > 0 ) {
  28647. this.version ++;
  28648. }
  28649. this._dispersion = value;
  28650. }
  28651. /**
  28652. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28653. *
  28654. * @type {number}
  28655. * @default 0
  28656. */
  28657. get sheen() {
  28658. return this._sheen;
  28659. }
  28660. set sheen( value ) {
  28661. if ( this._sheen > 0 !== value > 0 ) {
  28662. this.version ++;
  28663. }
  28664. this._sheen = value;
  28665. }
  28666. /**
  28667. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28668. *
  28669. * Thin, transparent or semitransparent, plastic or glass materials remain
  28670. * largely reflective even if they are fully transmissive. The transmission
  28671. * property can be used to model these materials.
  28672. *
  28673. * When transmission is non-zero, `opacity` should be set to `1`.
  28674. *
  28675. * @type {number}
  28676. * @default 0
  28677. */
  28678. get transmission() {
  28679. return this._transmission;
  28680. }
  28681. set transmission( value ) {
  28682. if ( this._transmission > 0 !== value > 0 ) {
  28683. this.version ++;
  28684. }
  28685. this._transmission = value;
  28686. }
  28687. copy( source ) {
  28688. super.copy( source );
  28689. this.defines = {
  28690. 'STANDARD': '',
  28691. 'PHYSICAL': ''
  28692. };
  28693. this.anisotropy = source.anisotropy;
  28694. this.anisotropyRotation = source.anisotropyRotation;
  28695. this.anisotropyMap = source.anisotropyMap;
  28696. this.clearcoat = source.clearcoat;
  28697. this.clearcoatMap = source.clearcoatMap;
  28698. this.clearcoatRoughness = source.clearcoatRoughness;
  28699. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28700. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28701. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28702. this.dispersion = source.dispersion;
  28703. this.ior = source.ior;
  28704. this.iridescence = source.iridescence;
  28705. this.iridescenceMap = source.iridescenceMap;
  28706. this.iridescenceIOR = source.iridescenceIOR;
  28707. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28708. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28709. this.sheen = source.sheen;
  28710. this.sheenColor.copy( source.sheenColor );
  28711. this.sheenColorMap = source.sheenColorMap;
  28712. this.sheenRoughness = source.sheenRoughness;
  28713. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28714. this.transmission = source.transmission;
  28715. this.transmissionMap = source.transmissionMap;
  28716. this.thickness = source.thickness;
  28717. this.thicknessMap = source.thicknessMap;
  28718. this.attenuationDistance = source.attenuationDistance;
  28719. this.attenuationColor.copy( source.attenuationColor );
  28720. this.specularIntensity = source.specularIntensity;
  28721. this.specularIntensityMap = source.specularIntensityMap;
  28722. this.specularColor.copy( source.specularColor );
  28723. this.specularColorMap = source.specularColorMap;
  28724. return this;
  28725. }
  28726. }
  28727. /**
  28728. * A material for shiny surfaces with specular highlights.
  28729. *
  28730. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28731. * model for calculating reflectance. Unlike the Lambertian model used in the
  28732. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28733. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28734. *
  28735. * Performance will generally be greater when using this material over the
  28736. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28737. * some graphical accuracy.
  28738. *
  28739. * @augments Material
  28740. * @demo scenes/material-browser.html#MeshPhongMaterial
  28741. */
  28742. class MeshPhongMaterial extends Material {
  28743. /**
  28744. * Constructs a new mesh phong material.
  28745. *
  28746. * @param {Object} [parameters] - An object with one or more properties
  28747. * defining the material's appearance. Any property of the material
  28748. * (including any property from inherited materials) can be passed
  28749. * in here. Color values can be passed any type of value accepted
  28750. * by {@link Color#set}.
  28751. */
  28752. constructor( parameters ) {
  28753. super();
  28754. /**
  28755. * This flag can be used for type testing.
  28756. *
  28757. * @type {boolean}
  28758. * @readonly
  28759. * @default true
  28760. */
  28761. this.isMeshPhongMaterial = true;
  28762. this.type = 'MeshPhongMaterial';
  28763. /**
  28764. * Color of the material.
  28765. *
  28766. * @type {Color}
  28767. * @default (1,1,1)
  28768. */
  28769. this.color = new Color( 0xffffff ); // diffuse
  28770. /**
  28771. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28772. *
  28773. * This defines how shiny the material is and the color of its shine.
  28774. *
  28775. * @type {Color}
  28776. */
  28777. this.specular = new Color( 0x111111 );
  28778. /**
  28779. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28780. *
  28781. * @type {number}
  28782. * @default 30
  28783. */
  28784. this.shininess = 30;
  28785. /**
  28786. * The color map. May optionally include an alpha channel, typically combined
  28787. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28788. * color is modulated by the diffuse `color`.
  28789. *
  28790. * `map` represents color data, and the texture must be assigned a
  28791. * {@link Texture#colorSpace}. Most `map` textures set
  28792. * `texture.colorSpace = SRGBColorSpace`.
  28793. *
  28794. * @type {?Texture}
  28795. * @default null
  28796. */
  28797. this.map = null;
  28798. /**
  28799. * The light map. Requires a second set of UVs.
  28800. *
  28801. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  28802. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  28803. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  28804. * such as `.exr` or `.hdr`.
  28805. *
  28806. * @type {?Texture}
  28807. * @default null
  28808. */
  28809. this.lightMap = null;
  28810. /**
  28811. * Intensity of the baked light.
  28812. *
  28813. * @type {number}
  28814. * @default 1
  28815. */
  28816. this.lightMapIntensity = 1.0;
  28817. /**
  28818. * The red channel of this texture is used as the ambient occlusion map.
  28819. * Requires a second set of UVs.
  28820. *
  28821. * `aoMap` represents non-color data. Any texture assigned must have
  28822. * `texture.colorSpace = NoColorSpace` (default).
  28823. *
  28824. * @type {?Texture}
  28825. * @default null
  28826. */
  28827. this.aoMap = null;
  28828. /**
  28829. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28830. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28831. * red channel is also `1`, ambient light is fully occluded on a surface.
  28832. *
  28833. * @type {number}
  28834. * @default 1
  28835. */
  28836. this.aoMapIntensity = 1.0;
  28837. /**
  28838. * Emissive (light) color of the material, essentially a solid color
  28839. * unaffected by other lighting.
  28840. *
  28841. * @type {Color}
  28842. * @default (0,0,0)
  28843. */
  28844. this.emissive = new Color( 0x000000 );
  28845. /**
  28846. * Intensity of the emissive light. Modulates the emissive color.
  28847. *
  28848. * @type {number}
  28849. * @default 1
  28850. */
  28851. this.emissiveIntensity = 1.0;
  28852. /**
  28853. * Set emissive (glow) map. The emissive map color is modulated by the
  28854. * emissive color and the emissive intensity. If you have an emissive map,
  28855. * be sure to set the emissive color to something other than black.
  28856. *
  28857. * `emissiveMap` represents color data, and the texture must be assigned a
  28858. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  28859. * `texture.colorSpace = SRGBColorSpace`.
  28860. *
  28861. * @type {?Texture}
  28862. * @default null
  28863. */
  28864. this.emissiveMap = null;
  28865. /**
  28866. * The texture to create a bump map. The black and white values map to the
  28867. * perceived depth in relation to the lights. Bump doesn't actually affect
  28868. * the geometry of the object, only the lighting. If a normal map is defined
  28869. * this will be ignored.
  28870. *
  28871. * `bumpMap` represents non-color data. Any texture assigned must have
  28872. * `texture.colorSpace = NoColorSpace` (default).
  28873. *
  28874. * @type {?Texture}
  28875. * @default null
  28876. */
  28877. this.bumpMap = null;
  28878. /**
  28879. * How much the bump map affects the material. Typical range is `[0,1]`.
  28880. *
  28881. * @type {number}
  28882. * @default 1
  28883. */
  28884. this.bumpScale = 1;
  28885. /**
  28886. * The texture to create a normal map. The RGB values affect the surface
  28887. * normal for each pixel fragment and change the way the color is lit. Normal
  28888. * maps do not change the actual shape of the surface, only the lighting. In
  28889. * case the material has a normal map authored using the left handed
  28890. * convention, the `y` component of `normalScale` should be negated to compensate
  28891. * for the different handedness.
  28892. *
  28893. * `normalMap` represents non-color data. Any texture assigned must have
  28894. * `texture.colorSpace = NoColorSpace` (default).
  28895. *
  28896. * @type {?Texture}
  28897. * @default null
  28898. */
  28899. this.normalMap = null;
  28900. /**
  28901. * The type of normal map.
  28902. *
  28903. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28904. * @default TangentSpaceNormalMap
  28905. */
  28906. this.normalMapType = TangentSpaceNormalMap;
  28907. /**
  28908. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28909. *
  28910. * @type {Vector2}
  28911. * @default (1,1)
  28912. */
  28913. this.normalScale = new Vector2( 1, 1 );
  28914. /**
  28915. * The displacement map affects the position of the mesh's vertices. Unlike
  28916. * other maps which only affect the light and shade of the material the
  28917. * displaced vertices can cast shadows, block other objects, and otherwise
  28918. * act as real geometry. The displacement texture is an image where the value
  28919. * of each pixel (white being the highest) is mapped against, and
  28920. * repositions, the vertices of the mesh. For best results, pair a
  28921. * displacement map with a matching normal map, since the renderer can
  28922. * not recompute surface normals from the displaced vertices.
  28923. *
  28924. * `displacementMap` represents non-color data. Any texture assigned must have
  28925. * `texture.colorSpace = NoColorSpace` (default).
  28926. *
  28927. * @type {?Texture}
  28928. * @default null
  28929. */
  28930. this.displacementMap = null;
  28931. /**
  28932. * How much the displacement map affects the mesh (where black is no
  28933. * displacement, and white is maximum displacement). Without a displacement
  28934. * map set, this value is not applied.
  28935. *
  28936. * @type {number}
  28937. * @default 0
  28938. */
  28939. this.displacementScale = 1;
  28940. /**
  28941. * The offset of the displacement map's values on the mesh's vertices.
  28942. * The bias is added to the scaled sample of the displacement map.
  28943. * Without a displacement map set, this value is not applied.
  28944. *
  28945. * @type {number}
  28946. * @default 0
  28947. */
  28948. this.displacementBias = 0;
  28949. /**
  28950. * The specular map value affects both how much the specular surface
  28951. * highlight contributes and how much of the environment map affects the
  28952. * surface.
  28953. *
  28954. * `specularMap` represents color data, and the texture must be assigned a
  28955. * {@link Texture#colorSpace}. Most `specularMap` textures set
  28956. * `texture.colorSpace = SRGBColorSpace`.
  28957. *
  28958. * @type {?Texture}
  28959. * @default null
  28960. */
  28961. this.specularMap = null;
  28962. /**
  28963. * The alpha map is a grayscale texture that controls the opacity across the
  28964. * surface (black: fully transparent; white: fully opaque).
  28965. *
  28966. * Only the color of the texture is used, ignoring the alpha channel if one
  28967. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28968. * when sampling this texture due to the extra bit of precision provided for
  28969. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28970. * luminance/alpha textures will also still work as expected.
  28971. *
  28972. * `alphaMap` represents non-color data. Any texture assigned must have
  28973. * `texture.colorSpace = NoColorSpace` (default).
  28974. *
  28975. * @type {?Texture}
  28976. * @default null
  28977. */
  28978. this.alphaMap = null;
  28979. /**
  28980. * The environment map.
  28981. *
  28982. * `envMap` represents luminance data, and the texture must be assigned
  28983. * a {@link Texture#colorSpace}. Most `envMap` textures set
  28984. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  28985. * such as `.exr` or `.hdr`.
  28986. *
  28987. * @type {?Texture}
  28988. * @default null
  28989. */
  28990. this.envMap = null;
  28991. /**
  28992. * The rotation of the environment map in radians.
  28993. *
  28994. * @type {Euler}
  28995. * @default (0,0,0)
  28996. */
  28997. this.envMapRotation = new Euler();
  28998. /**
  28999. * How to combine the result of the surface's color with the environment map, if any.
  29000. *
  29001. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29002. * blend between the two colors.
  29003. *
  29004. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29005. * @default MultiplyOperation
  29006. */
  29007. this.combine = MultiplyOperation;
  29008. /**
  29009. * How much the environment map affects the surface.
  29010. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29011. *
  29012. * @type {number}
  29013. * @default 1
  29014. */
  29015. this.reflectivity = 1;
  29016. /**
  29017. * Scales the effect of the environment map by multiplying its color.
  29018. *
  29019. * @type {number}
  29020. * @default 1
  29021. */
  29022. this.envMapIntensity = 1.0;
  29023. /**
  29024. * The index of refraction (IOR) of air (approximately 1) divided by the
  29025. * index of refraction of the material. It is used with environment mapping
  29026. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29027. * The refraction ratio should not exceed `1`.
  29028. *
  29029. * @type {number}
  29030. * @default 0.98
  29031. */
  29032. this.refractionRatio = 0.98;
  29033. /**
  29034. * Renders the geometry as a wireframe.
  29035. *
  29036. * @type {boolean}
  29037. * @default false
  29038. */
  29039. this.wireframe = false;
  29040. /**
  29041. * Controls the thickness of the wireframe.
  29042. *
  29043. * Can only be used with {@link SVGRenderer}.
  29044. *
  29045. * @type {number}
  29046. * @default 1
  29047. */
  29048. this.wireframeLinewidth = 1;
  29049. /**
  29050. * Defines appearance of wireframe ends.
  29051. *
  29052. * Can only be used with {@link SVGRenderer}.
  29053. *
  29054. * @type {('round'|'bevel'|'miter')}
  29055. * @default 'round'
  29056. */
  29057. this.wireframeLinecap = 'round';
  29058. /**
  29059. * Defines appearance of wireframe joints.
  29060. *
  29061. * Can only be used with {@link SVGRenderer}.
  29062. *
  29063. * @type {('round'|'bevel'|'miter')}
  29064. * @default 'round'
  29065. */
  29066. this.wireframeLinejoin = 'round';
  29067. /**
  29068. * Whether the material is rendered with flat shading or not.
  29069. *
  29070. * @type {boolean}
  29071. * @default false
  29072. */
  29073. this.flatShading = false;
  29074. /**
  29075. * Whether the material is affected by fog or not.
  29076. *
  29077. * @type {boolean}
  29078. * @default true
  29079. */
  29080. this.fog = true;
  29081. this.setValues( parameters );
  29082. }
  29083. copy( source ) {
  29084. super.copy( source );
  29085. this.color.copy( source.color );
  29086. this.specular.copy( source.specular );
  29087. this.shininess = source.shininess;
  29088. this.map = source.map;
  29089. this.lightMap = source.lightMap;
  29090. this.lightMapIntensity = source.lightMapIntensity;
  29091. this.aoMap = source.aoMap;
  29092. this.aoMapIntensity = source.aoMapIntensity;
  29093. this.emissive.copy( source.emissive );
  29094. this.emissiveMap = source.emissiveMap;
  29095. this.emissiveIntensity = source.emissiveIntensity;
  29096. this.bumpMap = source.bumpMap;
  29097. this.bumpScale = source.bumpScale;
  29098. this.normalMap = source.normalMap;
  29099. this.normalMapType = source.normalMapType;
  29100. this.normalScale.copy( source.normalScale );
  29101. this.displacementMap = source.displacementMap;
  29102. this.displacementScale = source.displacementScale;
  29103. this.displacementBias = source.displacementBias;
  29104. this.specularMap = source.specularMap;
  29105. this.alphaMap = source.alphaMap;
  29106. this.envMap = source.envMap;
  29107. this.envMapRotation.copy( source.envMapRotation );
  29108. this.combine = source.combine;
  29109. this.reflectivity = source.reflectivity;
  29110. this.envMapIntensity = source.envMapIntensity;
  29111. this.refractionRatio = source.refractionRatio;
  29112. this.wireframe = source.wireframe;
  29113. this.wireframeLinewidth = source.wireframeLinewidth;
  29114. this.wireframeLinecap = source.wireframeLinecap;
  29115. this.wireframeLinejoin = source.wireframeLinejoin;
  29116. this.flatShading = source.flatShading;
  29117. this.fog = source.fog;
  29118. return this;
  29119. }
  29120. }
  29121. /**
  29122. * A material implementing toon shading.
  29123. *
  29124. * @augments Material
  29125. * @demo scenes/material-browser.html#MeshToonMaterial
  29126. */
  29127. class MeshToonMaterial extends Material {
  29128. /**
  29129. * Constructs a new mesh toon material.
  29130. *
  29131. * @param {Object} [parameters] - An object with one or more properties
  29132. * defining the material's appearance. Any property of the material
  29133. * (including any property from inherited materials) can be passed
  29134. * in here. Color values can be passed any type of value accepted
  29135. * by {@link Color#set}.
  29136. */
  29137. constructor( parameters ) {
  29138. super();
  29139. /**
  29140. * This flag can be used for type testing.
  29141. *
  29142. * @type {boolean}
  29143. * @readonly
  29144. * @default true
  29145. */
  29146. this.isMeshToonMaterial = true;
  29147. this.defines = { 'TOON': '' };
  29148. this.type = 'MeshToonMaterial';
  29149. /**
  29150. * Color of the material.
  29151. *
  29152. * @type {Color}
  29153. * @default (1,1,1)
  29154. */
  29155. this.color = new Color( 0xffffff );
  29156. /**
  29157. * The color map. May optionally include an alpha channel, typically combined
  29158. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29159. * color is modulated by the diffuse `color`.
  29160. *
  29161. * `map` represents color data, and the texture must be assigned a
  29162. * {@link Texture#colorSpace}. Most `map` textures set
  29163. * `texture.colorSpace = SRGBColorSpace`.
  29164. *
  29165. * @type {?Texture}
  29166. * @default null
  29167. */
  29168. this.map = null;
  29169. /**
  29170. * Gradient map for toon shading. It's required to set
  29171. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@link NearestFilter}
  29172. * when using this type of texture.
  29173. *
  29174. * `gradientMap` represents non-color data. Any texture assigned must have
  29175. * `texture.colorSpace = NoColorSpace` (default).
  29176. *
  29177. * @type {?Texture}
  29178. * @default null
  29179. */
  29180. this.gradientMap = null;
  29181. /**
  29182. * The light map. Requires a second set of UVs.
  29183. *
  29184. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  29185. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  29186. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29187. * such as `.exr` or `.hdr`.
  29188. *
  29189. * @type {?Texture}
  29190. * @default null
  29191. */
  29192. this.lightMap = null;
  29193. /**
  29194. * Intensity of the baked light.
  29195. *
  29196. * @type {number}
  29197. * @default 1
  29198. */
  29199. this.lightMapIntensity = 1.0;
  29200. /**
  29201. * The red channel of this texture is used as the ambient occlusion map.
  29202. * Requires a second set of UVs.
  29203. *
  29204. * `aoMap` represents non-color data. Any texture assigned must have
  29205. * `texture.colorSpace = NoColorSpace` (default).
  29206. *
  29207. * @type {?Texture}
  29208. * @default null
  29209. */
  29210. this.aoMap = null;
  29211. /**
  29212. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29213. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29214. * red channel is also `1`, ambient light is fully occluded on a surface.
  29215. *
  29216. * @type {number}
  29217. * @default 1
  29218. */
  29219. this.aoMapIntensity = 1.0;
  29220. /**
  29221. * Emissive (light) color of the material, essentially a solid color
  29222. * unaffected by other lighting.
  29223. *
  29224. * @type {Color}
  29225. * @default (0,0,0)
  29226. */
  29227. this.emissive = new Color( 0x000000 );
  29228. /**
  29229. * Intensity of the emissive light. Modulates the emissive color.
  29230. *
  29231. * @type {number}
  29232. * @default 1
  29233. */
  29234. this.emissiveIntensity = 1.0;
  29235. /**
  29236. * Set emissive (glow) map. The emissive map color is modulated by the
  29237. * emissive color and the emissive intensity. If you have an emissive map,
  29238. * be sure to set the emissive color to something other than black.
  29239. *
  29240. * `emissiveMap` represents color data, and the texture must be assigned a
  29241. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  29242. * `texture.colorSpace = SRGBColorSpace`.
  29243. *
  29244. * @type {?Texture}
  29245. * @default null
  29246. */
  29247. this.emissiveMap = null;
  29248. /**
  29249. * The texture to create a bump map. The black and white values map to the
  29250. * perceived depth in relation to the lights. Bump doesn't actually affect
  29251. * the geometry of the object, only the lighting. If a normal map is defined
  29252. * this will be ignored.
  29253. *
  29254. * `bumpMap` represents non-color data. Any texture assigned must have
  29255. * `texture.colorSpace = NoColorSpace` (default).
  29256. *
  29257. * @type {?Texture}
  29258. * @default null
  29259. */
  29260. this.bumpMap = null;
  29261. /**
  29262. * How much the bump map affects the material. Typical range is `[0,1]`.
  29263. *
  29264. * @type {number}
  29265. * @default 1
  29266. */
  29267. this.bumpScale = 1;
  29268. /**
  29269. * The texture to create a normal map. The RGB values affect the surface
  29270. * normal for each pixel fragment and change the way the color is lit. Normal
  29271. * maps do not change the actual shape of the surface, only the lighting. In
  29272. * case the material has a normal map authored using the left handed
  29273. * convention, the `y` component of `normalScale` should be negated to compensate
  29274. * for the different handedness.
  29275. *
  29276. * `normalMap` represents non-color data. Any texture assigned must have
  29277. * `texture.colorSpace = NoColorSpace` (default).
  29278. *
  29279. * @type {?Texture}
  29280. * @default null
  29281. */
  29282. this.normalMap = null;
  29283. /**
  29284. * The type of normal map.
  29285. *
  29286. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29287. * @default TangentSpaceNormalMap
  29288. */
  29289. this.normalMapType = TangentSpaceNormalMap;
  29290. /**
  29291. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29292. *
  29293. * @type {Vector2}
  29294. * @default (1,1)
  29295. */
  29296. this.normalScale = new Vector2( 1, 1 );
  29297. /**
  29298. * The displacement map affects the position of the mesh's vertices. Unlike
  29299. * other maps which only affect the light and shade of the material the
  29300. * displaced vertices can cast shadows, block other objects, and otherwise
  29301. * act as real geometry. The displacement texture is an image where the value
  29302. * of each pixel (white being the highest) is mapped against, and
  29303. * repositions, the vertices of the mesh. For best results, pair a
  29304. * displacement map with a matching normal map, since the renderer can
  29305. * not recompute surface normals from the displaced vertices.
  29306. *
  29307. * `displacementMap` represents non-color data. Any texture assigned must have
  29308. * `texture.colorSpace = NoColorSpace` (default).
  29309. *
  29310. * @type {?Texture}
  29311. * @default null
  29312. */
  29313. this.displacementMap = null;
  29314. /**
  29315. * How much the displacement map affects the mesh (where black is no
  29316. * displacement, and white is maximum displacement). Without a displacement
  29317. * map set, this value is not applied.
  29318. *
  29319. * @type {number}
  29320. * @default 0
  29321. */
  29322. this.displacementScale = 1;
  29323. /**
  29324. * The offset of the displacement map's values on the mesh's vertices.
  29325. * The bias is added to the scaled sample of the displacement map.
  29326. * Without a displacement map set, this value is not applied.
  29327. *
  29328. * @type {number}
  29329. * @default 0
  29330. */
  29331. this.displacementBias = 0;
  29332. /**
  29333. * The alpha map is a grayscale texture that controls the opacity across the
  29334. * surface (black: fully transparent; white: fully opaque).
  29335. *
  29336. * Only the color of the texture is used, ignoring the alpha channel if one
  29337. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29338. * when sampling this texture due to the extra bit of precision provided for
  29339. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29340. * luminance/alpha textures will also still work as expected.
  29341. *
  29342. * `alphaMap` represents non-color data. Any texture assigned must have
  29343. * `texture.colorSpace = NoColorSpace` (default).
  29344. *
  29345. * @type {?Texture}
  29346. * @default null
  29347. */
  29348. this.alphaMap = null;
  29349. /**
  29350. * Renders the geometry as a wireframe.
  29351. *
  29352. * @type {boolean}
  29353. * @default false
  29354. */
  29355. this.wireframe = false;
  29356. /**
  29357. * Controls the thickness of the wireframe.
  29358. *
  29359. * Can only be used with {@link SVGRenderer}.
  29360. *
  29361. * @type {number}
  29362. * @default 1
  29363. */
  29364. this.wireframeLinewidth = 1;
  29365. /**
  29366. * Defines appearance of wireframe ends.
  29367. *
  29368. * Can only be used with {@link SVGRenderer}.
  29369. *
  29370. * @type {('round'|'bevel'|'miter')}
  29371. * @default 'round'
  29372. */
  29373. this.wireframeLinecap = 'round';
  29374. /**
  29375. * Defines appearance of wireframe joints.
  29376. *
  29377. * Can only be used with {@link SVGRenderer}.
  29378. *
  29379. * @type {('round'|'bevel'|'miter')}
  29380. * @default 'round'
  29381. */
  29382. this.wireframeLinejoin = 'round';
  29383. /**
  29384. * Whether the material is affected by fog or not.
  29385. *
  29386. * @type {boolean}
  29387. * @default true
  29388. */
  29389. this.fog = true;
  29390. this.setValues( parameters );
  29391. }
  29392. copy( source ) {
  29393. super.copy( source );
  29394. this.color.copy( source.color );
  29395. this.map = source.map;
  29396. this.gradientMap = source.gradientMap;
  29397. this.lightMap = source.lightMap;
  29398. this.lightMapIntensity = source.lightMapIntensity;
  29399. this.aoMap = source.aoMap;
  29400. this.aoMapIntensity = source.aoMapIntensity;
  29401. this.emissive.copy( source.emissive );
  29402. this.emissiveMap = source.emissiveMap;
  29403. this.emissiveIntensity = source.emissiveIntensity;
  29404. this.bumpMap = source.bumpMap;
  29405. this.bumpScale = source.bumpScale;
  29406. this.normalMap = source.normalMap;
  29407. this.normalMapType = source.normalMapType;
  29408. this.normalScale.copy( source.normalScale );
  29409. this.displacementMap = source.displacementMap;
  29410. this.displacementScale = source.displacementScale;
  29411. this.displacementBias = source.displacementBias;
  29412. this.alphaMap = source.alphaMap;
  29413. this.wireframe = source.wireframe;
  29414. this.wireframeLinewidth = source.wireframeLinewidth;
  29415. this.wireframeLinecap = source.wireframeLinecap;
  29416. this.wireframeLinejoin = source.wireframeLinejoin;
  29417. this.fog = source.fog;
  29418. return this;
  29419. }
  29420. }
  29421. /**
  29422. * A material that maps the normal vectors to RGB colors.
  29423. *
  29424. * @augments Material
  29425. * @demo scenes/material-browser.html#MeshNormalMaterial
  29426. */
  29427. class MeshNormalMaterial extends Material {
  29428. /**
  29429. * Constructs a new mesh normal material.
  29430. *
  29431. * @param {Object} [parameters] - An object with one or more properties
  29432. * defining the material's appearance. Any property of the material
  29433. * (including any property from inherited materials) can be passed
  29434. * in here. Color values can be passed any type of value accepted
  29435. * by {@link Color#set}.
  29436. */
  29437. constructor( parameters ) {
  29438. super();
  29439. /**
  29440. * This flag can be used for type testing.
  29441. *
  29442. * @type {boolean}
  29443. * @readonly
  29444. * @default true
  29445. */
  29446. this.isMeshNormalMaterial = true;
  29447. this.type = 'MeshNormalMaterial';
  29448. /**
  29449. * The texture to create a bump map. The black and white values map to the
  29450. * perceived depth in relation to the lights. Bump doesn't actually affect
  29451. * the geometry of the object, only the lighting. If a normal map is defined
  29452. * this will be ignored.
  29453. *
  29454. * `bumpMap` represents non-color data. Any texture assigned must have
  29455. * `texture.colorSpace = NoColorSpace` (default).
  29456. *
  29457. * @type {?Texture}
  29458. * @default null
  29459. */
  29460. this.bumpMap = null;
  29461. /**
  29462. * How much the bump map affects the material. Typical range is `[0,1]`.
  29463. *
  29464. * @type {number}
  29465. * @default 1
  29466. */
  29467. this.bumpScale = 1;
  29468. /**
  29469. * The texture to create a normal map. The RGB values affect the surface
  29470. * normal for each pixel fragment and change the way the color is lit. Normal
  29471. * maps do not change the actual shape of the surface, only the lighting. In
  29472. * case the material has a normal map authored using the left handed
  29473. * convention, the `y` component of `normalScale` should be negated to compensate
  29474. * for the different handedness.
  29475. *
  29476. * `normalMap` represents non-color data. Any texture assigned must have
  29477. * `texture.colorSpace = NoColorSpace` (default).
  29478. *
  29479. * @type {?Texture}
  29480. * @default null
  29481. */
  29482. this.normalMap = null;
  29483. /**
  29484. * The type of normal map.
  29485. *
  29486. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29487. * @default TangentSpaceNormalMap
  29488. */
  29489. this.normalMapType = TangentSpaceNormalMap;
  29490. /**
  29491. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29492. *
  29493. * @type {Vector2}
  29494. * @default (1,1)
  29495. */
  29496. this.normalScale = new Vector2( 1, 1 );
  29497. /**
  29498. * The displacement map affects the position of the mesh's vertices. Unlike
  29499. * other maps which only affect the light and shade of the material the
  29500. * displaced vertices can cast shadows, block other objects, and otherwise
  29501. * act as real geometry. The displacement texture is an image where the value
  29502. * of each pixel (white being the highest) is mapped against, and
  29503. * repositions, the vertices of the mesh. For best results, pair a
  29504. * displacement map with a matching normal map, since the renderer can
  29505. * not recompute surface normals from the displaced vertices.
  29506. *
  29507. * @type {?Texture}
  29508. * @default null
  29509. */
  29510. this.displacementMap = null;
  29511. /**
  29512. * How much the displacement map affects the mesh (where black is no
  29513. * displacement, and white is maximum displacement). Without a displacement
  29514. * map set, this value is not applied.
  29515. *
  29516. * @type {number}
  29517. * @default 0
  29518. */
  29519. this.displacementScale = 1;
  29520. /**
  29521. * The offset of the displacement map's values on the mesh's vertices.
  29522. * The bias is added to the scaled sample of the displacement map.
  29523. * Without a displacement map set, this value is not applied.
  29524. *
  29525. * @type {number}
  29526. * @default 0
  29527. */
  29528. this.displacementBias = 0;
  29529. /**
  29530. * Renders the geometry as a wireframe.
  29531. *
  29532. * @type {boolean}
  29533. * @default false
  29534. */
  29535. this.wireframe = false;
  29536. /**
  29537. * Controls the thickness of the wireframe.
  29538. *
  29539. * WebGL and WebGPU ignore this property and always render
  29540. * 1 pixel wide lines.
  29541. *
  29542. * @type {number}
  29543. * @default 1
  29544. */
  29545. this.wireframeLinewidth = 1;
  29546. /**
  29547. * Whether the material is rendered with flat shading or not.
  29548. *
  29549. * @type {boolean}
  29550. * @default false
  29551. */
  29552. this.flatShading = false;
  29553. this.setValues( parameters );
  29554. }
  29555. copy( source ) {
  29556. super.copy( source );
  29557. this.bumpMap = source.bumpMap;
  29558. this.bumpScale = source.bumpScale;
  29559. this.normalMap = source.normalMap;
  29560. this.normalMapType = source.normalMapType;
  29561. this.normalScale.copy( source.normalScale );
  29562. this.displacementMap = source.displacementMap;
  29563. this.displacementScale = source.displacementScale;
  29564. this.displacementBias = source.displacementBias;
  29565. this.wireframe = source.wireframe;
  29566. this.wireframeLinewidth = source.wireframeLinewidth;
  29567. this.flatShading = source.flatShading;
  29568. return this;
  29569. }
  29570. }
  29571. /**
  29572. * A material for non-shiny surfaces, without specular highlights.
  29573. *
  29574. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29575. * model for calculating reflectance. This can simulate some surfaces (such
  29576. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29577. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29578. * shading.
  29579. *
  29580. * Due to the simplicity of the reflectance and illumination models,
  29581. * performance will be greater when using this material over the
  29582. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29583. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29584. *
  29585. * @augments Material
  29586. * @demo scenes/material-browser.html#MeshLambertMaterial
  29587. */
  29588. class MeshLambertMaterial extends Material {
  29589. /**
  29590. * Constructs a new mesh lambert material.
  29591. *
  29592. * @param {Object} [parameters] - An object with one or more properties
  29593. * defining the material's appearance. Any property of the material
  29594. * (including any property from inherited materials) can be passed
  29595. * in here. Color values can be passed any type of value accepted
  29596. * by {@link Color#set}.
  29597. */
  29598. constructor( parameters ) {
  29599. super();
  29600. /**
  29601. * This flag can be used for type testing.
  29602. *
  29603. * @type {boolean}
  29604. * @readonly
  29605. * @default true
  29606. */
  29607. this.isMeshLambertMaterial = true;
  29608. this.type = 'MeshLambertMaterial';
  29609. /**
  29610. * Color of the material.
  29611. *
  29612. * @type {Color}
  29613. * @default (1,1,1)
  29614. */
  29615. this.color = new Color( 0xffffff ); // diffuse
  29616. /**
  29617. * The color map. May optionally include an alpha channel, typically combined
  29618. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29619. * color is modulated by the diffuse `color`.
  29620. *
  29621. * `map` represents color data, and the texture must be assigned a
  29622. * {@link Texture#colorSpace}. Most `map` textures set
  29623. * `texture.colorSpace = SRGBColorSpace`.
  29624. *
  29625. * @type {?Texture}
  29626. * @default null
  29627. */
  29628. this.map = null;
  29629. /**
  29630. * The light map. Requires a second set of UVs.
  29631. *
  29632. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  29633. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  29634. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29635. * such as `.exr` or `.hdr`.
  29636. *
  29637. * @type {?Texture}
  29638. * @default null
  29639. */
  29640. this.lightMap = null;
  29641. /**
  29642. * Intensity of the baked light.
  29643. *
  29644. * @type {number}
  29645. * @default 1
  29646. */
  29647. this.lightMapIntensity = 1.0;
  29648. /**
  29649. * The red channel of this texture is used as the ambient occlusion map.
  29650. * Requires a second set of UVs.
  29651. *
  29652. * `aoMap` represents non-color data. Any texture assigned must have
  29653. * `texture.colorSpace = NoColorSpace` (default).
  29654. *
  29655. * @type {?Texture}
  29656. * @default null
  29657. */
  29658. this.aoMap = null;
  29659. /**
  29660. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29661. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29662. * red channel is also `1`, ambient light is fully occluded on a surface.
  29663. *
  29664. * @type {number}
  29665. * @default 1
  29666. */
  29667. this.aoMapIntensity = 1.0;
  29668. /**
  29669. * Emissive (light) color of the material, essentially a solid color
  29670. * unaffected by other lighting.
  29671. *
  29672. * @type {Color}
  29673. * @default (0,0,0)
  29674. */
  29675. this.emissive = new Color( 0x000000 );
  29676. /**
  29677. * Intensity of the emissive light. Modulates the emissive color.
  29678. *
  29679. * @type {number}
  29680. * @default 1
  29681. */
  29682. this.emissiveIntensity = 1.0;
  29683. /**
  29684. * Set emissive (glow) map. The emissive map color is modulated by the
  29685. * emissive color and the emissive intensity. If you have an emissive map,
  29686. * be sure to set the emissive color to something other than black.
  29687. *
  29688. * `emissiveMap` represents color data, and the texture must be assigned a
  29689. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  29690. * `texture.colorSpace = SRGBColorSpace`.
  29691. *
  29692. * @type {?Texture}
  29693. * @default null
  29694. */
  29695. this.emissiveMap = null;
  29696. /**
  29697. * The texture to create a bump map. The black and white values map to the
  29698. * perceived depth in relation to the lights. Bump doesn't actually affect
  29699. * the geometry of the object, only the lighting. If a normal map is defined
  29700. * this will be ignored.
  29701. *
  29702. * `bumpMap` represents non-color data. Any texture assigned must have
  29703. * `texture.colorSpace = NoColorSpace` (default).
  29704. *
  29705. * @type {?Texture}
  29706. * @default null
  29707. */
  29708. this.bumpMap = null;
  29709. /**
  29710. * How much the bump map affects the material. Typical range is `[0,1]`.
  29711. *
  29712. * @type {number}
  29713. * @default 1
  29714. */
  29715. this.bumpScale = 1;
  29716. /**
  29717. * The texture to create a normal map. The RGB values affect the surface
  29718. * normal for each pixel fragment and change the way the color is lit. Normal
  29719. * maps do not change the actual shape of the surface, only the lighting. In
  29720. * case the material has a normal map authored using the left handed
  29721. * convention, the `y` component of `normalScale` should be negated to compensate
  29722. * for the different handedness.
  29723. *
  29724. * `normalMap` represents non-color data. Any texture assigned must have
  29725. * `texture.colorSpace = NoColorSpace` (default).
  29726. *
  29727. * @type {?Texture}
  29728. * @default null
  29729. */
  29730. this.normalMap = null;
  29731. /**
  29732. * The type of normal map.
  29733. *
  29734. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29735. * @default TangentSpaceNormalMap
  29736. */
  29737. this.normalMapType = TangentSpaceNormalMap;
  29738. /**
  29739. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29740. *
  29741. * @type {Vector2}
  29742. * @default (1,1)
  29743. */
  29744. this.normalScale = new Vector2( 1, 1 );
  29745. /**
  29746. * The displacement map affects the position of the mesh's vertices. Unlike
  29747. * other maps which only affect the light and shade of the material the
  29748. * displaced vertices can cast shadows, block other objects, and otherwise
  29749. * act as real geometry. The displacement texture is an image where the value
  29750. * of each pixel (white being the highest) is mapped against, and
  29751. * repositions, the vertices of the mesh. For best results, pair a
  29752. * displacement map with a matching normal map, since the renderer can
  29753. * not recompute surface normals from the displaced vertices.
  29754. *
  29755. * `displacementMap` represents non-color data. Any texture assigned must have
  29756. * `texture.colorSpace = NoColorSpace` (default).
  29757. *
  29758. * @type {?Texture}
  29759. * @default null
  29760. */
  29761. this.displacementMap = null;
  29762. /**
  29763. * How much the displacement map affects the mesh (where black is no
  29764. * displacement, and white is maximum displacement). Without a displacement
  29765. * map set, this value is not applied.
  29766. *
  29767. * @type {number}
  29768. * @default 0
  29769. */
  29770. this.displacementScale = 1;
  29771. /**
  29772. * The offset of the displacement map's values on the mesh's vertices.
  29773. * The bias is added to the scaled sample of the displacement map.
  29774. * Without a displacement map set, this value is not applied.
  29775. *
  29776. * @type {number}
  29777. * @default 0
  29778. */
  29779. this.displacementBias = 0;
  29780. /**
  29781. * Specular map used by the material.
  29782. *
  29783. * `specularMap` represents color data, and the texture must be assigned a
  29784. * {@link Texture#colorSpace}. Most `specularMap` textures set
  29785. * `texture.colorSpace = SRGBColorSpace`.
  29786. *
  29787. * @type {?Texture}
  29788. * @default null
  29789. */
  29790. this.specularMap = null;
  29791. /**
  29792. * The alpha map is a grayscale texture that controls the opacity across the
  29793. * surface (black: fully transparent; white: fully opaque).
  29794. *
  29795. * Only the color of the texture is used, ignoring the alpha channel if one
  29796. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29797. * when sampling this texture due to the extra bit of precision provided for
  29798. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29799. * luminance/alpha textures will also still work as expected.
  29800. *
  29801. * `alphaMap` represents non-color data. Any texture assigned must have
  29802. * `texture.colorSpace = NoColorSpace` (default).
  29803. *
  29804. * @type {?Texture}
  29805. * @default null
  29806. */
  29807. this.alphaMap = null;
  29808. /**
  29809. * The environment map.
  29810. *
  29811. * `envMap` represents luminance data, and the texture must be assigned
  29812. * a {@link Texture#colorSpace}. Most `envMap` textures set
  29813. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29814. * such as `.exr` or `.hdr`.
  29815. *
  29816. * @type {?Texture}
  29817. * @default null
  29818. */
  29819. this.envMap = null;
  29820. /**
  29821. * The rotation of the environment map in radians.
  29822. *
  29823. * @type {Euler}
  29824. * @default (0,0,0)
  29825. */
  29826. this.envMapRotation = new Euler();
  29827. /**
  29828. * How to combine the result of the surface's color with the environment map, if any.
  29829. *
  29830. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29831. * blend between the two colors.
  29832. *
  29833. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29834. * @default MultiplyOperation
  29835. */
  29836. this.combine = MultiplyOperation;
  29837. /**
  29838. * How much the environment map affects the surface.
  29839. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29840. *
  29841. * @type {number}
  29842. * @default 1
  29843. */
  29844. this.reflectivity = 1;
  29845. /**
  29846. * Scales the effect of the environment map by multiplying its color.
  29847. *
  29848. * @type {number}
  29849. * @default 1
  29850. */
  29851. this.envMapIntensity = 1.0;
  29852. /**
  29853. * The index of refraction (IOR) of air (approximately 1) divided by the
  29854. * index of refraction of the material. It is used with environment mapping
  29855. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29856. * The refraction ratio should not exceed `1`.
  29857. *
  29858. * @type {number}
  29859. * @default 0.98
  29860. */
  29861. this.refractionRatio = 0.98;
  29862. /**
  29863. * Renders the geometry as a wireframe.
  29864. *
  29865. * @type {boolean}
  29866. * @default false
  29867. */
  29868. this.wireframe = false;
  29869. /**
  29870. * Controls the thickness of the wireframe.
  29871. *
  29872. * Can only be used with {@link SVGRenderer}.
  29873. *
  29874. * @type {number}
  29875. * @default 1
  29876. */
  29877. this.wireframeLinewidth = 1;
  29878. /**
  29879. * Defines appearance of wireframe ends.
  29880. *
  29881. * Can only be used with {@link SVGRenderer}.
  29882. *
  29883. * @type {('round'|'bevel'|'miter')}
  29884. * @default 'round'
  29885. */
  29886. this.wireframeLinecap = 'round';
  29887. /**
  29888. * Defines appearance of wireframe joints.
  29889. *
  29890. * Can only be used with {@link SVGRenderer}.
  29891. *
  29892. * @type {('round'|'bevel'|'miter')}
  29893. * @default 'round'
  29894. */
  29895. this.wireframeLinejoin = 'round';
  29896. /**
  29897. * Whether the material is rendered with flat shading or not.
  29898. *
  29899. * @type {boolean}
  29900. * @default false
  29901. */
  29902. this.flatShading = false;
  29903. /**
  29904. * Whether the material is affected by fog or not.
  29905. *
  29906. * @type {boolean}
  29907. * @default true
  29908. */
  29909. this.fog = true;
  29910. this.setValues( parameters );
  29911. }
  29912. copy( source ) {
  29913. super.copy( source );
  29914. this.color.copy( source.color );
  29915. this.map = source.map;
  29916. this.lightMap = source.lightMap;
  29917. this.lightMapIntensity = source.lightMapIntensity;
  29918. this.aoMap = source.aoMap;
  29919. this.aoMapIntensity = source.aoMapIntensity;
  29920. this.emissive.copy( source.emissive );
  29921. this.emissiveMap = source.emissiveMap;
  29922. this.emissiveIntensity = source.emissiveIntensity;
  29923. this.bumpMap = source.bumpMap;
  29924. this.bumpScale = source.bumpScale;
  29925. this.normalMap = source.normalMap;
  29926. this.normalMapType = source.normalMapType;
  29927. this.normalScale.copy( source.normalScale );
  29928. this.displacementMap = source.displacementMap;
  29929. this.displacementScale = source.displacementScale;
  29930. this.displacementBias = source.displacementBias;
  29931. this.specularMap = source.specularMap;
  29932. this.alphaMap = source.alphaMap;
  29933. this.envMap = source.envMap;
  29934. this.envMapRotation.copy( source.envMapRotation );
  29935. this.combine = source.combine;
  29936. this.reflectivity = source.reflectivity;
  29937. this.envMapIntensity = source.envMapIntensity;
  29938. this.refractionRatio = source.refractionRatio;
  29939. this.wireframe = source.wireframe;
  29940. this.wireframeLinewidth = source.wireframeLinewidth;
  29941. this.wireframeLinecap = source.wireframeLinecap;
  29942. this.wireframeLinejoin = source.wireframeLinejoin;
  29943. this.flatShading = source.flatShading;
  29944. this.fog = source.fog;
  29945. return this;
  29946. }
  29947. }
  29948. /**
  29949. * A material for drawing geometry by depth. Depth is based off of the camera
  29950. * near and far plane. White is nearest, black is farthest.
  29951. *
  29952. * @augments Material
  29953. * @demo scenes/material-browser.html#MeshDepthMaterial
  29954. */
  29955. class MeshDepthMaterial extends Material {
  29956. /**
  29957. * Constructs a new mesh depth material.
  29958. *
  29959. * @param {Object} [parameters] - An object with one or more properties
  29960. * defining the material's appearance. Any property of the material
  29961. * (including any property from inherited materials) can be passed
  29962. * in here. Color values can be passed any type of value accepted
  29963. * by {@link Color#set}.
  29964. */
  29965. constructor( parameters ) {
  29966. super();
  29967. /**
  29968. * This flag can be used for type testing.
  29969. *
  29970. * @type {boolean}
  29971. * @readonly
  29972. * @default true
  29973. */
  29974. this.isMeshDepthMaterial = true;
  29975. this.type = 'MeshDepthMaterial';
  29976. /**
  29977. * Type for depth packing.
  29978. *
  29979. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29980. * @default BasicDepthPacking
  29981. */
  29982. this.depthPacking = BasicDepthPacking;
  29983. /**
  29984. * The color map. May optionally include an alpha channel, typically combined
  29985. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29986. *
  29987. * `map` represents color data, and the texture must be assigned a
  29988. * {@link Texture#colorSpace}. Most `map` textures set
  29989. * `texture.colorSpace = SRGBColorSpace`.
  29990. *
  29991. * @type {?Texture}
  29992. * @default null
  29993. */
  29994. this.map = null;
  29995. /**
  29996. * The alpha map is a grayscale texture that controls the opacity across the
  29997. * surface (black: fully transparent; white: fully opaque).
  29998. *
  29999. * Only the color of the texture is used, ignoring the alpha channel if one
  30000. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30001. * when sampling this texture due to the extra bit of precision provided for
  30002. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30003. * luminance/alpha textures will also still work as expected.
  30004. *
  30005. * `alphaMap` represents non-color data. Any texture assigned must have
  30006. * `texture.colorSpace = NoColorSpace` (default).
  30007. *
  30008. * @type {?Texture}
  30009. * @default null
  30010. */
  30011. this.alphaMap = null;
  30012. /**
  30013. * The displacement map affects the position of the mesh's vertices. Unlike
  30014. * other maps which only affect the light and shade of the material the
  30015. * displaced vertices can cast shadows, block other objects, and otherwise
  30016. * act as real geometry. The displacement texture is an image where the value
  30017. * of each pixel (white being the highest) is mapped against, and
  30018. * repositions, the vertices of the mesh.
  30019. *
  30020. * `displacementMap` represents non-color data. Any texture assigned must have
  30021. * `texture.colorSpace = NoColorSpace` (default).
  30022. *
  30023. * @type {?Texture}
  30024. * @default null
  30025. */
  30026. this.displacementMap = null;
  30027. /**
  30028. * How much the displacement map affects the mesh (where black is no
  30029. * displacement, and white is maximum displacement). Without a displacement
  30030. * map set, this value is not applied.
  30031. *
  30032. * @type {number}
  30033. * @default 0
  30034. */
  30035. this.displacementScale = 1;
  30036. /**
  30037. * The offset of the displacement map's values on the mesh's vertices.
  30038. * The bias is added to the scaled sample of the displacement map.
  30039. * Without a displacement map set, this value is not applied.
  30040. *
  30041. * @type {number}
  30042. * @default 0
  30043. */
  30044. this.displacementBias = 0;
  30045. /**
  30046. * Renders the geometry as a wireframe.
  30047. *
  30048. * @type {boolean}
  30049. * @default false
  30050. */
  30051. this.wireframe = false;
  30052. /**
  30053. * Controls the thickness of the wireframe.
  30054. *
  30055. * WebGL and WebGPU ignore this property and always render
  30056. * 1 pixel wide lines.
  30057. *
  30058. * @type {number}
  30059. * @default 1
  30060. */
  30061. this.wireframeLinewidth = 1;
  30062. this.setValues( parameters );
  30063. }
  30064. copy( source ) {
  30065. super.copy( source );
  30066. this.depthPacking = source.depthPacking;
  30067. this.map = source.map;
  30068. this.alphaMap = source.alphaMap;
  30069. this.displacementMap = source.displacementMap;
  30070. this.displacementScale = source.displacementScale;
  30071. this.displacementBias = source.displacementBias;
  30072. this.wireframe = source.wireframe;
  30073. this.wireframeLinewidth = source.wireframeLinewidth;
  30074. return this;
  30075. }
  30076. }
  30077. /**
  30078. * A material used internally for implementing shadow mapping with
  30079. * point lights.
  30080. *
  30081. * Can also be used to customize the shadow casting of an object by assigning
  30082. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  30083. * The following examples demonstrates this approach in order to ensure
  30084. * transparent parts of objects do not cast shadows.
  30085. *
  30086. * @augments Material
  30087. */
  30088. class MeshDistanceMaterial extends Material {
  30089. /**
  30090. * Constructs a new mesh distance material.
  30091. *
  30092. * @param {Object} [parameters] - An object with one or more properties
  30093. * defining the material's appearance. Any property of the material
  30094. * (including any property from inherited materials) can be passed
  30095. * in here. Color values can be passed any type of value accepted
  30096. * by {@link Color#set}.
  30097. */
  30098. constructor( parameters ) {
  30099. super();
  30100. /**
  30101. * This flag can be used for type testing.
  30102. *
  30103. * @type {boolean}
  30104. * @readonly
  30105. * @default true
  30106. */
  30107. this.isMeshDistanceMaterial = true;
  30108. this.type = 'MeshDistanceMaterial';
  30109. /**
  30110. * The color map. May optionally include an alpha channel, typically combined
  30111. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30112. *
  30113. * `map` represents color data, and the texture must be assigned a
  30114. * {@link Texture#colorSpace}. Most `map` textures set
  30115. * `texture.colorSpace = SRGBColorSpace`.
  30116. *
  30117. * @type {?Texture}
  30118. * @default null
  30119. */
  30120. this.map = null;
  30121. /**
  30122. * The alpha map is a grayscale texture that controls the opacity across the
  30123. * surface (black: fully transparent; white: fully opaque).
  30124. *
  30125. * Only the color of the texture is used, ignoring the alpha channel if one
  30126. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30127. * when sampling this texture due to the extra bit of precision provided for
  30128. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30129. * luminance/alpha textures will also still work as expected.
  30130. *
  30131. * `alphaMap` represents non-color data. Any texture assigned must have
  30132. * `texture.colorSpace = NoColorSpace` (default).
  30133. *
  30134. * @type {?Texture}
  30135. * @default null
  30136. */
  30137. this.alphaMap = null;
  30138. /**
  30139. * The displacement map affects the position of the mesh's vertices. Unlike
  30140. * other maps which only affect the light and shade of the material the
  30141. * displaced vertices can cast shadows, block other objects, and otherwise
  30142. * act as real geometry. The displacement texture is an image where the value
  30143. * of each pixel (white being the highest) is mapped against, and
  30144. * repositions, the vertices of the mesh.
  30145. *
  30146. * `displacementMap` represents non-color data. Any texture assigned must have
  30147. * `texture.colorSpace = NoColorSpace` (default).
  30148. *
  30149. * @type {?Texture}
  30150. * @default null
  30151. */
  30152. this.displacementMap = null;
  30153. /**
  30154. * How much the displacement map affects the mesh (where black is no
  30155. * displacement, and white is maximum displacement). Without a displacement
  30156. * map set, this value is not applied.
  30157. *
  30158. * @type {number}
  30159. * @default 0
  30160. */
  30161. this.displacementScale = 1;
  30162. /**
  30163. * The offset of the displacement map's values on the mesh's vertices.
  30164. * The bias is added to the scaled sample of the displacement map.
  30165. * Without a displacement map set, this value is not applied.
  30166. *
  30167. * @type {number}
  30168. * @default 0
  30169. */
  30170. this.displacementBias = 0;
  30171. this.setValues( parameters );
  30172. }
  30173. copy( source ) {
  30174. super.copy( source );
  30175. this.map = source.map;
  30176. this.alphaMap = source.alphaMap;
  30177. this.displacementMap = source.displacementMap;
  30178. this.displacementScale = source.displacementScale;
  30179. this.displacementBias = source.displacementBias;
  30180. return this;
  30181. }
  30182. }
  30183. /**
  30184. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  30185. * material color and shading.
  30186. *
  30187. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  30188. * baked lighting. It will cast a shadow onto an object that receives shadows
  30189. * (and shadow clipping works), but it will not self-shadow or receive
  30190. * shadows.
  30191. *
  30192. * @augments Material
  30193. * @demo scenes/material-browser.html#MeshMatcapMaterial
  30194. */
  30195. class MeshMatcapMaterial extends Material {
  30196. /**
  30197. * Constructs a new mesh matcap material.
  30198. *
  30199. * @param {Object} [parameters] - An object with one or more properties
  30200. * defining the material's appearance. Any property of the material
  30201. * (including any property from inherited materials) can be passed
  30202. * in here. Color values can be passed any type of value accepted
  30203. * by {@link Color#set}.
  30204. */
  30205. constructor( parameters ) {
  30206. super();
  30207. /**
  30208. * This flag can be used for type testing.
  30209. *
  30210. * @type {boolean}
  30211. * @readonly
  30212. * @default true
  30213. */
  30214. this.isMeshMatcapMaterial = true;
  30215. this.defines = { 'MATCAP': '' };
  30216. this.type = 'MeshMatcapMaterial';
  30217. /**
  30218. * Color of the material.
  30219. *
  30220. * @type {Color}
  30221. * @default (1,1,1)
  30222. */
  30223. this.color = new Color( 0xffffff ); // diffuse
  30224. /**
  30225. * The matcap map.
  30226. *
  30227. * `matcap` represents luminance data, and the texture must be assigned
  30228. * a {@link Texture#colorSpace}. HDR `matcap` textures (e.g. `.exr`)
  30229. * typically set `texture.colorSpace = LinearSRGBColorSpace`, while LDR
  30230. * `matcap` textures (e.g. `.png`, `.jpg`, `.webp`) typically set
  30231. * `texture.colorSpace = SRGBColorSpace`.
  30232. *
  30233. * @type {?Texture}
  30234. * @default null
  30235. */
  30236. this.matcap = null;
  30237. /**
  30238. * The color map. May optionally include an alpha channel, typically combined
  30239. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30240. * color is modulated by the diffuse `color`.
  30241. *
  30242. * `map` represents color data, and the texture must be assigned a
  30243. * {@link Texture#colorSpace}. Most `map` textures set
  30244. * `texture.colorSpace = SRGBColorSpace`.
  30245. *
  30246. * @type {?Texture}
  30247. * @default null
  30248. */
  30249. this.map = null;
  30250. /**
  30251. * The texture to create a bump map. The black and white values map to the
  30252. * perceived depth in relation to the lights. Bump doesn't actually affect
  30253. * the geometry of the object, only the lighting. If a normal map is defined
  30254. * this will be ignored.
  30255. *
  30256. * `bumpMap` represents non-color data. Any texture assigned must have
  30257. * `texture.colorSpace = NoColorSpace` (default).
  30258. *
  30259. * @type {?Texture}
  30260. * @default null
  30261. */
  30262. this.bumpMap = null;
  30263. /**
  30264. * How much the bump map affects the material. Typical range is `[0,1]`.
  30265. *
  30266. * @type {number}
  30267. * @default 1
  30268. */
  30269. this.bumpScale = 1;
  30270. /**
  30271. * The texture to create a normal map. The RGB values affect the surface
  30272. * normal for each pixel fragment and change the way the color is lit. Normal
  30273. * maps do not change the actual shape of the surface, only the lighting. In
  30274. * case the material has a normal map authored using the left handed
  30275. * convention, the `y` component of `normalScale` should be negated to compensate
  30276. * for the different handedness.
  30277. *
  30278. * `normalMap` represents non-color data. Any texture assigned must have
  30279. * `texture.colorSpace = NoColorSpace` (default).
  30280. *
  30281. * @type {?Texture}
  30282. * @default null
  30283. */
  30284. this.normalMap = null;
  30285. /**
  30286. * The type of normal map.
  30287. *
  30288. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30289. * @default TangentSpaceNormalMap
  30290. */
  30291. this.normalMapType = TangentSpaceNormalMap;
  30292. /**
  30293. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30294. *
  30295. * @type {Vector2}
  30296. * @default (1,1)
  30297. */
  30298. this.normalScale = new Vector2( 1, 1 );
  30299. /**
  30300. * The displacement map affects the position of the mesh's vertices. Unlike
  30301. * other maps which only affect the light and shade of the material the
  30302. * displaced vertices can cast shadows, block other objects, and otherwise
  30303. * act as real geometry. The displacement texture is an image where the value
  30304. * of each pixel (white being the highest) is mapped against, and
  30305. * repositions, the vertices of the mesh. For best results, pair a
  30306. * displacement map with a matching normal map, since the renderer can
  30307. * not recompute surface normals from the displaced vertices.
  30308. *
  30309. * `displacementMap` represents non-color data. Any texture assigned must have
  30310. * `texture.colorSpace = NoColorSpace` (default).
  30311. *
  30312. * @type {?Texture}
  30313. * @default null
  30314. */
  30315. this.displacementMap = null;
  30316. /**
  30317. * How much the displacement map affects the mesh (where black is no
  30318. * displacement, and white is maximum displacement). Without a displacement
  30319. * map set, this value is not applied.
  30320. *
  30321. * @type {number}
  30322. * @default 0
  30323. */
  30324. this.displacementScale = 1;
  30325. /**
  30326. * The offset of the displacement map's values on the mesh's vertices.
  30327. * The bias is added to the scaled sample of the displacement map.
  30328. * Without a displacement map set, this value is not applied.
  30329. *
  30330. * @type {number}
  30331. * @default 0
  30332. */
  30333. this.displacementBias = 0;
  30334. /**
  30335. * The alpha map is a grayscale texture that controls the opacity across the
  30336. * surface (black: fully transparent; white: fully opaque).
  30337. *
  30338. * Only the color of the texture is used, ignoring the alpha channel if one
  30339. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30340. * when sampling this texture due to the extra bit of precision provided for
  30341. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30342. * luminance/alpha textures will also still work as expected.
  30343. *
  30344. * `alphaMap` represents non-color data. Any texture assigned must have
  30345. * `texture.colorSpace = NoColorSpace` (default).
  30346. *
  30347. * @type {?Texture}
  30348. * @default null
  30349. */
  30350. this.alphaMap = null;
  30351. /**
  30352. * Renders the geometry as a wireframe.
  30353. *
  30354. * @type {boolean}
  30355. * @default false
  30356. */
  30357. this.wireframe = false;
  30358. /**
  30359. * Controls the thickness of the wireframe.
  30360. *
  30361. * Can only be used with {@link SVGRenderer}.
  30362. *
  30363. * @type {number}
  30364. * @default 1
  30365. */
  30366. this.wireframeLinewidth = 1;
  30367. /**
  30368. * Whether the material is rendered with flat shading or not.
  30369. *
  30370. * @type {boolean}
  30371. * @default false
  30372. */
  30373. this.flatShading = false;
  30374. /**
  30375. * Whether the material is affected by fog or not.
  30376. *
  30377. * @type {boolean}
  30378. * @default true
  30379. */
  30380. this.fog = true;
  30381. this.setValues( parameters );
  30382. }
  30383. copy( source ) {
  30384. super.copy( source );
  30385. this.defines = { 'MATCAP': '' };
  30386. this.color.copy( source.color );
  30387. this.matcap = source.matcap;
  30388. this.map = source.map;
  30389. this.bumpMap = source.bumpMap;
  30390. this.bumpScale = source.bumpScale;
  30391. this.normalMap = source.normalMap;
  30392. this.normalMapType = source.normalMapType;
  30393. this.normalScale.copy( source.normalScale );
  30394. this.displacementMap = source.displacementMap;
  30395. this.displacementScale = source.displacementScale;
  30396. this.displacementBias = source.displacementBias;
  30397. this.alphaMap = source.alphaMap;
  30398. this.wireframe = source.wireframe;
  30399. this.wireframeLinewidth = source.wireframeLinewidth;
  30400. this.flatShading = source.flatShading;
  30401. this.fog = source.fog;
  30402. return this;
  30403. }
  30404. }
  30405. /**
  30406. * A material for rendering line primitives.
  30407. *
  30408. * Materials define the appearance of renderable 3D objects.
  30409. *
  30410. * ```js
  30411. * const material = new THREE.LineDashedMaterial( {
  30412. * color: 0xffffff,
  30413. * scale: 1,
  30414. * dashSize: 3,
  30415. * gapSize: 1,
  30416. * } );
  30417. * ```
  30418. *
  30419. * @augments LineBasicMaterial
  30420. */
  30421. class LineDashedMaterial extends LineBasicMaterial {
  30422. /**
  30423. * Constructs a new line dashed material.
  30424. *
  30425. * @param {Object} [parameters] - An object with one or more properties
  30426. * defining the material's appearance. Any property of the material
  30427. * (including any property from inherited materials) can be passed
  30428. * in here. Color values can be passed any type of value accepted
  30429. * by {@link Color#set}.
  30430. */
  30431. constructor( parameters ) {
  30432. super();
  30433. /**
  30434. * This flag can be used for type testing.
  30435. *
  30436. * @type {boolean}
  30437. * @readonly
  30438. * @default true
  30439. */
  30440. this.isLineDashedMaterial = true;
  30441. this.type = 'LineDashedMaterial';
  30442. /**
  30443. * The scale of the dashed part of a line.
  30444. *
  30445. * @type {number}
  30446. * @default 1
  30447. */
  30448. this.scale = 1;
  30449. /**
  30450. * The size of the dash. This is both the gap with the stroke.
  30451. *
  30452. * @type {number}
  30453. * @default 3
  30454. */
  30455. this.dashSize = 3;
  30456. /**
  30457. * The size of the gap.
  30458. *
  30459. * @type {number}
  30460. * @default 1
  30461. */
  30462. this.gapSize = 1;
  30463. this.setValues( parameters );
  30464. }
  30465. copy( source ) {
  30466. super.copy( source );
  30467. this.scale = source.scale;
  30468. this.dashSize = source.dashSize;
  30469. this.gapSize = source.gapSize;
  30470. return this;
  30471. }
  30472. }
  30473. /**
  30474. * Converts an array to a specific type.
  30475. *
  30476. * @param {TypedArray|Array} array - The array to convert.
  30477. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30478. * @return {TypedArray} The converted array.
  30479. */
  30480. function convertArray( array, type ) {
  30481. if ( ! array || array.constructor === type ) return array;
  30482. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30483. return new type( array ); // create typed array
  30484. }
  30485. return Array.prototype.slice.call( array ); // create Array
  30486. }
  30487. /**
  30488. * Returns an array by which times and values can be sorted.
  30489. *
  30490. * @param {Array<number>} times - The keyframe time values.
  30491. * @return {Array<number>} The array.
  30492. */
  30493. function getKeyframeOrder( times ) {
  30494. function compareTime( i, j ) {
  30495. return times[ i ] - times[ j ];
  30496. }
  30497. const n = times.length;
  30498. const result = new Array( n );
  30499. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30500. result.sort( compareTime );
  30501. return result;
  30502. }
  30503. /**
  30504. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30505. *
  30506. * @param {Array<number>} values - The values to sort.
  30507. * @param {number} stride - The stride.
  30508. * @param {Array<number>} order - The sort order.
  30509. * @return {Array<number>} The sorted values.
  30510. */
  30511. function sortedArray( values, stride, order ) {
  30512. const nValues = values.length;
  30513. const result = new values.constructor( nValues );
  30514. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30515. const srcOffset = order[ i ] * stride;
  30516. for ( let j = 0; j !== stride; ++ j ) {
  30517. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30518. }
  30519. }
  30520. return result;
  30521. }
  30522. /**
  30523. * Used for parsing AOS keyframe formats.
  30524. *
  30525. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30526. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30527. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30528. * @param {string} valuePropertyName - The name of the property to use.
  30529. */
  30530. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30531. let i = 1, key = jsonKeys[ 0 ];
  30532. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30533. key = jsonKeys[ i ++ ];
  30534. }
  30535. if ( key === undefined ) return; // no data
  30536. let value = key[ valuePropertyName ];
  30537. if ( value === undefined ) return; // no data
  30538. if ( Array.isArray( value ) ) {
  30539. do {
  30540. value = key[ valuePropertyName ];
  30541. if ( value !== undefined ) {
  30542. times.push( key.time );
  30543. values.push( ...value ); // push all elements
  30544. }
  30545. key = jsonKeys[ i ++ ];
  30546. } while ( key !== undefined );
  30547. } else if ( value.toArray !== undefined ) {
  30548. // ...assume THREE.Math-ish
  30549. do {
  30550. value = key[ valuePropertyName ];
  30551. if ( value !== undefined ) {
  30552. times.push( key.time );
  30553. value.toArray( values, values.length );
  30554. }
  30555. key = jsonKeys[ i ++ ];
  30556. } while ( key !== undefined );
  30557. } else {
  30558. // otherwise push as-is
  30559. do {
  30560. value = key[ valuePropertyName ];
  30561. if ( value !== undefined ) {
  30562. times.push( key.time );
  30563. values.push( value );
  30564. }
  30565. key = jsonKeys[ i ++ ];
  30566. } while ( key !== undefined );
  30567. }
  30568. }
  30569. /**
  30570. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30571. *
  30572. * @param {AnimationClip} sourceClip - The values to sort.
  30573. * @param {string} name - The name of the clip.
  30574. * @param {number} startFrame - The start frame.
  30575. * @param {number} endFrame - The end frame.
  30576. * @param {number} [fps=30] - The FPS.
  30577. * @return {AnimationClip} The new sub clip.
  30578. */
  30579. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30580. const clip = sourceClip.clone();
  30581. clip.name = name;
  30582. const tracks = [];
  30583. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30584. const track = clip.tracks[ i ];
  30585. const valueSize = track.getValueSize();
  30586. const times = [];
  30587. const values = [];
  30588. for ( let j = 0; j < track.times.length; ++ j ) {
  30589. const frame = track.times[ j ] * fps;
  30590. if ( frame < startFrame || frame >= endFrame ) continue;
  30591. times.push( track.times[ j ] );
  30592. for ( let k = 0; k < valueSize; ++ k ) {
  30593. values.push( track.values[ j * valueSize + k ] );
  30594. }
  30595. }
  30596. if ( times.length === 0 ) continue;
  30597. track.times = convertArray( times, track.times.constructor );
  30598. track.values = convertArray( values, track.values.constructor );
  30599. tracks.push( track );
  30600. }
  30601. clip.tracks = tracks;
  30602. // find minimum .times value across all tracks in the trimmed clip
  30603. let minStartTime = Infinity;
  30604. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30605. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30606. minStartTime = clip.tracks[ i ].times[ 0 ];
  30607. }
  30608. }
  30609. // shift all tracks such that clip begins at t=0
  30610. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30611. clip.tracks[ i ].shift( -1 * minStartTime );
  30612. }
  30613. clip.resetDuration();
  30614. return clip;
  30615. }
  30616. /**
  30617. * Converts the keyframes of the given animation clip to an additive format.
  30618. *
  30619. * @param {AnimationClip} targetClip - The clip to make additive.
  30620. * @param {number} [referenceFrame=0] - The reference frame.
  30621. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30622. * @param {number} [fps=30] - The FPS.
  30623. * @return {AnimationClip} The updated clip which is now additive.
  30624. */
  30625. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30626. if ( fps <= 0 ) fps = 30;
  30627. const numTracks = referenceClip.tracks.length;
  30628. const referenceTime = referenceFrame / fps;
  30629. // Make each track's values relative to the values at the reference frame
  30630. for ( let i = 0; i < numTracks; ++ i ) {
  30631. const referenceTrack = referenceClip.tracks[ i ];
  30632. const referenceTrackType = referenceTrack.ValueTypeName;
  30633. // Skip this track if it's non-numeric
  30634. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30635. // Find the track in the target clip whose name and type matches the reference track
  30636. const targetTrack = targetClip.tracks.find( function ( track ) {
  30637. return track.name === referenceTrack.name
  30638. && track.ValueTypeName === referenceTrackType;
  30639. } );
  30640. if ( targetTrack === undefined ) continue;
  30641. let referenceOffset = 0;
  30642. const referenceValueSize = referenceTrack.getValueSize();
  30643. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30644. referenceOffset = referenceValueSize / 3;
  30645. }
  30646. let targetOffset = 0;
  30647. const targetValueSize = targetTrack.getValueSize();
  30648. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30649. targetOffset = targetValueSize / 3;
  30650. }
  30651. const lastIndex = referenceTrack.times.length - 1;
  30652. let referenceValue;
  30653. // Find the value to subtract out of the track
  30654. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30655. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30656. const startIndex = referenceOffset;
  30657. const endIndex = referenceValueSize - referenceOffset;
  30658. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30659. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30660. // Reference frame is after the last keyframe, so just use the last keyframe
  30661. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30662. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30663. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30664. } else {
  30665. // Interpolate to the reference value
  30666. const interpolant = referenceTrack.createInterpolant();
  30667. const startIndex = referenceOffset;
  30668. const endIndex = referenceValueSize - referenceOffset;
  30669. interpolant.evaluate( referenceTime );
  30670. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30671. }
  30672. // Conjugate the quaternion
  30673. if ( referenceTrackType === 'quaternion' ) {
  30674. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30675. referenceQuat.toArray( referenceValue );
  30676. }
  30677. // Subtract the reference value from all of the track values
  30678. const numTimes = targetTrack.times.length;
  30679. for ( let j = 0; j < numTimes; ++ j ) {
  30680. const valueStart = j * targetValueSize + targetOffset;
  30681. if ( referenceTrackType === 'quaternion' ) {
  30682. // Multiply the conjugate for quaternion track types
  30683. Quaternion.multiplyQuaternionsFlat(
  30684. targetTrack.values,
  30685. valueStart,
  30686. referenceValue,
  30687. 0,
  30688. targetTrack.values,
  30689. valueStart
  30690. );
  30691. } else {
  30692. const valueEnd = targetValueSize - targetOffset * 2;
  30693. // Subtract each value for all other numeric track types
  30694. for ( let k = 0; k < valueEnd; ++ k ) {
  30695. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30696. }
  30697. }
  30698. }
  30699. }
  30700. targetClip.blendMode = AdditiveAnimationBlendMode;
  30701. return targetClip;
  30702. }
  30703. /**
  30704. * A class with various methods to assist with animations.
  30705. *
  30706. * @hideconstructor
  30707. */
  30708. class AnimationUtils {
  30709. /**
  30710. * Converts an array to a specific type
  30711. *
  30712. * @static
  30713. * @param {TypedArray|Array} array - The array to convert.
  30714. * @param {TypedArray.constructor} type - The constructor of a type array.
  30715. * @return {TypedArray} The converted array
  30716. */
  30717. static convertArray( array, type ) {
  30718. return convertArray( array, type );
  30719. }
  30720. /**
  30721. * Returns `true` if the given object is a typed array.
  30722. *
  30723. * @static
  30724. * @param {any} object - The object to check.
  30725. * @return {boolean} Whether the given object is a typed array.
  30726. */
  30727. static isTypedArray( object ) {
  30728. return isTypedArray( object );
  30729. }
  30730. /**
  30731. * Returns an array by which times and values can be sorted.
  30732. *
  30733. * @static
  30734. * @param {Array<number>} times - The keyframe time values.
  30735. * @return {Array<number>} The array.
  30736. */
  30737. static getKeyframeOrder( times ) {
  30738. return getKeyframeOrder( times );
  30739. }
  30740. /**
  30741. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30742. *
  30743. * @static
  30744. * @param {Array<number>} values - The values to sort.
  30745. * @param {number} stride - The stride.
  30746. * @param {Array<number>} order - The sort order.
  30747. * @return {Array<number>} The sorted values.
  30748. */
  30749. static sortedArray( values, stride, order ) {
  30750. return sortedArray( values, stride, order );
  30751. }
  30752. /**
  30753. * Used for parsing AOS keyframe formats.
  30754. *
  30755. * @static
  30756. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30757. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30758. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30759. * @param {string} valuePropertyName - The name of the property to use.
  30760. */
  30761. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30762. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30763. }
  30764. /**
  30765. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30766. *
  30767. * @static
  30768. * @param {AnimationClip} sourceClip - The values to sort.
  30769. * @param {string} name - The name of the clip.
  30770. * @param {number} startFrame - The start frame.
  30771. * @param {number} endFrame - The end frame.
  30772. * @param {number} [fps=30] - The FPS.
  30773. * @return {AnimationClip} The new sub clip.
  30774. */
  30775. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30776. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30777. }
  30778. /**
  30779. * Converts the keyframes of the given animation clip to an additive format.
  30780. *
  30781. * @static
  30782. * @param {AnimationClip} targetClip - The clip to make additive.
  30783. * @param {number} [referenceFrame=0] - The reference frame.
  30784. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30785. * @param {number} [fps=30] - The FPS.
  30786. * @return {AnimationClip} The updated clip which is now additive.
  30787. */
  30788. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30789. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30790. }
  30791. }
  30792. /**
  30793. * Abstract base class of interpolants over parametric samples.
  30794. *
  30795. * The parameter domain is one dimensional, typically the time or a path
  30796. * along a curve defined by the data.
  30797. *
  30798. * The sample values can have any dimensionality and derived classes may
  30799. * apply special interpretations to the data.
  30800. *
  30801. * This class provides the interval seek in a Template Method, deferring
  30802. * the actual interpolation to derived classes.
  30803. *
  30804. * Time complexity is O(1) for linear access crossing at most two points
  30805. * and O(log N) for random access, where N is the number of positions.
  30806. *
  30807. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30808. *
  30809. * @abstract
  30810. */
  30811. class Interpolant {
  30812. /**
  30813. * Constructs a new interpolant.
  30814. *
  30815. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30816. * @param {TypedArray} sampleValues - The sample values.
  30817. * @param {number} sampleSize - The sample size
  30818. * @param {TypedArray} [resultBuffer] - The result buffer.
  30819. */
  30820. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30821. /**
  30822. * The parameter positions.
  30823. *
  30824. * @type {TypedArray}
  30825. */
  30826. this.parameterPositions = parameterPositions;
  30827. /**
  30828. * A cache index.
  30829. *
  30830. * @private
  30831. * @type {number}
  30832. * @default 0
  30833. */
  30834. this._cachedIndex = 0;
  30835. /**
  30836. * The result buffer.
  30837. *
  30838. * @type {TypedArray}
  30839. */
  30840. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30841. /**
  30842. * The sample values.
  30843. *
  30844. * @type {TypedArray}
  30845. */
  30846. this.sampleValues = sampleValues;
  30847. /**
  30848. * The value size.
  30849. *
  30850. * @type {TypedArray}
  30851. */
  30852. this.valueSize = sampleSize;
  30853. /**
  30854. * The interpolation settings.
  30855. *
  30856. * @type {?Object}
  30857. * @default null
  30858. */
  30859. this.settings = null;
  30860. /**
  30861. * The default settings object.
  30862. *
  30863. * @type {Object}
  30864. */
  30865. this.DefaultSettings_ = {};
  30866. }
  30867. /**
  30868. * Evaluate the interpolant at position `t`.
  30869. *
  30870. * @param {number} t - The interpolation factor.
  30871. * @return {TypedArray} The result buffer.
  30872. */
  30873. evaluate( t ) {
  30874. const pp = this.parameterPositions;
  30875. let i1 = this._cachedIndex,
  30876. t1 = pp[ i1 ],
  30877. t0 = pp[ i1 - 1 ];
  30878. validate_interval: {
  30879. seek: {
  30880. let right;
  30881. linear_scan: {
  30882. //- See http://jsperf.com/comparison-to-undefined/3
  30883. //- slower code:
  30884. //-
  30885. //- if ( t >= t1 || t1 === undefined ) {
  30886. forward_scan: if ( ! ( t < t1 ) ) {
  30887. for ( let giveUpAt = i1 + 2; ; ) {
  30888. if ( t1 === undefined ) {
  30889. if ( t < t0 ) break forward_scan;
  30890. // after end
  30891. i1 = pp.length;
  30892. this._cachedIndex = i1;
  30893. return this.copySampleValue_( i1 - 1 );
  30894. }
  30895. if ( i1 === giveUpAt ) break; // this loop
  30896. t0 = t1;
  30897. t1 = pp[ ++ i1 ];
  30898. if ( t < t1 ) {
  30899. // we have arrived at the sought interval
  30900. break seek;
  30901. }
  30902. }
  30903. // prepare binary search on the right side of the index
  30904. right = pp.length;
  30905. break linear_scan;
  30906. }
  30907. //- slower code:
  30908. //- if ( t < t0 || t0 === undefined ) {
  30909. if ( ! ( t >= t0 ) ) {
  30910. // looping?
  30911. const t1global = pp[ 1 ];
  30912. if ( t < t1global ) {
  30913. i1 = 2; // + 1, using the scan for the details
  30914. t0 = t1global;
  30915. }
  30916. // linear reverse scan
  30917. for ( let giveUpAt = i1 - 2; ; ) {
  30918. if ( t0 === undefined ) {
  30919. // before start
  30920. this._cachedIndex = 0;
  30921. return this.copySampleValue_( 0 );
  30922. }
  30923. if ( i1 === giveUpAt ) break; // this loop
  30924. t1 = t0;
  30925. t0 = pp[ -- i1 - 1 ];
  30926. if ( t >= t0 ) {
  30927. // we have arrived at the sought interval
  30928. break seek;
  30929. }
  30930. }
  30931. // prepare binary search on the left side of the index
  30932. right = i1;
  30933. i1 = 0;
  30934. break linear_scan;
  30935. }
  30936. // the interval is valid
  30937. break validate_interval;
  30938. } // linear scan
  30939. // binary search
  30940. while ( i1 < right ) {
  30941. const mid = ( i1 + right ) >>> 1;
  30942. if ( t < pp[ mid ] ) {
  30943. right = mid;
  30944. } else {
  30945. i1 = mid + 1;
  30946. }
  30947. }
  30948. t1 = pp[ i1 ];
  30949. t0 = pp[ i1 - 1 ];
  30950. // check boundary cases, again
  30951. if ( t0 === undefined ) {
  30952. this._cachedIndex = 0;
  30953. return this.copySampleValue_( 0 );
  30954. }
  30955. if ( t1 === undefined ) {
  30956. i1 = pp.length;
  30957. this._cachedIndex = i1;
  30958. return this.copySampleValue_( i1 - 1 );
  30959. }
  30960. } // seek
  30961. this._cachedIndex = i1;
  30962. this.intervalChanged_( i1, t0, t1 );
  30963. } // validate_interval
  30964. return this.interpolate_( i1, t0, t, t1 );
  30965. }
  30966. /**
  30967. * Returns the interpolation settings.
  30968. *
  30969. * @return {Object} The interpolation settings.
  30970. */
  30971. getSettings_() {
  30972. return this.settings || this.DefaultSettings_;
  30973. }
  30974. /**
  30975. * Copies a sample value to the result buffer.
  30976. *
  30977. * @param {number} index - An index into the sample value buffer.
  30978. * @return {TypedArray} The result buffer.
  30979. */
  30980. copySampleValue_( index ) {
  30981. // copies a sample value to the result buffer
  30982. const result = this.resultBuffer,
  30983. values = this.sampleValues,
  30984. stride = this.valueSize,
  30985. offset = index * stride;
  30986. for ( let i = 0; i !== stride; ++ i ) {
  30987. result[ i ] = values[ offset + i ];
  30988. }
  30989. return result;
  30990. }
  30991. /**
  30992. * Copies a sample value to the result buffer.
  30993. *
  30994. * @abstract
  30995. * @param {number} i1 - An index into the sample value buffer.
  30996. * @param {number} t0 - The previous interpolation factor.
  30997. * @param {number} t - The current interpolation factor.
  30998. * @param {number} t1 - The next interpolation factor.
  30999. * @return {TypedArray} The result buffer.
  31000. */
  31001. interpolate_( /* i1, t0, t, t1 */ ) {
  31002. throw new Error( 'THREE.Interpolant: Call to abstract method.' );
  31003. // implementations shall return this.resultBuffer
  31004. }
  31005. /**
  31006. * Optional method that is executed when the interval has changed.
  31007. *
  31008. * @param {number} i1 - An index into the sample value buffer.
  31009. * @param {number} t0 - The previous interpolation factor.
  31010. * @param {number} t - The current interpolation factor.
  31011. */
  31012. intervalChanged_( /* i1, t0, t1 */ ) {
  31013. // empty
  31014. }
  31015. }
  31016. /**
  31017. * Fast and simple cubic spline interpolant.
  31018. *
  31019. * It was derived from a Hermitian construction setting the first derivative
  31020. * at each sample position to the linear slope between neighboring positions
  31021. * over their parameter interval.
  31022. *
  31023. * @augments Interpolant
  31024. */
  31025. class CubicInterpolant extends Interpolant {
  31026. /**
  31027. * Constructs a new cubic interpolant.
  31028. *
  31029. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31030. * @param {TypedArray} sampleValues - The sample values.
  31031. * @param {number} sampleSize - The sample size
  31032. * @param {TypedArray} [resultBuffer] - The result buffer.
  31033. */
  31034. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31035. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31036. this._weightPrev = -0;
  31037. this._offsetPrev = -0;
  31038. this._weightNext = -0;
  31039. this._offsetNext = -0;
  31040. this.DefaultSettings_ = {
  31041. endingStart: ZeroCurvatureEnding,
  31042. endingEnd: ZeroCurvatureEnding
  31043. };
  31044. }
  31045. intervalChanged_( i1, t0, t1 ) {
  31046. const pp = this.parameterPositions;
  31047. let iPrev = i1 - 2,
  31048. iNext = i1 + 1,
  31049. tPrev = pp[ iPrev ],
  31050. tNext = pp[ iNext ];
  31051. if ( tPrev === undefined ) {
  31052. switch ( this.getSettings_().endingStart ) {
  31053. case ZeroSlopeEnding:
  31054. // f'(t0) = 0
  31055. iPrev = i1;
  31056. tPrev = 2 * t0 - t1;
  31057. break;
  31058. case WrapAroundEnding:
  31059. // use the other end of the curve
  31060. iPrev = pp.length - 2;
  31061. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  31062. break;
  31063. default: // ZeroCurvatureEnding
  31064. // f''(t0) = 0 a.k.a. Natural Spline
  31065. iPrev = i1;
  31066. tPrev = t1;
  31067. }
  31068. }
  31069. if ( tNext === undefined ) {
  31070. switch ( this.getSettings_().endingEnd ) {
  31071. case ZeroSlopeEnding:
  31072. // f'(tN) = 0
  31073. iNext = i1;
  31074. tNext = 2 * t1 - t0;
  31075. break;
  31076. case WrapAroundEnding:
  31077. // use the other end of the curve
  31078. iNext = 1;
  31079. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  31080. break;
  31081. default: // ZeroCurvatureEnding
  31082. // f''(tN) = 0, a.k.a. Natural Spline
  31083. iNext = i1 - 1;
  31084. tNext = t0;
  31085. }
  31086. }
  31087. const halfDt = ( t1 - t0 ) * 0.5,
  31088. stride = this.valueSize;
  31089. this._weightPrev = halfDt / ( t0 - tPrev );
  31090. this._weightNext = halfDt / ( tNext - t1 );
  31091. this._offsetPrev = iPrev * stride;
  31092. this._offsetNext = iNext * stride;
  31093. }
  31094. interpolate_( i1, t0, t, t1 ) {
  31095. const result = this.resultBuffer,
  31096. values = this.sampleValues,
  31097. stride = this.valueSize,
  31098. o1 = i1 * stride, o0 = o1 - stride,
  31099. oP = this._offsetPrev, oN = this._offsetNext,
  31100. wP = this._weightPrev, wN = this._weightNext,
  31101. p = ( t - t0 ) / ( t1 - t0 ),
  31102. pp = p * p,
  31103. ppp = pp * p;
  31104. // evaluate polynomials
  31105. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  31106. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  31107. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  31108. const sN = wN * ppp - wN * pp;
  31109. // combine data linearly
  31110. for ( let i = 0; i !== stride; ++ i ) {
  31111. result[ i ] =
  31112. sP * values[ oP + i ] +
  31113. s0 * values[ o0 + i ] +
  31114. s1 * values[ o1 + i ] +
  31115. sN * values[ oN + i ];
  31116. }
  31117. return result;
  31118. }
  31119. }
  31120. /**
  31121. * A basic linear interpolant.
  31122. *
  31123. * @augments Interpolant
  31124. */
  31125. class LinearInterpolant extends Interpolant {
  31126. /**
  31127. * Constructs a new linear interpolant.
  31128. *
  31129. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31130. * @param {TypedArray} sampleValues - The sample values.
  31131. * @param {number} sampleSize - The sample size
  31132. * @param {TypedArray} [resultBuffer] - The result buffer.
  31133. */
  31134. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31135. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31136. }
  31137. interpolate_( i1, t0, t, t1 ) {
  31138. const result = this.resultBuffer,
  31139. values = this.sampleValues,
  31140. stride = this.valueSize,
  31141. offset1 = i1 * stride,
  31142. offset0 = offset1 - stride,
  31143. weight1 = ( t - t0 ) / ( t1 - t0 ),
  31144. weight0 = 1 - weight1;
  31145. for ( let i = 0; i !== stride; ++ i ) {
  31146. result[ i ] =
  31147. values[ offset0 + i ] * weight0 +
  31148. values[ offset1 + i ] * weight1;
  31149. }
  31150. return result;
  31151. }
  31152. }
  31153. /**
  31154. * Interpolant that evaluates to the sample value at the position preceding
  31155. * the parameter.
  31156. *
  31157. * @augments Interpolant
  31158. */
  31159. class DiscreteInterpolant extends Interpolant {
  31160. /**
  31161. * Constructs a new discrete interpolant.
  31162. *
  31163. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31164. * @param {TypedArray} sampleValues - The sample values.
  31165. * @param {number} sampleSize - The sample size
  31166. * @param {TypedArray} [resultBuffer] - The result buffer.
  31167. */
  31168. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31169. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31170. }
  31171. interpolate_( i1 /*, t0, t, t1 */ ) {
  31172. return this.copySampleValue_( i1 - 1 );
  31173. }
  31174. }
  31175. /**
  31176. * A Bezier interpolant using cubic Bezier curves with 2D control points.
  31177. *
  31178. * This interpolant supports the COLLADA/Maya style of Bezier animation where
  31179. * each keyframe has explicit in/out tangent control points specified as
  31180. * 2D coordinates (time, value).
  31181. *
  31182. * Tangent data is read from `inTangents` and `outTangents` on the interpolant
  31183. * (populated by `KeyframeTrack.InterpolantFactoryMethodBezier`).
  31184. *
  31185. * For a track with N keyframes and stride S:
  31186. * - Each tangent array has N * S * 2 values
  31187. * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value,
  31188. * k1_c0_time, k1_c0_value, ...]
  31189. *
  31190. * @augments Interpolant
  31191. */
  31192. class BezierInterpolant extends Interpolant {
  31193. interpolate_( i1, t0, t, t1 ) {
  31194. const result = this.resultBuffer;
  31195. const values = this.sampleValues;
  31196. const stride = this.valueSize;
  31197. const offset1 = i1 * stride;
  31198. const offset0 = offset1 - stride;
  31199. const inTangents = this.inTangents;
  31200. const outTangents = this.outTangents;
  31201. // If no tangent data, fall back to linear interpolation
  31202. if ( ! inTangents || ! outTangents ) {
  31203. const weight1 = ( t - t0 ) / ( t1 - t0 );
  31204. const weight0 = 1 - weight1;
  31205. for ( let i = 0; i !== stride; ++ i ) {
  31206. result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1;
  31207. }
  31208. return result;
  31209. }
  31210. const tangentStride = stride * 2;
  31211. const i0 = i1 - 1;
  31212. for ( let i = 0; i !== stride; ++ i ) {
  31213. const v0 = values[ offset0 + i ];
  31214. const v1 = values[ offset1 + i ];
  31215. // outTangent of previous keyframe (C0)
  31216. const outTangentOffset = i0 * tangentStride + i * 2;
  31217. const c0x = outTangents[ outTangentOffset ];
  31218. const c0y = outTangents[ outTangentOffset + 1 ];
  31219. // inTangent of current keyframe (C1)
  31220. const inTangentOffset = i1 * tangentStride + i * 2;
  31221. const c1x = inTangents[ inTangentOffset ];
  31222. const c1y = inTangents[ inTangentOffset + 1 ];
  31223. // Solve for Bezier parameter s where Bx(s) = t using Newton-Raphson
  31224. let s = ( t - t0 ) / ( t1 - t0 );
  31225. let s2, s3, oneMinusS, oneMinusS2, oneMinusS3;
  31226. for ( let iter = 0; iter < 8; iter ++ ) {
  31227. s2 = s * s;
  31228. s3 = s2 * s;
  31229. oneMinusS = 1 - s;
  31230. oneMinusS2 = oneMinusS * oneMinusS;
  31231. oneMinusS3 = oneMinusS2 * oneMinusS;
  31232. // Bezier X(s) = (1-s)³·t0 + 3(1-s)²s·c0x + 3(1-s)s²·c1x + s³·t1
  31233. const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1;
  31234. const error = bx - t;
  31235. if ( Math.abs( error ) < 1e-10 ) break;
  31236. // Derivative dX/ds
  31237. const dbx = 3 * oneMinusS2 * ( c0x - t0 ) + 6 * oneMinusS * s * ( c1x - c0x ) + 3 * s2 * ( t1 - c1x );
  31238. if ( Math.abs( dbx ) < 1e-10 ) break;
  31239. s = s - error / dbx;
  31240. s = Math.max( 0, Math.min( 1, s ) );
  31241. }
  31242. // Evaluate Bezier Y(s)
  31243. result[ i ] = oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1;
  31244. }
  31245. return result;
  31246. }
  31247. }
  31248. /**
  31249. * Represents a timed sequence of keyframes, which are composed of lists of
  31250. * times and related values, and which are used to animate a specific property
  31251. * of an object.
  31252. */
  31253. class KeyframeTrack {
  31254. /**
  31255. * Constructs a new keyframe track.
  31256. *
  31257. * @param {string} name - The keyframe track's name.
  31258. * @param {Array<number>} times - A list of keyframe times.
  31259. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  31260. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type.
  31261. */
  31262. constructor( name, times, values, interpolation ) {
  31263. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  31264. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  31265. /**
  31266. * The track's name can refer to morph targets or bones or
  31267. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  31268. * for the forms of strings that can be parsed for property binding.
  31269. *
  31270. * @type {string}
  31271. */
  31272. this.name = name;
  31273. /**
  31274. * The keyframe times.
  31275. *
  31276. * @type {Float32Array}
  31277. */
  31278. this.times = convertArray( times, this.TimeBufferType );
  31279. /**
  31280. * The keyframe values.
  31281. *
  31282. * @type {Float32Array}
  31283. */
  31284. this.values = convertArray( values, this.ValueBufferType );
  31285. this.setInterpolation( interpolation || this.DefaultInterpolation );
  31286. }
  31287. /**
  31288. * Converts the keyframe track to JSON.
  31289. *
  31290. * @static
  31291. * @param {KeyframeTrack} track - The keyframe track to serialize.
  31292. * @return {Object} The serialized keyframe track as JSON.
  31293. */
  31294. static toJSON( track ) {
  31295. const trackType = track.constructor;
  31296. let json;
  31297. // derived classes can define a static toJSON method
  31298. if ( trackType.toJSON !== this.toJSON ) {
  31299. json = trackType.toJSON( track );
  31300. } else {
  31301. // by default, we assume the data can be serialized as-is
  31302. json = {
  31303. 'name': track.name,
  31304. 'times': convertArray( track.times, Array ),
  31305. 'values': convertArray( track.values, Array )
  31306. };
  31307. const interpolation = track.getInterpolation();
  31308. if ( interpolation !== track.DefaultInterpolation ) {
  31309. json.interpolation = interpolation;
  31310. }
  31311. }
  31312. json.type = track.ValueTypeName; // mandatory
  31313. return json;
  31314. }
  31315. /**
  31316. * Factory method for creating a new discrete interpolant.
  31317. *
  31318. * @static
  31319. * @param {TypedArray} [result] - The result buffer.
  31320. * @return {DiscreteInterpolant} The new interpolant.
  31321. */
  31322. InterpolantFactoryMethodDiscrete( result ) {
  31323. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31324. }
  31325. /**
  31326. * Factory method for creating a new linear interpolant.
  31327. *
  31328. * @static
  31329. * @param {TypedArray} [result] - The result buffer.
  31330. * @return {LinearInterpolant} The new interpolant.
  31331. */
  31332. InterpolantFactoryMethodLinear( result ) {
  31333. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31334. }
  31335. /**
  31336. * Factory method for creating a new smooth interpolant.
  31337. *
  31338. * @static
  31339. * @param {TypedArray} [result] - The result buffer.
  31340. * @return {CubicInterpolant} The new interpolant.
  31341. */
  31342. InterpolantFactoryMethodSmooth( result ) {
  31343. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31344. }
  31345. /**
  31346. * Factory method for creating a new Bezier interpolant.
  31347. *
  31348. * The Bezier interpolant requires tangent data to be set via the `settings` property
  31349. * on the track before creating the interpolant. The settings should contain:
  31350. * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component
  31351. * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component
  31352. *
  31353. * @static
  31354. * @param {TypedArray} [result] - The result buffer.
  31355. * @return {BezierInterpolant} The new interpolant.
  31356. */
  31357. InterpolantFactoryMethodBezier( result ) {
  31358. const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result );
  31359. if ( this.settings ) {
  31360. interpolant.inTangents = this.settings.inTangents;
  31361. interpolant.outTangents = this.settings.outTangents;
  31362. }
  31363. return interpolant;
  31364. }
  31365. /**
  31366. * Defines the interpolation factor method for this keyframe track.
  31367. *
  31368. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type.
  31369. * @return {KeyframeTrack} A reference to this keyframe track.
  31370. */
  31371. setInterpolation( interpolation ) {
  31372. let factoryMethod;
  31373. switch ( interpolation ) {
  31374. case InterpolateDiscrete:
  31375. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31376. break;
  31377. case InterpolateLinear:
  31378. factoryMethod = this.InterpolantFactoryMethodLinear;
  31379. break;
  31380. case InterpolateSmooth:
  31381. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31382. break;
  31383. case InterpolateBezier:
  31384. factoryMethod = this.InterpolantFactoryMethodBezier;
  31385. break;
  31386. }
  31387. if ( factoryMethod === undefined ) {
  31388. const message = 'unsupported interpolation for ' +
  31389. this.ValueTypeName + ' keyframe track named ' + this.name;
  31390. if ( this.createInterpolant === undefined ) {
  31391. // fall back to default, unless the default itself is messed up
  31392. if ( interpolation !== this.DefaultInterpolation ) {
  31393. this.setInterpolation( this.DefaultInterpolation );
  31394. } else {
  31395. throw new Error( message ); // fatal, in this case
  31396. }
  31397. }
  31398. warn( 'KeyframeTrack:', message );
  31399. return this;
  31400. }
  31401. this.createInterpolant = factoryMethod;
  31402. return this;
  31403. }
  31404. /**
  31405. * Returns the current interpolation type.
  31406. *
  31407. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type.
  31408. */
  31409. getInterpolation() {
  31410. switch ( this.createInterpolant ) {
  31411. case this.InterpolantFactoryMethodDiscrete:
  31412. return InterpolateDiscrete;
  31413. case this.InterpolantFactoryMethodLinear:
  31414. return InterpolateLinear;
  31415. case this.InterpolantFactoryMethodSmooth:
  31416. return InterpolateSmooth;
  31417. case this.InterpolantFactoryMethodBezier:
  31418. return InterpolateBezier;
  31419. }
  31420. }
  31421. /**
  31422. * Returns the value size.
  31423. *
  31424. * @return {number} The value size.
  31425. */
  31426. getValueSize() {
  31427. return this.values.length / this.times.length;
  31428. }
  31429. /**
  31430. * Moves all keyframes either forward or backward in time.
  31431. *
  31432. * @param {number} timeOffset - The offset to move the time values.
  31433. * @return {KeyframeTrack} A reference to this keyframe track.
  31434. */
  31435. shift( timeOffset ) {
  31436. if ( timeOffset !== 0.0 ) {
  31437. const times = this.times;
  31438. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31439. times[ i ] += timeOffset;
  31440. }
  31441. }
  31442. return this;
  31443. }
  31444. /**
  31445. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31446. *
  31447. * @param {number} timeScale - The time scale.
  31448. * @return {KeyframeTrack} A reference to this keyframe track.
  31449. */
  31450. scale( timeScale ) {
  31451. if ( timeScale !== 1.0 ) {
  31452. const times = this.times;
  31453. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31454. times[ i ] *= timeScale;
  31455. }
  31456. }
  31457. return this;
  31458. }
  31459. /**
  31460. * Removes keyframes before and after animation without changing any values within the defined time range.
  31461. *
  31462. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31463. * keys this will change their values
  31464. *
  31465. * @param {number} startTime - The start time.
  31466. * @param {number} endTime - The end time.
  31467. * @return {KeyframeTrack} A reference to this keyframe track.
  31468. */
  31469. trim( startTime, endTime ) {
  31470. const times = this.times,
  31471. nKeys = times.length;
  31472. let from = 0,
  31473. to = nKeys - 1;
  31474. while ( from !== nKeys && times[ from ] < startTime ) {
  31475. ++ from;
  31476. }
  31477. while ( to !== -1 && times[ to ] > endTime ) {
  31478. -- to;
  31479. }
  31480. ++ to; // inclusive -> exclusive bound
  31481. if ( from !== 0 || to !== nKeys ) {
  31482. // empty tracks are forbidden, so keep at least one keyframe
  31483. if ( from >= to ) {
  31484. to = Math.max( to, 1 );
  31485. from = to - 1;
  31486. }
  31487. const stride = this.getValueSize();
  31488. this.times = times.slice( from, to );
  31489. this.values = this.values.slice( from * stride, to * stride );
  31490. }
  31491. return this;
  31492. }
  31493. /**
  31494. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31495. * are valid.
  31496. *
  31497. * @return {boolean} Whether the keyframes are valid or not.
  31498. */
  31499. validate() {
  31500. let valid = true;
  31501. const valueSize = this.getValueSize();
  31502. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31503. error( 'KeyframeTrack: Invalid value size in track.', this );
  31504. valid = false;
  31505. }
  31506. const times = this.times,
  31507. values = this.values,
  31508. nKeys = times.length;
  31509. if ( nKeys === 0 ) {
  31510. error( 'KeyframeTrack: Track is empty.', this );
  31511. valid = false;
  31512. }
  31513. let prevTime = null;
  31514. for ( let i = 0; i !== nKeys; i ++ ) {
  31515. const currTime = times[ i ];
  31516. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31517. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31518. valid = false;
  31519. break;
  31520. }
  31521. if ( prevTime !== null && prevTime > currTime ) {
  31522. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31523. valid = false;
  31524. break;
  31525. }
  31526. prevTime = currTime;
  31527. }
  31528. if ( values !== undefined ) {
  31529. if ( isTypedArray( values ) ) {
  31530. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31531. const value = values[ i ];
  31532. if ( isNaN( value ) ) {
  31533. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31534. valid = false;
  31535. break;
  31536. }
  31537. }
  31538. }
  31539. }
  31540. return valid;
  31541. }
  31542. /**
  31543. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31544. * common in morph target sequences).
  31545. *
  31546. * @return {KeyframeTrack} A reference to this keyframe track.
  31547. */
  31548. optimize() {
  31549. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31550. // times or values may be shared with other tracks, so overwriting is unsafe
  31551. const times = this.times.slice(),
  31552. values = this.values.slice(),
  31553. stride = this.getValueSize(),
  31554. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31555. lastIndex = times.length - 1;
  31556. let writeIndex = 1;
  31557. for ( let i = 1; i < lastIndex; ++ i ) {
  31558. let keep = false;
  31559. const time = times[ i ];
  31560. const timeNext = times[ i + 1 ];
  31561. // remove adjacent keyframes scheduled at the same time
  31562. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31563. if ( ! smoothInterpolation ) {
  31564. // remove unnecessary keyframes same as their neighbors
  31565. const offset = i * stride,
  31566. offsetP = offset - stride,
  31567. offsetN = offset + stride;
  31568. for ( let j = 0; j !== stride; ++ j ) {
  31569. const value = values[ offset + j ];
  31570. if ( value !== values[ offsetP + j ] ||
  31571. value !== values[ offsetN + j ] ) {
  31572. keep = true;
  31573. break;
  31574. }
  31575. }
  31576. } else {
  31577. keep = true;
  31578. }
  31579. }
  31580. // in-place compaction
  31581. if ( keep ) {
  31582. if ( i !== writeIndex ) {
  31583. times[ writeIndex ] = times[ i ];
  31584. const readOffset = i * stride,
  31585. writeOffset = writeIndex * stride;
  31586. for ( let j = 0; j !== stride; ++ j ) {
  31587. values[ writeOffset + j ] = values[ readOffset + j ];
  31588. }
  31589. }
  31590. ++ writeIndex;
  31591. }
  31592. }
  31593. // flush last keyframe (compaction looks ahead)
  31594. if ( lastIndex > 0 ) {
  31595. times[ writeIndex ] = times[ lastIndex ];
  31596. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31597. values[ writeOffset + j ] = values[ readOffset + j ];
  31598. }
  31599. ++ writeIndex;
  31600. }
  31601. if ( writeIndex !== times.length ) {
  31602. this.times = times.slice( 0, writeIndex );
  31603. this.values = values.slice( 0, writeIndex * stride );
  31604. } else {
  31605. this.times = times;
  31606. this.values = values;
  31607. }
  31608. return this;
  31609. }
  31610. /**
  31611. * Returns a new keyframe track with copied values from this instance.
  31612. *
  31613. * @return {KeyframeTrack} A clone of this instance.
  31614. */
  31615. clone() {
  31616. const times = this.times.slice();
  31617. const values = this.values.slice();
  31618. const TypedKeyframeTrack = this.constructor;
  31619. const track = new TypedKeyframeTrack( this.name, times, values );
  31620. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31621. track.createInterpolant = this.createInterpolant;
  31622. return track;
  31623. }
  31624. }
  31625. /**
  31626. * The value type name.
  31627. *
  31628. * @type {string}
  31629. * @default ''
  31630. */
  31631. KeyframeTrack.prototype.ValueTypeName = '';
  31632. /**
  31633. * The time buffer type of this keyframe track.
  31634. *
  31635. * @type {TypedArray|Array}
  31636. * @default Float32Array.constructor
  31637. */
  31638. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31639. /**
  31640. * The value buffer type of this keyframe track.
  31641. *
  31642. * @type {TypedArray|Array}
  31643. * @default Float32Array.constructor
  31644. */
  31645. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31646. /**
  31647. * The default interpolation type of this keyframe track.
  31648. *
  31649. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)}
  31650. * @default InterpolateLinear
  31651. */
  31652. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31653. /**
  31654. * A track for boolean keyframe values.
  31655. *
  31656. * @augments KeyframeTrack
  31657. */
  31658. class BooleanKeyframeTrack extends KeyframeTrack {
  31659. /**
  31660. * Constructs a new boolean keyframe track.
  31661. *
  31662. * This keyframe track type has no `interpolation` parameter because the
  31663. * interpolation is always discrete.
  31664. *
  31665. * @param {string} name - The keyframe track's name.
  31666. * @param {Array<number>} times - A list of keyframe times.
  31667. * @param {Array<boolean>} values - A list of keyframe values.
  31668. */
  31669. constructor( name, times, values ) {
  31670. super( name, times, values );
  31671. }
  31672. }
  31673. /**
  31674. * The value type name.
  31675. *
  31676. * @type {string}
  31677. * @default 'bool'
  31678. */
  31679. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31680. /**
  31681. * The value buffer type of this keyframe track.
  31682. *
  31683. * @type {TypedArray|Array}
  31684. * @default Array.constructor
  31685. */
  31686. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31687. /**
  31688. * The default interpolation type of this keyframe track.
  31689. *
  31690. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31691. * @default InterpolateDiscrete
  31692. */
  31693. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31694. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31695. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31696. /**
  31697. * A track for color keyframe values.
  31698. *
  31699. * @augments KeyframeTrack
  31700. */
  31701. class ColorKeyframeTrack extends KeyframeTrack {
  31702. /**
  31703. * Constructs a new color keyframe track.
  31704. *
  31705. * @param {string} name - The keyframe track's name.
  31706. * @param {Array<number>} times - A list of keyframe times.
  31707. * @param {Array<number>} values - A list of keyframe values.
  31708. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31709. */
  31710. constructor( name, times, values, interpolation ) {
  31711. super( name, times, values, interpolation );
  31712. }
  31713. }
  31714. /**
  31715. * The value type name.
  31716. *
  31717. * @type {string}
  31718. * @default 'color'
  31719. */
  31720. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31721. /**
  31722. * A track for numeric keyframe values.
  31723. *
  31724. * @augments KeyframeTrack
  31725. */
  31726. class NumberKeyframeTrack extends KeyframeTrack {
  31727. /**
  31728. * Constructs a new number keyframe track.
  31729. *
  31730. * @param {string} name - The keyframe track's name.
  31731. * @param {Array<number>} times - A list of keyframe times.
  31732. * @param {Array<number>} values - A list of keyframe values.
  31733. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31734. */
  31735. constructor( name, times, values, interpolation ) {
  31736. super( name, times, values, interpolation );
  31737. }
  31738. }
  31739. /**
  31740. * The value type name.
  31741. *
  31742. * @type {string}
  31743. * @default 'number'
  31744. */
  31745. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31746. /**
  31747. * Spherical linear unit quaternion interpolant.
  31748. *
  31749. * @augments Interpolant
  31750. */
  31751. class QuaternionLinearInterpolant extends Interpolant {
  31752. /**
  31753. * Constructs a new SLERP interpolant.
  31754. *
  31755. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31756. * @param {TypedArray} sampleValues - The sample values.
  31757. * @param {number} sampleSize - The sample size
  31758. * @param {TypedArray} [resultBuffer] - The result buffer.
  31759. */
  31760. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31761. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31762. }
  31763. interpolate_( i1, t0, t, t1 ) {
  31764. const result = this.resultBuffer,
  31765. values = this.sampleValues,
  31766. stride = this.valueSize,
  31767. alpha = ( t - t0 ) / ( t1 - t0 );
  31768. let offset = i1 * stride;
  31769. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31770. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31771. }
  31772. return result;
  31773. }
  31774. }
  31775. /**
  31776. * A track for Quaternion keyframe values.
  31777. *
  31778. * @augments KeyframeTrack
  31779. */
  31780. class QuaternionKeyframeTrack extends KeyframeTrack {
  31781. /**
  31782. * Constructs a new Quaternion keyframe track.
  31783. *
  31784. * @param {string} name - The keyframe track's name.
  31785. * @param {Array<number>} times - A list of keyframe times.
  31786. * @param {Array<number>} values - A list of keyframe values.
  31787. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31788. */
  31789. constructor( name, times, values, interpolation ) {
  31790. super( name, times, values, interpolation );
  31791. }
  31792. /**
  31793. * Overwritten so the method returns Quaternion based interpolant.
  31794. *
  31795. * @static
  31796. * @param {TypedArray} [result] - The result buffer.
  31797. * @return {QuaternionLinearInterpolant} The new interpolant.
  31798. */
  31799. InterpolantFactoryMethodLinear( result ) {
  31800. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31801. }
  31802. }
  31803. /**
  31804. * The value type name.
  31805. *
  31806. * @type {string}
  31807. * @default 'quaternion'
  31808. */
  31809. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31810. // ValueBufferType is inherited
  31811. // DefaultInterpolation is inherited;
  31812. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31813. /**
  31814. * A track for string keyframe values.
  31815. *
  31816. * @augments KeyframeTrack
  31817. */
  31818. class StringKeyframeTrack extends KeyframeTrack {
  31819. /**
  31820. * Constructs a new string keyframe track.
  31821. *
  31822. * This keyframe track type has no `interpolation` parameter because the
  31823. * interpolation is always discrete.
  31824. *
  31825. * @param {string} name - The keyframe track's name.
  31826. * @param {Array<number>} times - A list of keyframe times.
  31827. * @param {Array<string>} values - A list of keyframe values.
  31828. */
  31829. constructor( name, times, values ) {
  31830. super( name, times, values );
  31831. }
  31832. }
  31833. /**
  31834. * The value type name.
  31835. *
  31836. * @type {string}
  31837. * @default 'string'
  31838. */
  31839. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31840. /**
  31841. * The value buffer type of this keyframe track.
  31842. *
  31843. * @type {TypedArray|Array}
  31844. * @default Array.constructor
  31845. */
  31846. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31847. /**
  31848. * The default interpolation type of this keyframe track.
  31849. *
  31850. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31851. * @default InterpolateDiscrete
  31852. */
  31853. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31854. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31855. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31856. /**
  31857. * A track for vector keyframe values.
  31858. *
  31859. * @augments KeyframeTrack
  31860. */
  31861. class VectorKeyframeTrack extends KeyframeTrack {
  31862. /**
  31863. * Constructs a new vector keyframe track.
  31864. *
  31865. * @param {string} name - The keyframe track's name.
  31866. * @param {Array<number>} times - A list of keyframe times.
  31867. * @param {Array<number>} values - A list of keyframe values.
  31868. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31869. */
  31870. constructor( name, times, values, interpolation ) {
  31871. super( name, times, values, interpolation );
  31872. }
  31873. }
  31874. /**
  31875. * The value type name.
  31876. *
  31877. * @type {string}
  31878. * @default 'vector'
  31879. */
  31880. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31881. /**
  31882. * A reusable set of keyframe tracks which represent an animation.
  31883. */
  31884. class AnimationClip {
  31885. /**
  31886. * Constructs a new animation clip.
  31887. *
  31888. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31889. * use the static interface of this class for creating clips. In most cases though, animation clips
  31890. * will automatically be created by loaders when importing animated 3D assets.
  31891. *
  31892. * @param {string} [name=''] - The clip's name.
  31893. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31894. * the duration will be calculated from the passed keyframes.
  31895. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31896. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31897. * is blended/combined when two or more animations are simultaneously played.
  31898. */
  31899. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31900. /**
  31901. * The clip's name.
  31902. *
  31903. * @type {string}
  31904. */
  31905. this.name = name;
  31906. /**
  31907. * An array of keyframe tracks.
  31908. *
  31909. * @type {Array<KeyframeTrack>}
  31910. */
  31911. this.tracks = tracks;
  31912. /**
  31913. * The clip's duration in seconds.
  31914. *
  31915. * @type {number}
  31916. */
  31917. this.duration = duration;
  31918. /**
  31919. * Defines how the animation is blended/combined when two or more animations
  31920. * are simultaneously played.
  31921. *
  31922. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31923. */
  31924. this.blendMode = blendMode;
  31925. /**
  31926. * The UUID of the animation clip.
  31927. *
  31928. * @type {string}
  31929. * @readonly
  31930. */
  31931. this.uuid = generateUUID();
  31932. /**
  31933. * An object that can be used to store custom data about the animation clip.
  31934. * It should not hold references to functions as these will not be cloned.
  31935. *
  31936. * @type {Object}
  31937. */
  31938. this.userData = {};
  31939. // this means it should figure out its duration by scanning the tracks
  31940. if ( this.duration < 0 ) {
  31941. this.resetDuration();
  31942. }
  31943. }
  31944. /**
  31945. * Factory method for creating an animation clip from the given JSON.
  31946. *
  31947. * @static
  31948. * @param {Object} json - The serialized animation clip.
  31949. * @return {AnimationClip} The new animation clip.
  31950. */
  31951. static parse( json ) {
  31952. const tracks = [],
  31953. jsonTracks = json.tracks,
  31954. frameTime = 1.0 / ( json.fps || 1.0 );
  31955. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31956. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31957. }
  31958. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31959. clip.uuid = json.uuid;
  31960. clip.userData = JSON.parse( json.userData || '{}' );
  31961. return clip;
  31962. }
  31963. /**
  31964. * Serializes the given animation clip into JSON.
  31965. *
  31966. * @static
  31967. * @param {AnimationClip} clip - The animation clip to serialize.
  31968. * @return {Object} The JSON object.
  31969. */
  31970. static toJSON( clip ) {
  31971. const tracks = [],
  31972. clipTracks = clip.tracks;
  31973. const json = {
  31974. 'name': clip.name,
  31975. 'duration': clip.duration,
  31976. 'tracks': tracks,
  31977. 'uuid': clip.uuid,
  31978. 'blendMode': clip.blendMode,
  31979. 'userData': JSON.stringify( clip.userData ),
  31980. };
  31981. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31982. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31983. }
  31984. return json;
  31985. }
  31986. /**
  31987. * Returns a new animation clip from the passed morph targets array of a
  31988. * geometry, taking a name and the number of frames per second.
  31989. *
  31990. * Note: The fps parameter is required, but the animation speed can be
  31991. * overridden via {@link AnimationAction#setDuration}.
  31992. *
  31993. * @static
  31994. * @param {string} name - The name of the animation clip.
  31995. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31996. * @param {number} fps - The Frames-Per-Second value.
  31997. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31998. * @return {AnimationClip} The new animation clip.
  31999. */
  32000. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  32001. const numMorphTargets = morphTargetSequence.length;
  32002. const tracks = [];
  32003. for ( let i = 0; i < numMorphTargets; i ++ ) {
  32004. let times = [];
  32005. let values = [];
  32006. times.push(
  32007. ( i + numMorphTargets - 1 ) % numMorphTargets,
  32008. i,
  32009. ( i + 1 ) % numMorphTargets );
  32010. values.push( 0, 1, 0 );
  32011. const order = getKeyframeOrder( times );
  32012. times = sortedArray( times, 1, order );
  32013. values = sortedArray( values, 1, order );
  32014. // if there is a key at the first frame, duplicate it as the
  32015. // last frame as well for perfect loop.
  32016. if ( ! noLoop && times[ 0 ] === 0 ) {
  32017. times.push( numMorphTargets );
  32018. values.push( values[ 0 ] );
  32019. }
  32020. tracks.push(
  32021. new NumberKeyframeTrack(
  32022. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  32023. times, values
  32024. ).scale( 1.0 / fps ) );
  32025. }
  32026. return new this( name, -1, tracks );
  32027. }
  32028. /**
  32029. * Searches for an animation clip by name, taking as its first parameter
  32030. * either an array of clips, or a mesh or geometry that contains an
  32031. * array named "animations" property.
  32032. *
  32033. * @static
  32034. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  32035. * @param {string} name - The name to search for.
  32036. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  32037. */
  32038. static findByName( objectOrClipArray, name ) {
  32039. let clipArray = objectOrClipArray;
  32040. if ( ! Array.isArray( objectOrClipArray ) ) {
  32041. const o = objectOrClipArray;
  32042. clipArray = o.geometry && o.geometry.animations || o.animations;
  32043. }
  32044. for ( let i = 0; i < clipArray.length; i ++ ) {
  32045. if ( clipArray[ i ].name === name ) {
  32046. return clipArray[ i ];
  32047. }
  32048. }
  32049. return null;
  32050. }
  32051. /**
  32052. * Returns an array of new AnimationClips created from the morph target
  32053. * sequences of a geometry, trying to sort morph target names into
  32054. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  32055. *
  32056. * See {@link MD2Loader#parse} as an example for how the method should be used.
  32057. *
  32058. * @static
  32059. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  32060. * @param {number} fps - The Frames-Per-Second value.
  32061. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  32062. * @return {Array<AnimationClip>} An array of new animation clips.
  32063. */
  32064. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  32065. const animationToMorphTargets = {};
  32066. // tested with https://regex101.com/ on trick sequences
  32067. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  32068. const pattern = /^([\w-]*?)([\d]+)$/;
  32069. // sort morph target names into animation groups based
  32070. // patterns like Walk_001, Walk_002, Run_001, Run_002
  32071. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  32072. const morphTarget = morphTargets[ i ];
  32073. const parts = morphTarget.name.match( pattern );
  32074. if ( parts && parts.length > 1 ) {
  32075. const name = parts[ 1 ];
  32076. let animationMorphTargets = animationToMorphTargets[ name ];
  32077. if ( ! animationMorphTargets ) {
  32078. animationToMorphTargets[ name ] = animationMorphTargets = [];
  32079. }
  32080. animationMorphTargets.push( morphTarget );
  32081. }
  32082. }
  32083. const clips = [];
  32084. for ( const name in animationToMorphTargets ) {
  32085. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  32086. }
  32087. return clips;
  32088. }
  32089. /**
  32090. * Sets the duration of this clip to the duration of its longest keyframe track.
  32091. *
  32092. * @return {AnimationClip} A reference to this animation clip.
  32093. */
  32094. resetDuration() {
  32095. const tracks = this.tracks;
  32096. let duration = 0;
  32097. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  32098. const track = this.tracks[ i ];
  32099. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  32100. }
  32101. this.duration = duration;
  32102. return this;
  32103. }
  32104. /**
  32105. * Trims all tracks to the clip's duration.
  32106. *
  32107. * @return {AnimationClip} A reference to this animation clip.
  32108. */
  32109. trim() {
  32110. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32111. this.tracks[ i ].trim( 0, this.duration );
  32112. }
  32113. return this;
  32114. }
  32115. /**
  32116. * Performs minimal validation on each track in the clip. Returns `true` if all
  32117. * tracks are valid.
  32118. *
  32119. * @return {boolean} Whether the clip's keyframes are valid or not.
  32120. */
  32121. validate() {
  32122. let valid = true;
  32123. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32124. valid = valid && this.tracks[ i ].validate();
  32125. }
  32126. return valid;
  32127. }
  32128. /**
  32129. * Optimizes each track by removing equivalent sequential keys (which are
  32130. * common in morph target sequences).
  32131. *
  32132. * @return {AnimationClip} A reference to this animation clip.
  32133. */
  32134. optimize() {
  32135. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32136. this.tracks[ i ].optimize();
  32137. }
  32138. return this;
  32139. }
  32140. /**
  32141. * Returns a new animation clip with copied values from this instance.
  32142. *
  32143. * @return {AnimationClip} A clone of this instance.
  32144. */
  32145. clone() {
  32146. const tracks = [];
  32147. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32148. tracks.push( this.tracks[ i ].clone() );
  32149. }
  32150. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  32151. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  32152. return clip;
  32153. }
  32154. /**
  32155. * Serializes this animation clip into JSON.
  32156. *
  32157. * @return {Object} The JSON object.
  32158. */
  32159. toJSON() {
  32160. return this.constructor.toJSON( this );
  32161. }
  32162. }
  32163. function getTrackTypeForValueTypeName( typeName ) {
  32164. switch ( typeName.toLowerCase() ) {
  32165. case 'scalar':
  32166. case 'double':
  32167. case 'float':
  32168. case 'number':
  32169. case 'integer':
  32170. return NumberKeyframeTrack;
  32171. case 'vector':
  32172. case 'vector2':
  32173. case 'vector3':
  32174. case 'vector4':
  32175. return VectorKeyframeTrack;
  32176. case 'color':
  32177. return ColorKeyframeTrack;
  32178. case 'quaternion':
  32179. return QuaternionKeyframeTrack;
  32180. case 'bool':
  32181. case 'boolean':
  32182. return BooleanKeyframeTrack;
  32183. case 'string':
  32184. return StringKeyframeTrack;
  32185. }
  32186. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  32187. }
  32188. function parseKeyframeTrack( json ) {
  32189. if ( json.type === undefined ) {
  32190. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  32191. }
  32192. const trackType = getTrackTypeForValueTypeName( json.type );
  32193. if ( json.times === undefined ) {
  32194. const times = [], values = [];
  32195. flattenJSON( json.keys, times, values, 'value' );
  32196. json.times = times;
  32197. json.values = values;
  32198. }
  32199. // derived classes can define a static parse method
  32200. if ( trackType.parse !== undefined ) {
  32201. return trackType.parse( json );
  32202. } else {
  32203. // by default, we assume a constructor compatible with the base
  32204. return new trackType( json.name, json.times, json.values, json.interpolation );
  32205. }
  32206. }
  32207. /**
  32208. * @class
  32209. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  32210. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  32211. * @hideconstructor
  32212. */
  32213. const Cache = {
  32214. /**
  32215. * Whether caching is enabled or not.
  32216. *
  32217. * @static
  32218. * @type {boolean}
  32219. * @default false
  32220. */
  32221. enabled: false,
  32222. /**
  32223. * A dictionary that holds cached files.
  32224. *
  32225. * @static
  32226. * @type {Object<string,Object>}
  32227. */
  32228. files: {},
  32229. /**
  32230. * Adds a cache entry with a key to reference the file. If this key already
  32231. * holds a file, it is overwritten.
  32232. *
  32233. * @static
  32234. * @param {string} key - The key to reference the cached file.
  32235. * @param {Object} file - The file to be cached.
  32236. */
  32237. add: function ( key, file ) {
  32238. if ( this.enabled === false ) return;
  32239. if ( isBlobURL( key ) ) return;
  32240. // log( 'Cache', 'Adding key:', key );
  32241. this.files[ key ] = file;
  32242. },
  32243. /**
  32244. * Gets the cached value for the given key.
  32245. *
  32246. * @static
  32247. * @param {string} key - The key to reference the cached file.
  32248. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  32249. */
  32250. get: function ( key ) {
  32251. if ( this.enabled === false ) return;
  32252. if ( isBlobURL( key ) ) return;
  32253. // log( 'Cache', 'Checking key:', key );
  32254. return this.files[ key ];
  32255. },
  32256. /**
  32257. * Removes the cached file associated with the given key.
  32258. *
  32259. * @static
  32260. * @param {string} key - The key to reference the cached file.
  32261. */
  32262. remove: function ( key ) {
  32263. delete this.files[ key ];
  32264. },
  32265. /**
  32266. * Remove all values from the cache.
  32267. *
  32268. * @static
  32269. */
  32270. clear: function () {
  32271. this.files = {};
  32272. }
  32273. };
  32274. /**
  32275. * Returns true if the given cache key contains the blob: scheme.
  32276. *
  32277. * @private
  32278. * @param {string} key - The cache key.
  32279. * @return {boolean} Whether the given cache key contains the blob: scheme or not.
  32280. */
  32281. function isBlobURL( key ) {
  32282. try {
  32283. const urlString = key.slice( key.indexOf( ':' ) + 1 ); // remove type identifier
  32284. const url = new URL( urlString );
  32285. return url.protocol === 'blob:';
  32286. } catch ( e ) {
  32287. // If the string is not a valid URL, it throws an error
  32288. return false;
  32289. }
  32290. }
  32291. /**
  32292. * Handles and keeps track of loaded and pending data. A default global
  32293. * instance of this class is created and used by loaders if not supplied
  32294. * manually.
  32295. *
  32296. * In general that should be sufficient, however there are times when it can
  32297. * be useful to have separate loaders - for example if you want to show
  32298. * separate loading bars for objects and textures.
  32299. *
  32300. * ```js
  32301. * const manager = new THREE.LoadingManager();
  32302. * manager.onLoad = () => console.log( 'Loading complete!' );
  32303. *
  32304. * const loader1 = new OBJLoader( manager );
  32305. * const loader2 = new ColladaLoader( manager );
  32306. * ```
  32307. */
  32308. class LoadingManager {
  32309. /**
  32310. * Constructs a new loading manager.
  32311. *
  32312. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32313. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32314. * @param {Function} [onError] - Executes when an error occurs.
  32315. */
  32316. constructor( onLoad, onProgress, onError ) {
  32317. const scope = this;
  32318. let isLoading = false;
  32319. let itemsLoaded = 0;
  32320. let itemsTotal = 0;
  32321. let urlModifier = undefined;
  32322. const handlers = [];
  32323. // Refer to #5689 for the reason why we don't set .onStart
  32324. // in the constructor
  32325. /**
  32326. * Executes when an item starts loading.
  32327. *
  32328. * @type {Function|undefined}
  32329. * @default undefined
  32330. */
  32331. this.onStart = undefined;
  32332. /**
  32333. * Executes when all items have been loaded.
  32334. *
  32335. * @type {Function|undefined}
  32336. * @default undefined
  32337. */
  32338. this.onLoad = onLoad;
  32339. /**
  32340. * Executes when single items have been loaded.
  32341. *
  32342. * @type {Function|undefined}
  32343. * @default undefined
  32344. */
  32345. this.onProgress = onProgress;
  32346. /**
  32347. * Executes when an error occurs.
  32348. *
  32349. * @type {Function|undefined}
  32350. * @default undefined
  32351. */
  32352. this.onError = onError;
  32353. /**
  32354. * Used for aborting ongoing requests in loaders using this manager.
  32355. *
  32356. * @private
  32357. * @type {AbortController | null}
  32358. */
  32359. this._abortController = null;
  32360. /**
  32361. * This should be called by any loader using the manager when the loader
  32362. * starts loading an item.
  32363. *
  32364. * @param {string} url - The URL to load.
  32365. */
  32366. this.itemStart = function ( url ) {
  32367. itemsTotal ++;
  32368. if ( isLoading === false ) {
  32369. if ( scope.onStart !== undefined ) {
  32370. scope.onStart( url, itemsLoaded, itemsTotal );
  32371. }
  32372. }
  32373. isLoading = true;
  32374. };
  32375. /**
  32376. * This should be called by any loader using the manager when the loader
  32377. * ended loading an item.
  32378. *
  32379. * @param {string} url - The URL of the loaded item.
  32380. */
  32381. this.itemEnd = function ( url ) {
  32382. itemsLoaded ++;
  32383. if ( scope.onProgress !== undefined ) {
  32384. scope.onProgress( url, itemsLoaded, itemsTotal );
  32385. }
  32386. if ( itemsLoaded === itemsTotal ) {
  32387. isLoading = false;
  32388. if ( scope.onLoad !== undefined ) {
  32389. scope.onLoad();
  32390. }
  32391. }
  32392. };
  32393. /**
  32394. * This should be called by any loader using the manager when the loader
  32395. * encounters an error when loading an item.
  32396. *
  32397. * @param {string} url - The URL of the item that produces an error.
  32398. */
  32399. this.itemError = function ( url ) {
  32400. if ( scope.onError !== undefined ) {
  32401. scope.onError( url );
  32402. }
  32403. };
  32404. /**
  32405. * Given a URL, uses the URL modifier callback (if any) and returns a
  32406. * resolved URL. If no URL modifier is set, returns the original URL.
  32407. *
  32408. * @param {string} url - The URL to load.
  32409. * @return {string} The resolved URL.
  32410. */
  32411. this.resolveURL = function ( url ) {
  32412. // Normalize to NFC so that Unicode URIs (e.g. from glTF)
  32413. // are percent-encoded correctly per RFC 3987.
  32414. url = url.normalize( 'NFC' );
  32415. if ( urlModifier ) {
  32416. return urlModifier( url );
  32417. }
  32418. return url;
  32419. };
  32420. /**
  32421. * If provided, the callback will be passed each resource URL before a
  32422. * request is sent. The callback may return the original URL, or a new URL to
  32423. * override loading behavior. This behavior can be used to load assets from
  32424. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32425. *
  32426. * ```js
  32427. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32428. *
  32429. * const manager = new THREE.LoadingManager();
  32430. *
  32431. * // Initialize loading manager with URL callback.
  32432. * const objectURLs = [];
  32433. * manager.setURLModifier( ( url ) => {
  32434. *
  32435. * url = URL.createObjectURL( blobs[ url ] );
  32436. * objectURLs.push( url );
  32437. * return url;
  32438. *
  32439. * } );
  32440. *
  32441. * // Load as usual, then revoke the blob URLs.
  32442. * const loader = new GLTFLoader( manager );
  32443. * loader.load( 'fish.gltf', (gltf) => {
  32444. *
  32445. * scene.add( gltf.scene );
  32446. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32447. *
  32448. * } );
  32449. * ```
  32450. *
  32451. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32452. * @return {LoadingManager} A reference to this loading manager.
  32453. */
  32454. this.setURLModifier = function ( transform ) {
  32455. urlModifier = transform;
  32456. return this;
  32457. };
  32458. /**
  32459. * Registers a loader with the given regular expression. Can be used to
  32460. * define what loader should be used in order to load specific files. A
  32461. * typical use case is to overwrite the default loader for textures.
  32462. *
  32463. * ```js
  32464. * // add handler for TGA textures
  32465. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32466. * ```
  32467. *
  32468. * @param {string} regex - A regular expression.
  32469. * @param {Loader} loader - A loader that should handle matched cases.
  32470. * @return {LoadingManager} A reference to this loading manager.
  32471. */
  32472. this.addHandler = function ( regex, loader ) {
  32473. handlers.push( regex, loader );
  32474. return this;
  32475. };
  32476. /**
  32477. * Removes the loader for the given regular expression.
  32478. *
  32479. * @param {string} regex - A regular expression.
  32480. * @return {LoadingManager} A reference to this loading manager.
  32481. */
  32482. this.removeHandler = function ( regex ) {
  32483. const index = handlers.indexOf( regex );
  32484. if ( index !== -1 ) {
  32485. handlers.splice( index, 2 );
  32486. }
  32487. return this;
  32488. };
  32489. /**
  32490. * Can be used to retrieve the registered loader for the given file path.
  32491. *
  32492. * @param {string} file - The file path.
  32493. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32494. */
  32495. this.getHandler = function ( file ) {
  32496. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32497. const regex = handlers[ i ];
  32498. const loader = handlers[ i + 1 ];
  32499. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32500. if ( regex.test( file ) ) {
  32501. return loader;
  32502. }
  32503. }
  32504. return null;
  32505. };
  32506. /**
  32507. * Can be used to abort ongoing loading requests in loaders using this manager.
  32508. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32509. * is supported in the browser.
  32510. *
  32511. * @return {LoadingManager} A reference to this loading manager.
  32512. */
  32513. this.abort = function () {
  32514. this.abortController.abort();
  32515. this._abortController = null;
  32516. return this;
  32517. };
  32518. }
  32519. // TODO: Revert this back to a single member variable once this issue has been fixed
  32520. // https://github.com/cloudflare/workerd/issues/3657
  32521. /**
  32522. * Used for aborting ongoing requests in loaders using this manager.
  32523. *
  32524. * @type {AbortController}
  32525. */
  32526. get abortController() {
  32527. if ( ! this._abortController ) {
  32528. this._abortController = new AbortController();
  32529. }
  32530. return this._abortController;
  32531. }
  32532. }
  32533. /**
  32534. * The global default loading manager.
  32535. *
  32536. * @constant
  32537. * @type {LoadingManager}
  32538. */
  32539. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32540. /**
  32541. * Abstract base class for loaders.
  32542. *
  32543. * @abstract
  32544. */
  32545. class Loader {
  32546. /**
  32547. * Constructs a new loader.
  32548. *
  32549. * @param {LoadingManager} [manager] - The loading manager.
  32550. */
  32551. constructor( manager ) {
  32552. /**
  32553. * The loading manager.
  32554. *
  32555. * @type {LoadingManager}
  32556. * @default DefaultLoadingManager
  32557. */
  32558. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32559. /**
  32560. * The crossOrigin string to implement CORS for loading the url from a
  32561. * different domain that allows CORS.
  32562. *
  32563. * @type {string}
  32564. * @default 'anonymous'
  32565. */
  32566. this.crossOrigin = 'anonymous';
  32567. /**
  32568. * Whether the XMLHttpRequest uses credentials.
  32569. *
  32570. * @type {boolean}
  32571. * @default false
  32572. */
  32573. this.withCredentials = false;
  32574. /**
  32575. * The base path from which the asset will be loaded.
  32576. *
  32577. * @type {string}
  32578. */
  32579. this.path = '';
  32580. /**
  32581. * The base path from which additional resources like textures will be loaded.
  32582. *
  32583. * @type {string}
  32584. */
  32585. this.resourcePath = '';
  32586. /**
  32587. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32588. * used in HTTP request.
  32589. *
  32590. * @type {Object<string, any>}
  32591. */
  32592. this.requestHeader = {};
  32593. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32594. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32595. }
  32596. }
  32597. /**
  32598. * This method needs to be implemented by all concrete loaders. It holds the
  32599. * logic for loading assets from the backend.
  32600. *
  32601. * @abstract
  32602. * @param {string} url - The path/URL of the file to be loaded.
  32603. * @param {Function} onLoad - Executed when the loading process has been finished.
  32604. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32605. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32606. */
  32607. load( /* url, onLoad, onProgress, onError */ ) {}
  32608. /**
  32609. * A async version of {@link Loader#load}.
  32610. *
  32611. * @param {string} url - The path/URL of the file to be loaded.
  32612. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32613. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32614. */
  32615. loadAsync( url, onProgress ) {
  32616. const scope = this;
  32617. return new Promise( function ( resolve, reject ) {
  32618. scope.load( url, resolve, onProgress, reject );
  32619. } );
  32620. }
  32621. /**
  32622. * This method needs to be implemented by all concrete loaders. It holds the
  32623. * logic for parsing the asset into three.js entities.
  32624. *
  32625. * @abstract
  32626. * @param {any} data - The data to parse.
  32627. */
  32628. parse( /* data */ ) {}
  32629. /**
  32630. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32631. * from a different domain that allows CORS.
  32632. *
  32633. * @param {string} crossOrigin - The `crossOrigin` value.
  32634. * @return {Loader} A reference to this instance.
  32635. */
  32636. setCrossOrigin( crossOrigin ) {
  32637. this.crossOrigin = crossOrigin;
  32638. return this;
  32639. }
  32640. /**
  32641. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32642. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32643. *
  32644. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32645. *
  32646. * @param {boolean} value - The `withCredentials` value.
  32647. * @return {Loader} A reference to this instance.
  32648. */
  32649. setWithCredentials( value ) {
  32650. this.withCredentials = value;
  32651. return this;
  32652. }
  32653. /**
  32654. * Sets the base path for the asset.
  32655. *
  32656. * @param {string} path - The base path.
  32657. * @return {Loader} A reference to this instance.
  32658. */
  32659. setPath( path ) {
  32660. this.path = path;
  32661. return this;
  32662. }
  32663. /**
  32664. * Sets the base path for dependent resources like textures.
  32665. *
  32666. * @param {string} resourcePath - The resource path.
  32667. * @return {Loader} A reference to this instance.
  32668. */
  32669. setResourcePath( resourcePath ) {
  32670. this.resourcePath = resourcePath;
  32671. return this;
  32672. }
  32673. /**
  32674. * Sets the given request header.
  32675. *
  32676. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32677. * for configuring the HTTP request.
  32678. * @return {Loader} A reference to this instance.
  32679. */
  32680. setRequestHeader( requestHeader ) {
  32681. this.requestHeader = requestHeader;
  32682. return this;
  32683. }
  32684. /**
  32685. * This method can be implemented in loaders for aborting ongoing requests.
  32686. *
  32687. * @abstract
  32688. * @return {Loader} A reference to this instance.
  32689. */
  32690. abort() {
  32691. return this;
  32692. }
  32693. }
  32694. /**
  32695. * Callback for onProgress in loaders.
  32696. *
  32697. * @callback onProgressCallback
  32698. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32699. */
  32700. /**
  32701. * Callback for onError in loaders.
  32702. *
  32703. * @callback onErrorCallback
  32704. * @param {Error} error - The error which occurred during the loading process.
  32705. */
  32706. /**
  32707. * The default material name that is used by loaders
  32708. * when creating materials for loaded 3D objects.
  32709. *
  32710. * Note: Not all loaders might honor this setting.
  32711. *
  32712. * @static
  32713. * @type {string}
  32714. * @default '__DEFAULT'
  32715. */
  32716. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32717. const loading = {};
  32718. class HttpError extends Error {
  32719. constructor( message, response ) {
  32720. super( message );
  32721. this.response = response;
  32722. }
  32723. }
  32724. /**
  32725. * A low level class for loading resources with the Fetch API, used internally by
  32726. * most loaders. It can also be used directly to load any file type that does
  32727. * not have a loader.
  32728. *
  32729. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32730. * once to your application.
  32731. *
  32732. * ```js
  32733. * const loader = new THREE.FileLoader();
  32734. * const data = await loader.loadAsync( 'example.txt' );
  32735. * ```
  32736. *
  32737. * @augments Loader
  32738. */
  32739. class FileLoader extends Loader {
  32740. /**
  32741. * Constructs a new file loader.
  32742. *
  32743. * @param {LoadingManager} [manager] - The loading manager.
  32744. */
  32745. constructor( manager ) {
  32746. super( manager );
  32747. /**
  32748. * The expected mime type. Valid values can be found
  32749. * [here](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32750. *
  32751. * @type {string}
  32752. */
  32753. this.mimeType = '';
  32754. /**
  32755. * The expected response type.
  32756. *
  32757. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32758. * @default ''
  32759. */
  32760. this.responseType = '';
  32761. /**
  32762. * Used for aborting requests.
  32763. *
  32764. * @private
  32765. * @type {AbortController}
  32766. */
  32767. this._abortController = new AbortController();
  32768. }
  32769. /**
  32770. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32771. *
  32772. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32773. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32774. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32775. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32776. */
  32777. load( url, onLoad, onProgress, onError ) {
  32778. if ( url === undefined ) url = '';
  32779. if ( this.path !== undefined ) url = this.path + url;
  32780. url = this.manager.resolveURL( url );
  32781. const cached = Cache.get( `file:${url}` );
  32782. if ( cached !== undefined ) {
  32783. this.manager.itemStart( url );
  32784. setTimeout( () => {
  32785. if ( onLoad ) onLoad( cached );
  32786. this.manager.itemEnd( url );
  32787. }, 0 );
  32788. return;
  32789. }
  32790. // Check if request is duplicate
  32791. if ( loading[ url ] !== undefined ) {
  32792. loading[ url ].push( {
  32793. onLoad: onLoad,
  32794. onProgress: onProgress,
  32795. onError: onError
  32796. } );
  32797. return;
  32798. }
  32799. // Initialise array for duplicate requests
  32800. loading[ url ] = [];
  32801. loading[ url ].push( {
  32802. onLoad: onLoad,
  32803. onProgress: onProgress,
  32804. onError: onError,
  32805. } );
  32806. // create request
  32807. const req = new Request( url, {
  32808. headers: new Headers( this.requestHeader ),
  32809. credentials: this.withCredentials ? 'include' : 'same-origin',
  32810. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32811. } );
  32812. // record states ( avoid data race )
  32813. const mimeType = this.mimeType;
  32814. const responseType = this.responseType;
  32815. // start the fetch
  32816. fetch( req )
  32817. .then( response => {
  32818. if ( response.status === 200 || response.status === 0 ) {
  32819. // Some browsers return HTTP Status 0 when using non-http protocol
  32820. // e.g. 'file://' or 'data://'. Handle as success.
  32821. if ( response.status === 0 ) {
  32822. warn( 'FileLoader: HTTP Status 0 received.' );
  32823. }
  32824. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32825. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32826. return response;
  32827. }
  32828. const callbacks = loading[ url ];
  32829. const reader = response.body.getReader();
  32830. // Nginx needs X-File-Size check
  32831. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32832. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32833. const total = contentLength ? parseInt( contentLength ) : 0;
  32834. const lengthComputable = total !== 0;
  32835. let loaded = 0;
  32836. // periodically read data into the new stream tracking while download progress
  32837. const stream = new ReadableStream( {
  32838. start( controller ) {
  32839. readData();
  32840. function readData() {
  32841. reader.read().then( ( { done, value } ) => {
  32842. if ( done ) {
  32843. controller.close();
  32844. } else {
  32845. loaded += value.byteLength;
  32846. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32847. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32848. const callback = callbacks[ i ];
  32849. if ( callback.onProgress ) callback.onProgress( event );
  32850. }
  32851. controller.enqueue( value );
  32852. readData();
  32853. }
  32854. }, ( e ) => {
  32855. controller.error( e );
  32856. } );
  32857. }
  32858. }
  32859. } );
  32860. return new Response( stream );
  32861. } else {
  32862. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32863. }
  32864. } )
  32865. .then( response => {
  32866. switch ( responseType ) {
  32867. case 'arraybuffer':
  32868. return response.arrayBuffer();
  32869. case 'blob':
  32870. return response.blob();
  32871. case 'document':
  32872. return response.text()
  32873. .then( text => {
  32874. const parser = new DOMParser();
  32875. return parser.parseFromString( text, mimeType );
  32876. } );
  32877. case 'json':
  32878. return response.json();
  32879. default:
  32880. if ( mimeType === '' ) {
  32881. return response.text();
  32882. } else {
  32883. // sniff encoding
  32884. const re = /charset="?([^;"\s]*)"?/i;
  32885. const exec = re.exec( mimeType );
  32886. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32887. const decoder = new TextDecoder( label );
  32888. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32889. }
  32890. }
  32891. } )
  32892. .then( data => {
  32893. // Add to cache only on HTTP success, so that we do not cache
  32894. // error response bodies as proper responses to requests.
  32895. Cache.add( `file:${url}`, data );
  32896. const callbacks = loading[ url ];
  32897. delete loading[ url ];
  32898. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32899. const callback = callbacks[ i ];
  32900. if ( callback.onLoad ) callback.onLoad( data );
  32901. }
  32902. } )
  32903. .catch( err => {
  32904. // Abort errors and other errors are handled the same
  32905. const callbacks = loading[ url ];
  32906. if ( callbacks === undefined ) {
  32907. // When onLoad was called and url was deleted in `loading`
  32908. this.manager.itemError( url );
  32909. throw err;
  32910. }
  32911. delete loading[ url ];
  32912. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32913. const callback = callbacks[ i ];
  32914. if ( callback.onError ) callback.onError( err );
  32915. }
  32916. this.manager.itemError( url );
  32917. } )
  32918. .finally( () => {
  32919. this.manager.itemEnd( url );
  32920. } );
  32921. this.manager.itemStart( url );
  32922. }
  32923. /**
  32924. * Sets the expected response type.
  32925. *
  32926. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32927. * @return {FileLoader} A reference to this file loader.
  32928. */
  32929. setResponseType( value ) {
  32930. this.responseType = value;
  32931. return this;
  32932. }
  32933. /**
  32934. * Sets the expected mime type of the loaded file.
  32935. *
  32936. * @param {string} value - The mime type.
  32937. * @return {FileLoader} A reference to this file loader.
  32938. */
  32939. setMimeType( value ) {
  32940. this.mimeType = value;
  32941. return this;
  32942. }
  32943. /**
  32944. * Aborts ongoing fetch requests.
  32945. *
  32946. * @return {FileLoader} A reference to this instance.
  32947. */
  32948. abort() {
  32949. this._abortController.abort();
  32950. this._abortController = new AbortController();
  32951. return this;
  32952. }
  32953. }
  32954. /**
  32955. * Class for loading animation clips in the JSON format. The files are internally
  32956. * loaded via {@link FileLoader}.
  32957. *
  32958. * ```js
  32959. * const loader = new THREE.AnimationLoader();
  32960. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32961. * ```
  32962. *
  32963. * @augments Loader
  32964. */
  32965. class AnimationLoader extends Loader {
  32966. /**
  32967. * Constructs a new animation loader.
  32968. *
  32969. * @param {LoadingManager} [manager] - The loading manager.
  32970. */
  32971. constructor( manager ) {
  32972. super( manager );
  32973. }
  32974. /**
  32975. * Starts loading from the given URL and pass the loaded animations as an array
  32976. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32977. *
  32978. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32979. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32980. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32981. * @param {onErrorCallback} onError - Executed when errors occur.
  32982. */
  32983. load( url, onLoad, onProgress, onError ) {
  32984. const scope = this;
  32985. const loader = new FileLoader( this.manager );
  32986. loader.setPath( this.path );
  32987. loader.setRequestHeader( this.requestHeader );
  32988. loader.setWithCredentials( this.withCredentials );
  32989. loader.load( url, function ( text ) {
  32990. try {
  32991. onLoad( scope.parse( JSON.parse( text ) ) );
  32992. } catch ( e ) {
  32993. if ( onError ) {
  32994. onError( e );
  32995. } else {
  32996. error( e );
  32997. }
  32998. scope.manager.itemError( url );
  32999. }
  33000. }, onProgress, onError );
  33001. }
  33002. /**
  33003. * Parses the given JSON object and returns an array of animation clips.
  33004. *
  33005. * @param {Object} json - The serialized animation clips.
  33006. * @return {Array<AnimationClip>} The parsed animation clips.
  33007. */
  33008. parse( json ) {
  33009. const animations = [];
  33010. for ( let i = 0; i < json.length; i ++ ) {
  33011. const clip = AnimationClip.parse( json[ i ] );
  33012. animations.push( clip );
  33013. }
  33014. return animations;
  33015. }
  33016. }
  33017. /**
  33018. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  33019. * Textures are internally loaded via {@link FileLoader}.
  33020. *
  33021. * Derived classes have to implement the `parse()` method which holds the parsing
  33022. * for the respective format.
  33023. *
  33024. * @abstract
  33025. * @augments Loader
  33026. */
  33027. class CompressedTextureLoader extends Loader {
  33028. /**
  33029. * Constructs a new compressed texture loader.
  33030. *
  33031. * @param {LoadingManager} [manager] - The loading manager.
  33032. */
  33033. constructor( manager ) {
  33034. super( manager );
  33035. }
  33036. /**
  33037. * Starts loading from the given URL and passes the loaded compressed texture
  33038. * to the `onLoad()` callback. The method also returns a new texture object which can
  33039. * directly be used for material creation. If you do it this way, the texture
  33040. * may pop up in your scene once the respective loading process is finished.
  33041. *
  33042. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33043. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  33044. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33045. * @param {onErrorCallback} onError - Executed when errors occur.
  33046. * @return {CompressedTexture} The compressed texture.
  33047. */
  33048. load( url, onLoad, onProgress, onError ) {
  33049. const scope = this;
  33050. const images = [];
  33051. const texture = new CompressedTexture();
  33052. const loader = new FileLoader( this.manager );
  33053. loader.setPath( this.path );
  33054. loader.setResponseType( 'arraybuffer' );
  33055. loader.setRequestHeader( this.requestHeader );
  33056. loader.setWithCredentials( scope.withCredentials );
  33057. let loaded = 0;
  33058. function loadTexture( i ) {
  33059. loader.load( url[ i ], function ( buffer ) {
  33060. const texDatas = scope.parse( buffer, true );
  33061. images[ i ] = {
  33062. width: texDatas.width,
  33063. height: texDatas.height,
  33064. format: texDatas.format,
  33065. mipmaps: texDatas.mipmaps
  33066. };
  33067. loaded += 1;
  33068. if ( loaded === 6 ) {
  33069. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  33070. texture.image = images;
  33071. texture.format = texDatas.format;
  33072. texture.needsUpdate = true;
  33073. if ( onLoad ) onLoad( texture );
  33074. }
  33075. }, onProgress, onError );
  33076. }
  33077. if ( Array.isArray( url ) ) {
  33078. for ( let i = 0, il = url.length; i < il; ++ i ) {
  33079. loadTexture( i );
  33080. }
  33081. } else {
  33082. // compressed cubemap texture stored in a single DDS file
  33083. loader.load( url, function ( buffer ) {
  33084. const texDatas = scope.parse( buffer, true );
  33085. if ( texDatas.isCubemap ) {
  33086. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  33087. for ( let f = 0; f < faces; f ++ ) {
  33088. images[ f ] = { mipmaps: [] };
  33089. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  33090. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  33091. images[ f ].format = texDatas.format;
  33092. images[ f ].width = texDatas.width;
  33093. images[ f ].height = texDatas.height;
  33094. }
  33095. }
  33096. texture.image = images;
  33097. } else {
  33098. texture.image.width = texDatas.width;
  33099. texture.image.height = texDatas.height;
  33100. texture.mipmaps = texDatas.mipmaps;
  33101. }
  33102. if ( texDatas.mipmapCount === 1 ) {
  33103. texture.minFilter = LinearFilter;
  33104. }
  33105. texture.format = texDatas.format;
  33106. texture.needsUpdate = true;
  33107. if ( onLoad ) onLoad( texture );
  33108. }, onProgress, onError );
  33109. }
  33110. return texture;
  33111. }
  33112. }
  33113. const _loading = new WeakMap();
  33114. /**
  33115. * A loader for loading images. The class loads images with the HTML `Image` API.
  33116. *
  33117. * ```js
  33118. * const loader = new THREE.ImageLoader();
  33119. * const image = await loader.loadAsync( 'image.png' );
  33120. * ```
  33121. * Please note that `ImageLoader` has dropped support for progress
  33122. * events in `r84`. For an `ImageLoader` that supports progress events, see
  33123. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  33124. *
  33125. * @augments Loader
  33126. */
  33127. class ImageLoader extends Loader {
  33128. /**
  33129. * Constructs a new image loader.
  33130. *
  33131. * @param {LoadingManager} [manager] - The loading manager.
  33132. */
  33133. constructor( manager ) {
  33134. super( manager );
  33135. }
  33136. /**
  33137. * Starts loading from the given URL and passes the loaded image
  33138. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  33139. * directly be used for texture creation. If you do it this way, the texture
  33140. * may pop up in your scene once the respective loading process is finished.
  33141. *
  33142. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33143. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  33144. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33145. * @param {onErrorCallback} onError - Executed when errors occur.
  33146. * @return {Image} The image.
  33147. */
  33148. load( url, onLoad, onProgress, onError ) {
  33149. if ( this.path !== undefined ) url = this.path + url;
  33150. url = this.manager.resolveURL( url );
  33151. const scope = this;
  33152. const cached = Cache.get( `image:${url}` );
  33153. if ( cached !== undefined ) {
  33154. if ( cached.complete === true ) {
  33155. scope.manager.itemStart( url );
  33156. setTimeout( function () {
  33157. if ( onLoad ) onLoad( cached );
  33158. scope.manager.itemEnd( url );
  33159. }, 0 );
  33160. } else {
  33161. let arr = _loading.get( cached );
  33162. if ( arr === undefined ) {
  33163. arr = [];
  33164. _loading.set( cached, arr );
  33165. }
  33166. arr.push( { onLoad, onError } );
  33167. }
  33168. return cached;
  33169. }
  33170. const image = createElementNS( 'img' );
  33171. function onImageLoad() {
  33172. removeEventListeners();
  33173. if ( onLoad ) onLoad( this );
  33174. //
  33175. const callbacks = _loading.get( this ) || [];
  33176. for ( let i = 0; i < callbacks.length; i ++ ) {
  33177. const callback = callbacks[ i ];
  33178. if ( callback.onLoad ) callback.onLoad( this );
  33179. }
  33180. _loading.delete( this );
  33181. scope.manager.itemEnd( url );
  33182. }
  33183. function onImageError( event ) {
  33184. removeEventListeners();
  33185. if ( onError ) onError( event );
  33186. Cache.remove( `image:${url}` );
  33187. //
  33188. const callbacks = _loading.get( this ) || [];
  33189. for ( let i = 0; i < callbacks.length; i ++ ) {
  33190. const callback = callbacks[ i ];
  33191. if ( callback.onError ) callback.onError( event );
  33192. }
  33193. _loading.delete( this );
  33194. scope.manager.itemError( url );
  33195. scope.manager.itemEnd( url );
  33196. }
  33197. function removeEventListeners() {
  33198. image.removeEventListener( 'load', onImageLoad, false );
  33199. image.removeEventListener( 'error', onImageError, false );
  33200. }
  33201. image.addEventListener( 'load', onImageLoad, false );
  33202. image.addEventListener( 'error', onImageError, false );
  33203. if ( url.slice( 0, 5 ) !== 'data:' ) {
  33204. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  33205. }
  33206. Cache.add( `image:${url}`, image );
  33207. scope.manager.itemStart( url );
  33208. image.src = url;
  33209. return image;
  33210. }
  33211. }
  33212. /**
  33213. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  33214. *
  33215. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  33216. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  33217. * like vertical and horizontal cross, column and row layouts are not supported.
  33218. *
  33219. * Note that, by convention, cube maps are specified in a coordinate system
  33220. * in which positive-x is to the right when looking up the positive-z axis --
  33221. * in other words, using a left-handed coordinate system. Since three.js uses
  33222. * a right-handed coordinate system, environment maps used in three.js will
  33223. * have pos-x and neg-x swapped.
  33224. *
  33225. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  33226. * is set to `SRGBColorSpace` by default.
  33227. *
  33228. * ```js
  33229. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  33230. * const cubeTexture = await loader.loadAsync( [
  33231. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  33232. * ] );
  33233. * scene.background = cubeTexture;
  33234. * ```
  33235. *
  33236. * @augments Loader
  33237. */
  33238. class CubeTextureLoader extends Loader {
  33239. /**
  33240. * Constructs a new cube texture loader.
  33241. *
  33242. * @param {LoadingManager} [manager] - The loading manager.
  33243. */
  33244. constructor( manager ) {
  33245. super( manager );
  33246. }
  33247. /**
  33248. * Starts loading from the given URL and pass the fully loaded cube texture
  33249. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  33250. * directly be used for material creation. If you do it this way, the cube texture
  33251. * may pop up in your scene once the respective loading process is finished.
  33252. *
  33253. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  33254. * cube texture. The urls should be specified in the following order: pos-x,
  33255. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  33256. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  33257. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33258. * @param {onErrorCallback} onError - Executed when errors occur.
  33259. * @return {CubeTexture} The cube texture.
  33260. */
  33261. load( urls, onLoad, onProgress, onError ) {
  33262. const texture = new CubeTexture();
  33263. texture.colorSpace = SRGBColorSpace;
  33264. const loader = new ImageLoader( this.manager );
  33265. loader.setCrossOrigin( this.crossOrigin );
  33266. loader.setPath( this.path );
  33267. let loaded = 0;
  33268. function loadTexture( i ) {
  33269. loader.load( urls[ i ], function ( image ) {
  33270. texture.images[ i ] = image;
  33271. loaded ++;
  33272. if ( loaded === 6 ) {
  33273. texture.needsUpdate = true;
  33274. if ( onLoad ) onLoad( texture );
  33275. }
  33276. }, undefined, onError );
  33277. }
  33278. for ( let i = 0; i < urls.length; ++ i ) {
  33279. loadTexture( i );
  33280. }
  33281. return texture;
  33282. }
  33283. }
  33284. /**
  33285. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33286. * Textures are internally loaded via {@link FileLoader}.
  33287. *
  33288. * Derived classes have to implement the `parse()` method which holds the parsing
  33289. * for the respective format.
  33290. *
  33291. * @abstract
  33292. * @augments Loader
  33293. */
  33294. class DataTextureLoader extends Loader {
  33295. /**
  33296. * Constructs a new data texture loader.
  33297. *
  33298. * @param {LoadingManager} [manager] - The loading manager.
  33299. */
  33300. constructor( manager ) {
  33301. super( manager );
  33302. }
  33303. /**
  33304. * Starts loading from the given URL and passes the loaded data texture
  33305. * to the `onLoad()` callback. The method also returns a new texture object which can
  33306. * directly be used for material creation. If you do it this way, the texture
  33307. * may pop up in your scene once the respective loading process is finished.
  33308. *
  33309. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33310. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33311. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33312. * @param {onErrorCallback} onError - Executed when errors occur.
  33313. * @return {DataTexture} The data texture.
  33314. */
  33315. load( url, onLoad, onProgress, onError ) {
  33316. const scope = this;
  33317. const texture = new DataTexture();
  33318. const loader = new FileLoader( this.manager );
  33319. loader.setResponseType( 'arraybuffer' );
  33320. loader.setRequestHeader( this.requestHeader );
  33321. loader.setPath( this.path );
  33322. loader.setWithCredentials( scope.withCredentials );
  33323. loader.load( url, function ( buffer ) {
  33324. let texData;
  33325. try {
  33326. texData = scope.parse( buffer );
  33327. } catch ( e ) {
  33328. if ( onError !== undefined ) {
  33329. onError( e );
  33330. } else {
  33331. error( e );
  33332. }
  33333. return;
  33334. }
  33335. scope._applyTexData( texture, texData );
  33336. if ( onLoad ) onLoad( texture, texData );
  33337. }, onProgress, onError );
  33338. return texture;
  33339. }
  33340. /**
  33341. * Parses the given buffer and returns a configured data texture. Use this method
  33342. * for parsing texture data that is already in memory (e.g. drag and drop or data
  33343. * loaded from a server) without going through {@link DataTextureLoader#load}.
  33344. *
  33345. * @param {ArrayBuffer} buffer - The raw texture data.
  33346. * @return {DataTexture} The data texture.
  33347. */
  33348. createDataTexture( buffer ) {
  33349. const texture = new DataTexture();
  33350. this._applyTexData( texture, this.parse( buffer ) );
  33351. return texture;
  33352. }
  33353. /**
  33354. * Applies the given parsed texture data to the given data texture.
  33355. *
  33356. * @private
  33357. * @param {DataTexture} texture - The data texture.
  33358. * @param {DataTextureLoader~TexData} texData - The parsed texture data.
  33359. */
  33360. _applyTexData( texture, texData ) {
  33361. if ( texData.image !== undefined ) {
  33362. texture.image = texData.image;
  33363. } else if ( texData.data !== undefined ) {
  33364. texture.image.width = texData.width;
  33365. texture.image.height = texData.height;
  33366. texture.image.data = texData.data;
  33367. }
  33368. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33369. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33370. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33371. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33372. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33373. if ( texData.colorSpace !== undefined ) {
  33374. texture.colorSpace = texData.colorSpace;
  33375. }
  33376. if ( texData.flipY !== undefined ) {
  33377. texture.flipY = texData.flipY;
  33378. }
  33379. if ( texData.format !== undefined ) {
  33380. texture.format = texData.format;
  33381. }
  33382. if ( texData.type !== undefined ) {
  33383. texture.type = texData.type;
  33384. }
  33385. if ( texData.mipmaps !== undefined ) {
  33386. texture.mipmaps = texData.mipmaps;
  33387. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33388. }
  33389. if ( texData.mipmapCount === 1 ) {
  33390. texture.minFilter = LinearFilter;
  33391. }
  33392. if ( texData.generateMipmaps !== undefined ) {
  33393. texture.generateMipmaps = texData.generateMipmaps;
  33394. }
  33395. texture.needsUpdate = true;
  33396. }
  33397. }
  33398. /**
  33399. * Class for loading textures. Images are internally
  33400. * loaded via {@link ImageLoader}.
  33401. *
  33402. * ```js
  33403. * const loader = new THREE.TextureLoader();
  33404. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33405. *
  33406. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33407. * ```
  33408. * Please note that `TextureLoader` has dropped support for progress
  33409. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33410. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33411. *
  33412. * @augments Loader
  33413. */
  33414. class TextureLoader extends Loader {
  33415. /**
  33416. * Constructs a new texture loader.
  33417. *
  33418. * @param {LoadingManager} [manager] - The loading manager.
  33419. */
  33420. constructor( manager ) {
  33421. super( manager );
  33422. }
  33423. /**
  33424. * Starts loading from the given URL and pass the fully loaded texture
  33425. * to the `onLoad()` callback. The method also returns a new texture object which can
  33426. * directly be used for material creation. If you do it this way, the texture
  33427. * may pop up in your scene once the respective loading process is finished.
  33428. *
  33429. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33430. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33431. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33432. * @param {onErrorCallback} onError - Executed when errors occur.
  33433. * @return {Texture} The texture.
  33434. */
  33435. load( url, onLoad, onProgress, onError ) {
  33436. const texture = new Texture();
  33437. const loader = new ImageLoader( this.manager );
  33438. loader.setCrossOrigin( this.crossOrigin );
  33439. loader.setPath( this.path );
  33440. loader.load( url, function ( image ) {
  33441. texture.image = image;
  33442. texture.needsUpdate = true;
  33443. if ( onLoad !== undefined ) {
  33444. onLoad( texture );
  33445. }
  33446. }, onProgress, onError );
  33447. return texture;
  33448. }
  33449. }
  33450. /**
  33451. * Abstract base class for lights - all other light types inherit the
  33452. * properties and methods described here.
  33453. *
  33454. * @abstract
  33455. * @augments Object3D
  33456. */
  33457. class Light extends Object3D {
  33458. /**
  33459. * Constructs a new light.
  33460. *
  33461. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33462. * @param {number} [intensity=1] - The light's strength/intensity.
  33463. */
  33464. constructor( color, intensity = 1 ) {
  33465. super();
  33466. /**
  33467. * This flag can be used for type testing.
  33468. *
  33469. * @type {boolean}
  33470. * @readonly
  33471. * @default true
  33472. */
  33473. this.isLight = true;
  33474. this.type = 'Light';
  33475. /**
  33476. * The light's color.
  33477. *
  33478. * @type {Color}
  33479. */
  33480. this.color = new Color( color );
  33481. /**
  33482. * The light's intensity.
  33483. *
  33484. * @type {number}
  33485. * @default 1
  33486. */
  33487. this.intensity = intensity;
  33488. }
  33489. /**
  33490. * Frees the GPU-related resources allocated by this instance. Call this
  33491. * method whenever this instance is no longer used in your app.
  33492. */
  33493. dispose() {
  33494. this.dispatchEvent( { type: 'dispose' } );
  33495. }
  33496. copy( source, recursive ) {
  33497. super.copy( source, recursive );
  33498. this.color.copy( source.color );
  33499. this.intensity = source.intensity;
  33500. return this;
  33501. }
  33502. toJSON( meta ) {
  33503. const data = super.toJSON( meta );
  33504. data.object.color = this.color.getHex();
  33505. data.object.intensity = this.intensity;
  33506. return data;
  33507. }
  33508. }
  33509. /**
  33510. * A light source positioned directly above the scene, with color fading from
  33511. * the sky color to the ground color.
  33512. *
  33513. * This light cannot be used to cast shadows.
  33514. *
  33515. * ```js
  33516. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33517. * scene.add( light );
  33518. * ```
  33519. *
  33520. * @augments Light
  33521. */
  33522. class HemisphereLight extends Light {
  33523. /**
  33524. * Constructs a new hemisphere light.
  33525. *
  33526. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33527. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33528. * @param {number} [intensity=1] - The light's strength/intensity.
  33529. */
  33530. constructor( skyColor, groundColor, intensity ) {
  33531. super( skyColor, intensity );
  33532. /**
  33533. * This flag can be used for type testing.
  33534. *
  33535. * @type {boolean}
  33536. * @readonly
  33537. * @default true
  33538. */
  33539. this.isHemisphereLight = true;
  33540. this.type = 'HemisphereLight';
  33541. this.position.copy( Object3D.DEFAULT_UP );
  33542. this.updateMatrix();
  33543. /**
  33544. * The light's ground color.
  33545. *
  33546. * @type {Color}
  33547. */
  33548. this.groundColor = new Color( groundColor );
  33549. }
  33550. copy( source, recursive ) {
  33551. super.copy( source, recursive );
  33552. this.groundColor.copy( source.groundColor );
  33553. return this;
  33554. }
  33555. toJSON( meta ) {
  33556. const data = super.toJSON( meta );
  33557. data.object.groundColor = this.groundColor.getHex();
  33558. return data;
  33559. }
  33560. }
  33561. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33562. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33563. const _lookTarget = /*@__PURE__*/ new Vector3();
  33564. /**
  33565. * Abstract base class for light shadow classes. These classes
  33566. * represent the shadow configuration for different light types.
  33567. *
  33568. * @abstract
  33569. */
  33570. class LightShadow {
  33571. /**
  33572. * Constructs a new light shadow.
  33573. *
  33574. * @param {Camera} camera - The light's view of the world.
  33575. */
  33576. constructor( camera ) {
  33577. /**
  33578. * The light's view of the world.
  33579. *
  33580. * @type {Camera}
  33581. */
  33582. this.camera = camera;
  33583. /**
  33584. * The intensity of the shadow. The default is `1`.
  33585. * Valid values are in the range `[0, 1]`.
  33586. *
  33587. * @type {number}
  33588. * @default 1
  33589. */
  33590. this.intensity = 1;
  33591. /**
  33592. * Shadow map bias, how much to add or subtract from the normalized depth
  33593. * when deciding whether a surface is in shadow.
  33594. *
  33595. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33596. * may help reduce artifacts in shadows.
  33597. *
  33598. * @type {number}
  33599. * @default 0
  33600. */
  33601. this.bias = 0;
  33602. /**
  33603. * A node version of `bias`. Only supported with `WebGPURenderer`.
  33604. *
  33605. * If a bias node is defined, `bias` has no effect.
  33606. *
  33607. * @type {?Node<float>}
  33608. * @default null
  33609. */
  33610. this.biasNode = null;
  33611. /**
  33612. * Defines how much the position used to query the shadow map is offset along
  33613. * the object normal. The default is `0`. Increasing this value can be used to
  33614. * reduce shadow acne especially in large scenes where light shines onto
  33615. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33616. *
  33617. * @type {number}
  33618. * @default 0
  33619. */
  33620. this.normalBias = 0;
  33621. /**
  33622. * Setting this to values greater than 1 will blur the edges of the shadow.
  33623. * High values will cause unwanted banding effects in the shadows - a greater
  33624. * map size will allow for a higher value to be used here before these effects
  33625. * become visible.
  33626. *
  33627. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33628. *
  33629. * @type {number}
  33630. * @default 1
  33631. */
  33632. this.radius = 1;
  33633. /**
  33634. * The amount of samples to use when blurring a VSM shadow map.
  33635. *
  33636. * @type {number}
  33637. * @default 8
  33638. */
  33639. this.blurSamples = 8;
  33640. /**
  33641. * Defines the width and height of the shadow map. Higher values give better quality
  33642. * shadows at the cost of computation time. Values must be powers of two.
  33643. *
  33644. * @type {Vector2}
  33645. * @default (512,512)
  33646. */
  33647. this.mapSize = new Vector2( 512, 512 );
  33648. /**
  33649. * The type of shadow texture. The default is `UnsignedByteType`.
  33650. *
  33651. * @type {number}
  33652. * @default UnsignedByteType
  33653. */
  33654. this.mapType = UnsignedByteType;
  33655. /**
  33656. * The depth map generated using the internal camera; a location beyond a
  33657. * pixel's depth is in shadow. Computed internally during rendering.
  33658. *
  33659. * @type {?RenderTarget}
  33660. * @default null
  33661. */
  33662. this.map = null;
  33663. /**
  33664. * The distribution map generated using the internal camera; an occlusion is
  33665. * calculated based on the distribution of depths. Computed internally during
  33666. * rendering.
  33667. *
  33668. * @type {?RenderTarget}
  33669. * @default null
  33670. */
  33671. this.mapPass = null;
  33672. /**
  33673. * Model to shadow camera space, to compute location and depth in shadow map.
  33674. * This is computed internally during rendering.
  33675. *
  33676. * @type {Matrix4}
  33677. */
  33678. this.matrix = new Matrix4();
  33679. /**
  33680. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33681. * lighting / shadows, you may set this to `false`.
  33682. *
  33683. * @type {boolean}
  33684. * @default true
  33685. */
  33686. this.autoUpdate = true;
  33687. /**
  33688. * When set to `true`, shadow maps will be updated in the next `render` call.
  33689. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33690. * set this property to `true` and then make a render call to update the light's shadow.
  33691. *
  33692. * @type {boolean}
  33693. * @default false
  33694. */
  33695. this.needsUpdate = false;
  33696. this._frustum = new Frustum();
  33697. this._frameExtents = new Vector2( 1, 1 );
  33698. this._viewportCount = 1;
  33699. this._viewports = [
  33700. new Vector4( 0, 0, 1, 1 )
  33701. ];
  33702. }
  33703. /**
  33704. * Used internally by the renderer to get the number of viewports that need
  33705. * to be rendered for this shadow.
  33706. *
  33707. * @return {number} The viewport count.
  33708. */
  33709. getViewportCount() {
  33710. return this._viewportCount;
  33711. }
  33712. /**
  33713. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33714. *
  33715. * @return {Frustum} The shadow camera frustum.
  33716. */
  33717. getFrustum() {
  33718. return this._frustum;
  33719. }
  33720. /**
  33721. * Update the matrices for the camera and shadow, used internally by the renderer.
  33722. *
  33723. * @param {Light} light - The light for which the shadow is being rendered.
  33724. */
  33725. updateMatrices( light ) {
  33726. const shadowCamera = this.camera;
  33727. const shadowMatrix = this.matrix;
  33728. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33729. shadowCamera.position.copy( _lightPositionWorld );
  33730. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  33731. shadowCamera.lookAt( _lookTarget );
  33732. shadowCamera.updateMatrixWorld();
  33733. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33734. this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33735. if ( shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth ) {
  33736. shadowMatrix.set(
  33737. 0.5, 0.0, 0.0, 0.5,
  33738. 0.0, 0.5, 0.0, 0.5,
  33739. 0.0, 0.0, 1.0, 0.0, // Identity Z (preserving the correct [0, 1] range from the projection matrix)
  33740. 0.0, 0.0, 0.0, 1.0
  33741. );
  33742. } else {
  33743. shadowMatrix.set(
  33744. 0.5, 0.0, 0.0, 0.5,
  33745. 0.0, 0.5, 0.0, 0.5,
  33746. 0.0, 0.0, 0.5, 0.5,
  33747. 0.0, 0.0, 0.0, 1.0
  33748. );
  33749. }
  33750. shadowMatrix.multiply( _projScreenMatrix );
  33751. }
  33752. /**
  33753. * Returns a viewport definition for the given viewport index.
  33754. *
  33755. * @param {number} viewportIndex - The viewport index.
  33756. * @return {Vector4} The viewport.
  33757. */
  33758. getViewport( viewportIndex ) {
  33759. return this._viewports[ viewportIndex ];
  33760. }
  33761. /**
  33762. * Returns the frame extends.
  33763. *
  33764. * @return {Vector2} The frame extends.
  33765. */
  33766. getFrameExtents() {
  33767. return this._frameExtents;
  33768. }
  33769. /**
  33770. * Frees the GPU-related resources allocated by this instance. Call this
  33771. * method whenever this instance is no longer used in your app.
  33772. */
  33773. dispose() {
  33774. if ( this.map ) {
  33775. this.map.dispose();
  33776. }
  33777. if ( this.mapPass ) {
  33778. this.mapPass.dispose();
  33779. }
  33780. }
  33781. /**
  33782. * Copies the values of the given light shadow instance to this instance.
  33783. *
  33784. * @param {LightShadow} source - The light shadow to copy.
  33785. * @return {LightShadow} A reference to this light shadow instance.
  33786. */
  33787. copy( source ) {
  33788. this.camera = source.camera.clone();
  33789. this.intensity = source.intensity;
  33790. this.bias = source.bias;
  33791. this.radius = source.radius;
  33792. this.autoUpdate = source.autoUpdate;
  33793. this.needsUpdate = source.needsUpdate;
  33794. this.normalBias = source.normalBias;
  33795. this.blurSamples = source.blurSamples;
  33796. this.mapSize.copy( source.mapSize );
  33797. this.biasNode = source.biasNode;
  33798. return this;
  33799. }
  33800. /**
  33801. * Returns a new light shadow instance with copied values from this instance.
  33802. *
  33803. * @return {LightShadow} A clone of this instance.
  33804. */
  33805. clone() {
  33806. return new this.constructor().copy( this );
  33807. }
  33808. /**
  33809. * Serializes the light shadow into JSON.
  33810. *
  33811. * @return {Object} A JSON object representing the serialized light shadow.
  33812. * @see {@link ObjectLoader#parse}
  33813. */
  33814. toJSON() {
  33815. const object = {};
  33816. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33817. if ( this.bias !== 0 ) object.bias = this.bias;
  33818. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33819. if ( this.radius !== 1 ) object.radius = this.radius;
  33820. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33821. object.camera = this.camera.toJSON( false ).object;
  33822. delete object.camera.matrix;
  33823. return object;
  33824. }
  33825. }
  33826. const _position$2 = /*@__PURE__*/ new Vector3();
  33827. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  33828. const _scale$2 = /*@__PURE__*/ new Vector3();
  33829. /**
  33830. * Abstract base class for cameras. This class should always be inherited
  33831. * when you build a new camera.
  33832. *
  33833. * @abstract
  33834. * @augments Object3D
  33835. */
  33836. class Camera extends Object3D {
  33837. /**
  33838. * Constructs a new camera.
  33839. */
  33840. constructor() {
  33841. super();
  33842. /**
  33843. * This flag can be used for type testing.
  33844. *
  33845. * @type {boolean}
  33846. * @readonly
  33847. * @default true
  33848. */
  33849. this.isCamera = true;
  33850. this.type = 'Camera';
  33851. /**
  33852. * The inverse of the camera's world matrix.
  33853. *
  33854. * @type {Matrix4}
  33855. */
  33856. this.matrixWorldInverse = new Matrix4();
  33857. /**
  33858. * The camera's projection matrix.
  33859. *
  33860. * @type {Matrix4}
  33861. */
  33862. this.projectionMatrix = new Matrix4();
  33863. /**
  33864. * The inverse of the camera's projection matrix.
  33865. *
  33866. * @type {Matrix4}
  33867. */
  33868. this.projectionMatrixInverse = new Matrix4();
  33869. /**
  33870. * The coordinate system in which the camera is used.
  33871. *
  33872. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  33873. */
  33874. this.coordinateSystem = WebGLCoordinateSystem;
  33875. this._reversedDepth = false;
  33876. }
  33877. /**
  33878. * The flag that indicates whether the camera uses a reversed depth buffer.
  33879. *
  33880. * @type {boolean}
  33881. * @default false
  33882. */
  33883. get reversedDepth() {
  33884. return this._reversedDepth;
  33885. }
  33886. copy( source, recursive ) {
  33887. super.copy( source, recursive );
  33888. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  33889. this.projectionMatrix.copy( source.projectionMatrix );
  33890. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  33891. this.coordinateSystem = source.coordinateSystem;
  33892. return this;
  33893. }
  33894. /**
  33895. * Returns a vector representing the ("look") direction of the 3D object in world space.
  33896. *
  33897. * This method is overwritten since cameras have a different forward vector compared to other
  33898. * 3D objects. A camera looks down its local, negative z-axis by default.
  33899. *
  33900. * @param {Vector3} target - The target vector the result is stored to.
  33901. * @return {Vector3} The 3D object's direction in world space.
  33902. */
  33903. getWorldDirection( target ) {
  33904. return super.getWorldDirection( target ).negate();
  33905. }
  33906. updateMatrixWorld( force ) {
  33907. super.updateMatrixWorld( force );
  33908. // exclude scale from view matrix to be glTF conform
  33909. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33910. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33911. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33912. } else {
  33913. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33914. }
  33915. }
  33916. updateWorldMatrix( updateParents, updateChildren, force = false ) {
  33917. super.updateWorldMatrix( updateParents, updateChildren, force );
  33918. // exclude scale from view matrix to be glTF conform
  33919. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33920. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33921. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33922. } else {
  33923. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33924. }
  33925. }
  33926. clone() {
  33927. return new this.constructor().copy( this );
  33928. }
  33929. }
  33930. const _v3$1 = /*@__PURE__*/ new Vector3();
  33931. const _minTarget = /*@__PURE__*/ new Vector2();
  33932. const _maxTarget = /*@__PURE__*/ new Vector2();
  33933. /**
  33934. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  33935. *
  33936. * This projection mode is designed to mimic the way the human eye sees. It
  33937. * is the most common projection mode used for rendering a 3D scene.
  33938. *
  33939. * ```js
  33940. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  33941. * scene.add( camera );
  33942. * ```
  33943. *
  33944. * @augments Camera
  33945. */
  33946. class PerspectiveCamera extends Camera {
  33947. /**
  33948. * Constructs a new perspective camera.
  33949. *
  33950. * @param {number} [fov=50] - The vertical field of view.
  33951. * @param {number} [aspect=1] - The aspect ratio.
  33952. * @param {number} [near=0.1] - The camera's near plane.
  33953. * @param {number} [far=2000] - The camera's far plane.
  33954. */
  33955. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  33956. super();
  33957. /**
  33958. * This flag can be used for type testing.
  33959. *
  33960. * @type {boolean}
  33961. * @readonly
  33962. * @default true
  33963. */
  33964. this.isPerspectiveCamera = true;
  33965. this.type = 'PerspectiveCamera';
  33966. /**
  33967. * The vertical field of view, from bottom to top of view,
  33968. * in degrees.
  33969. *
  33970. * @type {number}
  33971. * @default 50
  33972. */
  33973. this.fov = fov;
  33974. /**
  33975. * The zoom factor of the camera.
  33976. *
  33977. * @type {number}
  33978. * @default 1
  33979. */
  33980. this.zoom = 1;
  33981. /**
  33982. * The camera's near plane. The valid range is greater than `0`
  33983. * and less than the current value of {@link PerspectiveCamera#far}.
  33984. *
  33985. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  33986. * valid value for a perspective camera's near plane.
  33987. *
  33988. * @type {number}
  33989. * @default 0.1
  33990. */
  33991. this.near = near;
  33992. /**
  33993. * The camera's far plane. Must be greater than the
  33994. * current value of {@link PerspectiveCamera#near}.
  33995. *
  33996. * @type {number}
  33997. * @default 2000
  33998. */
  33999. this.far = far;
  34000. /**
  34001. * Object distance used for stereoscopy and depth-of-field effects. This
  34002. * parameter does not influence the projection matrix unless a
  34003. * {@link StereoCamera} is being used.
  34004. *
  34005. * @type {number}
  34006. * @default 10
  34007. */
  34008. this.focus = 10;
  34009. /**
  34010. * The aspect ratio, usually the canvas width / canvas height.
  34011. *
  34012. * @type {number}
  34013. * @default 1
  34014. */
  34015. this.aspect = aspect;
  34016. /**
  34017. * Represents the frustum window specification. This property should not be edited
  34018. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34019. *
  34020. * @type {?Object}
  34021. * @default null
  34022. */
  34023. this.view = null;
  34024. /**
  34025. * Film size used for the larger axis. Default is `35` (millimeters). This
  34026. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  34027. * is set to a nonzero value.
  34028. *
  34029. * @type {number}
  34030. * @default 35
  34031. */
  34032. this.filmGauge = 35;
  34033. /**
  34034. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  34035. *
  34036. * @type {number}
  34037. * @default 0
  34038. */
  34039. this.filmOffset = 0;
  34040. this.updateProjectionMatrix();
  34041. }
  34042. copy( source, recursive ) {
  34043. super.copy( source, recursive );
  34044. this.fov = source.fov;
  34045. this.zoom = source.zoom;
  34046. this.near = source.near;
  34047. this.far = source.far;
  34048. this.focus = source.focus;
  34049. this.aspect = source.aspect;
  34050. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34051. this.filmGauge = source.filmGauge;
  34052. this.filmOffset = source.filmOffset;
  34053. return this;
  34054. }
  34055. /**
  34056. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  34057. *
  34058. * The default film gauge is 35, so that the focal length can be specified for
  34059. * a 35mm (full frame) camera.
  34060. *
  34061. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  34062. */
  34063. setFocalLength( focalLength ) {
  34064. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  34065. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  34066. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  34067. this.updateProjectionMatrix();
  34068. }
  34069. /**
  34070. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  34071. * {@link PerspectiveCamera#filmGauge}.
  34072. *
  34073. * @return {number} The computed focal length.
  34074. */
  34075. getFocalLength() {
  34076. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  34077. return 0.5 * this.getFilmHeight() / vExtentSlope;
  34078. }
  34079. /**
  34080. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  34081. *
  34082. * @return {number} The effective FOV.
  34083. */
  34084. getEffectiveFOV() {
  34085. return RAD2DEG * 2 * Math.atan(
  34086. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  34087. }
  34088. /**
  34089. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  34090. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  34091. *
  34092. * @return {number} The film width.
  34093. */
  34094. getFilmWidth() {
  34095. // film not completely covered in portrait format (aspect < 1)
  34096. return this.filmGauge * Math.min( this.aspect, 1 );
  34097. }
  34098. /**
  34099. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  34100. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  34101. *
  34102. * @return {number} The film width.
  34103. */
  34104. getFilmHeight() {
  34105. // film not completely covered in landscape format (aspect > 1)
  34106. return this.filmGauge / Math.max( this.aspect, 1 );
  34107. }
  34108. /**
  34109. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  34110. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  34111. *
  34112. * @param {number} distance - The viewing distance.
  34113. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  34114. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  34115. */
  34116. getViewBounds( distance, minTarget, maxTarget ) {
  34117. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  34118. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  34119. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  34120. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  34121. }
  34122. /**
  34123. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  34124. *
  34125. * @param {number} distance - The viewing distance.
  34126. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  34127. * @returns {Vector2} The view size.
  34128. */
  34129. getViewSize( distance, target ) {
  34130. this.getViewBounds( distance, _minTarget, _maxTarget );
  34131. return target.subVectors( _maxTarget, _minTarget );
  34132. }
  34133. /**
  34134. * Sets an offset in a larger frustum. This is useful for multi-window or
  34135. * multi-monitor/multi-machine setups.
  34136. *
  34137. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  34138. * the monitors are in grid like this
  34139. *```
  34140. * +---+---+---+
  34141. * | A | B | C |
  34142. * +---+---+---+
  34143. * | D | E | F |
  34144. * +---+---+---+
  34145. *```
  34146. * then for each monitor you would call it like this:
  34147. *```js
  34148. * const w = 1920;
  34149. * const h = 1080;
  34150. * const fullWidth = w * 3;
  34151. * const fullHeight = h * 2;
  34152. *
  34153. * // --A--
  34154. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  34155. * // --B--
  34156. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  34157. * // --C--
  34158. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  34159. * // --D--
  34160. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  34161. * // --E--
  34162. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  34163. * // --F--
  34164. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  34165. * ```
  34166. *
  34167. * Note there is no reason monitors have to be the same size or in a grid.
  34168. *
  34169. * @param {number} fullWidth - The full width of multiview setup.
  34170. * @param {number} fullHeight - The full height of multiview setup.
  34171. * @param {number} x - The horizontal offset of the subcamera.
  34172. * @param {number} y - The vertical offset of the subcamera.
  34173. * @param {number} width - The width of subcamera.
  34174. * @param {number} height - The height of subcamera.
  34175. */
  34176. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34177. this.aspect = fullWidth / fullHeight;
  34178. if ( this.view === null ) {
  34179. this.view = {
  34180. enabled: true,
  34181. fullWidth: 1,
  34182. fullHeight: 1,
  34183. offsetX: 0,
  34184. offsetY: 0,
  34185. width: 1,
  34186. height: 1
  34187. };
  34188. }
  34189. this.view.enabled = true;
  34190. this.view.fullWidth = fullWidth;
  34191. this.view.fullHeight = fullHeight;
  34192. this.view.offsetX = x;
  34193. this.view.offsetY = y;
  34194. this.view.width = width;
  34195. this.view.height = height;
  34196. this.updateProjectionMatrix();
  34197. }
  34198. /**
  34199. * Removes the view offset from the projection matrix.
  34200. */
  34201. clearViewOffset() {
  34202. if ( this.view !== null ) {
  34203. this.view.enabled = false;
  34204. }
  34205. this.updateProjectionMatrix();
  34206. }
  34207. /**
  34208. * Updates the camera's projection matrix. Must be called after any change of
  34209. * camera properties.
  34210. */
  34211. updateProjectionMatrix() {
  34212. const near = this.near;
  34213. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  34214. let height = 2 * top;
  34215. let width = this.aspect * height;
  34216. let left = -0.5 * width;
  34217. const view = this.view;
  34218. if ( this.view !== null && this.view.enabled ) {
  34219. const fullWidth = view.fullWidth,
  34220. fullHeight = view.fullHeight;
  34221. left += view.offsetX * width / fullWidth;
  34222. top -= view.offsetY * height / fullHeight;
  34223. width *= view.width / fullWidth;
  34224. height *= view.height / fullHeight;
  34225. }
  34226. const skew = this.filmOffset;
  34227. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  34228. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  34229. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34230. }
  34231. toJSON( meta ) {
  34232. const data = super.toJSON( meta );
  34233. data.object.fov = this.fov;
  34234. data.object.zoom = this.zoom;
  34235. data.object.near = this.near;
  34236. data.object.far = this.far;
  34237. data.object.focus = this.focus;
  34238. data.object.aspect = this.aspect;
  34239. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34240. data.object.filmGauge = this.filmGauge;
  34241. data.object.filmOffset = this.filmOffset;
  34242. return data;
  34243. }
  34244. }
  34245. /**
  34246. * Represents the shadow configuration of directional lights.
  34247. *
  34248. * @augments LightShadow
  34249. */
  34250. class SpotLightShadow extends LightShadow {
  34251. /**
  34252. * Constructs a new spot light shadow.
  34253. */
  34254. constructor() {
  34255. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  34256. /**
  34257. * This flag can be used for type testing.
  34258. *
  34259. * @type {boolean}
  34260. * @readonly
  34261. * @default true
  34262. */
  34263. this.isSpotLightShadow = true;
  34264. /**
  34265. * Used to focus the shadow camera. The camera's field of view is set as a
  34266. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  34267. *
  34268. * @type {number}
  34269. * @default 1
  34270. */
  34271. this.focus = 1;
  34272. /**
  34273. * Texture aspect ratio.
  34274. *
  34275. * @type {number}
  34276. * @default 1
  34277. */
  34278. this.aspect = 1;
  34279. }
  34280. updateMatrices( light ) {
  34281. const camera = this.camera;
  34282. const fov = RAD2DEG * 2 * light.angle * this.focus;
  34283. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  34284. const far = light.distance || camera.far;
  34285. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  34286. camera.fov = fov;
  34287. camera.aspect = aspect;
  34288. camera.far = far;
  34289. camera.updateProjectionMatrix();
  34290. }
  34291. super.updateMatrices( light );
  34292. }
  34293. copy( source ) {
  34294. super.copy( source );
  34295. this.focus = source.focus;
  34296. return this;
  34297. }
  34298. }
  34299. /**
  34300. * This light gets emitted from a single point in one direction, along a cone
  34301. * that increases in size the further from the light it gets.
  34302. *
  34303. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  34304. *
  34305. * ```js
  34306. * // white spotlight shining from the side, modulated by a texture
  34307. * const spotLight = new THREE.SpotLight( 0xffffff );
  34308. * spotLight.position.set( 100, 1000, 100 );
  34309. * spotLight.map = new THREE.TextureLoader().load( url );
  34310. *
  34311. * spotLight.castShadow = true;
  34312. * spotLight.shadow.mapSize.width = 1024;
  34313. * spotLight.shadow.mapSize.height = 1024;
  34314. * spotLight.shadow.camera.near = 500;
  34315. * spotLight.shadow.camera.far = 4000;
  34316. * spotLight.shadow.camera.fov = 30;s
  34317. * ```
  34318. *
  34319. * @augments Light
  34320. */
  34321. class SpotLight extends Light {
  34322. /**
  34323. * Constructs a new spot light.
  34324. *
  34325. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34326. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  34327. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  34328. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  34329. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  34330. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  34331. */
  34332. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  34333. super( color, intensity );
  34334. /**
  34335. * This flag can be used for type testing.
  34336. *
  34337. * @type {boolean}
  34338. * @readonly
  34339. * @default true
  34340. */
  34341. this.isSpotLight = true;
  34342. this.type = 'SpotLight';
  34343. this.position.copy( Object3D.DEFAULT_UP );
  34344. this.updateMatrix();
  34345. /**
  34346. * The spot light points from its position to the
  34347. * target's position.
  34348. *
  34349. * For the target's position to be changed to anything other
  34350. * than the default, it must be added to the scene.
  34351. *
  34352. * It is also possible to set the target to be another 3D object
  34353. * in the scene. The light will now track the target object.
  34354. *
  34355. * @type {Object3D}
  34356. */
  34357. this.target = new Object3D();
  34358. /**
  34359. * Maximum range of the light. `0` means no limit.
  34360. *
  34361. * @type {number}
  34362. * @default 0
  34363. */
  34364. this.distance = distance;
  34365. /**
  34366. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  34367. *
  34368. * @type {number}
  34369. * @default Math.PI/3
  34370. */
  34371. this.angle = angle;
  34372. /**
  34373. * Percent of the spotlight cone that is attenuated due to penumbra.
  34374. * Value range is `[0,1]`.
  34375. *
  34376. * @type {number}
  34377. * @default 0
  34378. */
  34379. this.penumbra = penumbra;
  34380. /**
  34381. * The amount the light dims along the distance of the light. In context of
  34382. * physically-correct rendering the default value should not be changed.
  34383. *
  34384. * @type {number}
  34385. * @default 2
  34386. */
  34387. this.decay = decay;
  34388. /**
  34389. * A texture used to modulate the color of the light. The spot light
  34390. * color is mixed with the RGB value of this texture, with a ratio
  34391. * corresponding to its alpha value. The cookie-like masking effect is
  34392. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  34393. *
  34394. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  34395. *
  34396. * @type {?Texture}
  34397. * @default null
  34398. */
  34399. this.map = null;
  34400. /**
  34401. * This property holds the light's shadow configuration.
  34402. *
  34403. * @type {SpotLightShadow}
  34404. */
  34405. this.shadow = new SpotLightShadow();
  34406. }
  34407. /**
  34408. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34409. * Changing the power will also change the light's intensity.
  34410. *
  34411. * @type {number}
  34412. */
  34413. get power() {
  34414. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34415. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  34416. return this.intensity * Math.PI;
  34417. }
  34418. set power( power ) {
  34419. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34420. this.intensity = power / Math.PI;
  34421. }
  34422. dispose() {
  34423. super.dispose();
  34424. this.shadow.dispose();
  34425. }
  34426. copy( source, recursive ) {
  34427. super.copy( source, recursive );
  34428. this.distance = source.distance;
  34429. this.angle = source.angle;
  34430. this.penumbra = source.penumbra;
  34431. this.decay = source.decay;
  34432. this.target = source.target.clone();
  34433. this.map = source.map;
  34434. this.shadow = source.shadow.clone();
  34435. return this;
  34436. }
  34437. toJSON( meta ) {
  34438. const data = super.toJSON( meta );
  34439. data.object.distance = this.distance;
  34440. data.object.angle = this.angle;
  34441. data.object.decay = this.decay;
  34442. data.object.penumbra = this.penumbra;
  34443. data.object.target = this.target.uuid;
  34444. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  34445. data.object.shadow = this.shadow.toJSON();
  34446. return data;
  34447. }
  34448. }
  34449. /**
  34450. * Represents the shadow configuration of point lights.
  34451. *
  34452. * @augments LightShadow
  34453. */
  34454. class PointLightShadow extends LightShadow {
  34455. /**
  34456. * Constructs a new point light shadow.
  34457. */
  34458. constructor() {
  34459. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  34460. /**
  34461. * This flag can be used for type testing.
  34462. *
  34463. * @type {boolean}
  34464. * @readonly
  34465. * @default true
  34466. */
  34467. this.isPointLightShadow = true;
  34468. }
  34469. }
  34470. /**
  34471. * A light that gets emitted from a single point in all directions. A common
  34472. * use case for this is to replicate the light emitted from a bare
  34473. * lightbulb.
  34474. *
  34475. * This light can cast shadows - see the {@link PointLightShadow} for details.
  34476. *
  34477. * ```js
  34478. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  34479. * light.position.set( 50, 50, 50 );
  34480. * scene.add( light );
  34481. * ```
  34482. *
  34483. * @augments Light
  34484. */
  34485. class PointLight extends Light {
  34486. /**
  34487. * Constructs a new point light.
  34488. *
  34489. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34490. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  34491. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  34492. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  34493. */
  34494. constructor( color, intensity, distance = 0, decay = 2 ) {
  34495. super( color, intensity );
  34496. /**
  34497. * This flag can be used for type testing.
  34498. *
  34499. * @type {boolean}
  34500. * @readonly
  34501. * @default true
  34502. */
  34503. this.isPointLight = true;
  34504. this.type = 'PointLight';
  34505. /**
  34506. * When distance is zero, light will attenuate according to inverse-square
  34507. * law to infinite distance. When distance is non-zero, light will attenuate
  34508. * according to inverse-square law until near the distance cutoff, where it
  34509. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  34510. * physically correct.
  34511. *
  34512. * @type {number}
  34513. * @default 0
  34514. */
  34515. this.distance = distance;
  34516. /**
  34517. * The amount the light dims along the distance of the light. In context of
  34518. * physically-correct rendering the default value should not be changed.
  34519. *
  34520. * @type {number}
  34521. * @default 2
  34522. */
  34523. this.decay = decay;
  34524. /**
  34525. * This property holds the light's shadow configuration.
  34526. *
  34527. * @type {PointLightShadow}
  34528. */
  34529. this.shadow = new PointLightShadow();
  34530. }
  34531. /**
  34532. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34533. * Changing the power will also change the light's intensity.
  34534. *
  34535. * @type {number}
  34536. */
  34537. get power() {
  34538. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34539. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  34540. return this.intensity * 4 * Math.PI;
  34541. }
  34542. set power( power ) {
  34543. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34544. this.intensity = power / ( 4 * Math.PI );
  34545. }
  34546. dispose() {
  34547. super.dispose();
  34548. this.shadow.dispose();
  34549. }
  34550. copy( source, recursive ) {
  34551. super.copy( source, recursive );
  34552. this.distance = source.distance;
  34553. this.decay = source.decay;
  34554. this.shadow = source.shadow.clone();
  34555. return this;
  34556. }
  34557. toJSON( meta ) {
  34558. const data = super.toJSON( meta );
  34559. data.object.distance = this.distance;
  34560. data.object.decay = this.decay;
  34561. data.object.shadow = this.shadow.toJSON();
  34562. return data;
  34563. }
  34564. }
  34565. /**
  34566. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  34567. *
  34568. * In this projection mode, an object's size in the rendered image stays
  34569. * constant regardless of its distance from the camera. This can be useful
  34570. * for rendering 2D scenes and UI elements, amongst other things.
  34571. *
  34572. * ```js
  34573. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  34574. * scene.add( camera );
  34575. * ```
  34576. *
  34577. * @augments Camera
  34578. */
  34579. class OrthographicCamera extends Camera {
  34580. /**
  34581. * Constructs a new orthographic camera.
  34582. *
  34583. * @param {number} [left=-1] - The left plane of the camera's frustum.
  34584. * @param {number} [right=1] - The right plane of the camera's frustum.
  34585. * @param {number} [top=1] - The top plane of the camera's frustum.
  34586. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  34587. * @param {number} [near=0.1] - The camera's near plane.
  34588. * @param {number} [far=2000] - The camera's far plane.
  34589. */
  34590. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  34591. super();
  34592. /**
  34593. * This flag can be used for type testing.
  34594. *
  34595. * @type {boolean}
  34596. * @readonly
  34597. * @default true
  34598. */
  34599. this.isOrthographicCamera = true;
  34600. this.type = 'OrthographicCamera';
  34601. /**
  34602. * The zoom factor of the camera.
  34603. *
  34604. * @type {number}
  34605. * @default 1
  34606. */
  34607. this.zoom = 1;
  34608. /**
  34609. * Represents the frustum window specification. This property should not be edited
  34610. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34611. *
  34612. * @type {?Object}
  34613. * @default null
  34614. */
  34615. this.view = null;
  34616. /**
  34617. * The left plane of the camera's frustum.
  34618. *
  34619. * @type {number}
  34620. * @default -1
  34621. */
  34622. this.left = left;
  34623. /**
  34624. * The right plane of the camera's frustum.
  34625. *
  34626. * @type {number}
  34627. * @default 1
  34628. */
  34629. this.right = right;
  34630. /**
  34631. * The top plane of the camera's frustum.
  34632. *
  34633. * @type {number}
  34634. * @default 1
  34635. */
  34636. this.top = top;
  34637. /**
  34638. * The bottom plane of the camera's frustum.
  34639. *
  34640. * @type {number}
  34641. * @default -1
  34642. */
  34643. this.bottom = bottom;
  34644. /**
  34645. * The camera's near plane. The valid range is greater than `0`
  34646. * and less than the current value of {@link OrthographicCamera#far}.
  34647. *
  34648. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34649. * valid value for an orthographic camera's near plane.
  34650. *
  34651. * @type {number}
  34652. * @default 0.1
  34653. */
  34654. this.near = near;
  34655. /**
  34656. * The camera's far plane. Must be greater than the
  34657. * current value of {@link OrthographicCamera#near}.
  34658. *
  34659. * @type {number}
  34660. * @default 2000
  34661. */
  34662. this.far = far;
  34663. this.updateProjectionMatrix();
  34664. }
  34665. copy( source, recursive ) {
  34666. super.copy( source, recursive );
  34667. this.left = source.left;
  34668. this.right = source.right;
  34669. this.top = source.top;
  34670. this.bottom = source.bottom;
  34671. this.near = source.near;
  34672. this.far = source.far;
  34673. this.zoom = source.zoom;
  34674. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34675. return this;
  34676. }
  34677. /**
  34678. * Sets an offset in a larger frustum. This is useful for multi-window or
  34679. * multi-monitor/multi-machine setups.
  34680. *
  34681. * @param {number} fullWidth - The full width of multiview setup.
  34682. * @param {number} fullHeight - The full height of multiview setup.
  34683. * @param {number} x - The horizontal offset of the subcamera.
  34684. * @param {number} y - The vertical offset of the subcamera.
  34685. * @param {number} width - The width of subcamera.
  34686. * @param {number} height - The height of subcamera.
  34687. * @see {@link PerspectiveCamera#setViewOffset}
  34688. */
  34689. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34690. if ( this.view === null ) {
  34691. this.view = {
  34692. enabled: true,
  34693. fullWidth: 1,
  34694. fullHeight: 1,
  34695. offsetX: 0,
  34696. offsetY: 0,
  34697. width: 1,
  34698. height: 1
  34699. };
  34700. }
  34701. this.view.enabled = true;
  34702. this.view.fullWidth = fullWidth;
  34703. this.view.fullHeight = fullHeight;
  34704. this.view.offsetX = x;
  34705. this.view.offsetY = y;
  34706. this.view.width = width;
  34707. this.view.height = height;
  34708. this.updateProjectionMatrix();
  34709. }
  34710. /**
  34711. * Removes the view offset from the projection matrix.
  34712. */
  34713. clearViewOffset() {
  34714. if ( this.view !== null ) {
  34715. this.view.enabled = false;
  34716. }
  34717. this.updateProjectionMatrix();
  34718. }
  34719. /**
  34720. * Updates the camera's projection matrix. Must be called after any change of
  34721. * camera properties.
  34722. */
  34723. updateProjectionMatrix() {
  34724. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34725. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34726. const cx = ( this.right + this.left ) / 2;
  34727. const cy = ( this.top + this.bottom ) / 2;
  34728. let left = cx - dx;
  34729. let right = cx + dx;
  34730. let top = cy + dy;
  34731. let bottom = cy - dy;
  34732. if ( this.view !== null && this.view.enabled ) {
  34733. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34734. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34735. left += scaleW * this.view.offsetX;
  34736. right = left + scaleW * this.view.width;
  34737. top -= scaleH * this.view.offsetY;
  34738. bottom = top - scaleH * this.view.height;
  34739. }
  34740. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34741. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34742. }
  34743. toJSON( meta ) {
  34744. const data = super.toJSON( meta );
  34745. data.object.zoom = this.zoom;
  34746. data.object.left = this.left;
  34747. data.object.right = this.right;
  34748. data.object.top = this.top;
  34749. data.object.bottom = this.bottom;
  34750. data.object.near = this.near;
  34751. data.object.far = this.far;
  34752. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34753. return data;
  34754. }
  34755. }
  34756. /**
  34757. * Represents the shadow configuration of directional lights.
  34758. *
  34759. * @augments LightShadow
  34760. */
  34761. class DirectionalLightShadow extends LightShadow {
  34762. /**
  34763. * Constructs a new directional light shadow.
  34764. */
  34765. constructor() {
  34766. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34767. /**
  34768. * This flag can be used for type testing.
  34769. *
  34770. * @type {boolean}
  34771. * @readonly
  34772. * @default true
  34773. */
  34774. this.isDirectionalLightShadow = true;
  34775. }
  34776. }
  34777. /**
  34778. * A light that gets emitted in a specific direction. This light will behave
  34779. * as though it is infinitely far away and the rays produced from it are all
  34780. * parallel. The common use case for this is to simulate daylight; the sun is
  34781. * far enough away that its position can be considered to be infinite, and
  34782. * all light rays coming from it are parallel.
  34783. *
  34784. * A common point of confusion for directional lights is that setting the
  34785. * rotation has no effect. This is because three.js's DirectionalLight is the
  34786. * equivalent to what is often called a 'Target Direct Light' in other
  34787. * applications.
  34788. *
  34789. * This means that its direction is calculated as pointing from the light's
  34790. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34791. * (as opposed to a 'Free Direct Light' that just has a rotation
  34792. * component).
  34793. *
  34794. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34795. *
  34796. * ```js
  34797. * // White directional light at half intensity shining from the top.
  34798. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34799. * scene.add( directionalLight );
  34800. * ```
  34801. *
  34802. * @augments Light
  34803. */
  34804. class DirectionalLight extends Light {
  34805. /**
  34806. * Constructs a new directional light.
  34807. *
  34808. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34809. * @param {number} [intensity=1] - The light's strength/intensity.
  34810. */
  34811. constructor( color, intensity ) {
  34812. super( color, intensity );
  34813. /**
  34814. * This flag can be used for type testing.
  34815. *
  34816. * @type {boolean}
  34817. * @readonly
  34818. * @default true
  34819. */
  34820. this.isDirectionalLight = true;
  34821. this.type = 'DirectionalLight';
  34822. this.position.copy( Object3D.DEFAULT_UP );
  34823. this.updateMatrix();
  34824. /**
  34825. * The directional light points from its position to the
  34826. * target's position.
  34827. *
  34828. * For the target's position to be changed to anything other
  34829. * than the default, it must be added to the scene.
  34830. *
  34831. * It is also possible to set the target to be another 3D object
  34832. * in the scene. The light will now track the target object.
  34833. *
  34834. * @type {Object3D}
  34835. */
  34836. this.target = new Object3D();
  34837. /**
  34838. * This property holds the light's shadow configuration.
  34839. *
  34840. * @type {DirectionalLightShadow}
  34841. */
  34842. this.shadow = new DirectionalLightShadow();
  34843. }
  34844. dispose() {
  34845. super.dispose();
  34846. this.shadow.dispose();
  34847. }
  34848. copy( source ) {
  34849. super.copy( source );
  34850. this.target = source.target.clone();
  34851. this.shadow = source.shadow.clone();
  34852. return this;
  34853. }
  34854. toJSON( meta ) {
  34855. const data = super.toJSON( meta );
  34856. data.object.shadow = this.shadow.toJSON();
  34857. data.object.target = this.target.uuid;
  34858. return data;
  34859. }
  34860. }
  34861. /**
  34862. * This light globally illuminates all objects in the scene equally.
  34863. *
  34864. * It cannot be used to cast shadows as it does not have a direction.
  34865. *
  34866. * ```js
  34867. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34868. * scene.add( light );
  34869. * ```
  34870. *
  34871. * @augments Light
  34872. */
  34873. class AmbientLight extends Light {
  34874. /**
  34875. * Constructs a new ambient light.
  34876. *
  34877. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34878. * @param {number} [intensity=1] - The light's strength/intensity.
  34879. */
  34880. constructor( color, intensity ) {
  34881. super( color, intensity );
  34882. /**
  34883. * This flag can be used for type testing.
  34884. *
  34885. * @type {boolean}
  34886. * @readonly
  34887. * @default true
  34888. */
  34889. this.isAmbientLight = true;
  34890. this.type = 'AmbientLight';
  34891. }
  34892. }
  34893. /**
  34894. * This class emits light uniformly across the face a rectangular plane.
  34895. * This light type can be used to simulate light sources such as bright
  34896. * windows or strip lighting.
  34897. *
  34898. * Important Notes:
  34899. *
  34900. * - There is no shadow support.
  34901. * - Only PBR materials are supported.
  34902. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34903. * into your app and init the uniforms/textures.
  34904. *
  34905. * ```js
  34906. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34907. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34908. *
  34909. * const intensity = 1; const width = 10; const height = 10;
  34910. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34911. * rectLight.position.set( 5, 5, 0 );
  34912. * rectLight.lookAt( 0, 0, 0 );
  34913. * scene.add( rectLight )
  34914. * ```
  34915. *
  34916. * @augments Light
  34917. */
  34918. class RectAreaLight extends Light {
  34919. /**
  34920. * Constructs a new area light.
  34921. *
  34922. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34923. * @param {number} [intensity=1] - The light's strength/intensity.
  34924. * @param {number} [width=10] - The width of the light.
  34925. * @param {number} [height=10] - The height of the light.
  34926. */
  34927. constructor( color, intensity, width = 10, height = 10 ) {
  34928. super( color, intensity );
  34929. /**
  34930. * This flag can be used for type testing.
  34931. *
  34932. * @type {boolean}
  34933. * @readonly
  34934. * @default true
  34935. */
  34936. this.isRectAreaLight = true;
  34937. this.type = 'RectAreaLight';
  34938. /**
  34939. * The width of the light.
  34940. *
  34941. * @type {number}
  34942. * @default 10
  34943. */
  34944. this.width = width;
  34945. /**
  34946. * The height of the light.
  34947. *
  34948. * @type {number}
  34949. * @default 10
  34950. */
  34951. this.height = height;
  34952. }
  34953. /**
  34954. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34955. * Changing the power will also change the light's intensity.
  34956. *
  34957. * @type {number}
  34958. */
  34959. get power() {
  34960. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34961. return this.intensity * this.width * this.height * Math.PI;
  34962. }
  34963. set power( power ) {
  34964. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34965. this.intensity = power / ( this.width * this.height * Math.PI );
  34966. }
  34967. copy( source ) {
  34968. super.copy( source );
  34969. this.width = source.width;
  34970. this.height = source.height;
  34971. return this;
  34972. }
  34973. toJSON( meta ) {
  34974. const data = super.toJSON( meta );
  34975. data.object.width = this.width;
  34976. data.object.height = this.height;
  34977. return data;
  34978. }
  34979. }
  34980. /**
  34981. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34982. * to encode lighting information.
  34983. *
  34984. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34985. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34986. */
  34987. class SphericalHarmonics3 {
  34988. /**
  34989. * Constructs a new spherical harmonics.
  34990. */
  34991. constructor() {
  34992. /**
  34993. * This flag can be used for type testing.
  34994. *
  34995. * @type {boolean}
  34996. * @readonly
  34997. * @default true
  34998. */
  34999. this.isSphericalHarmonics3 = true;
  35000. /**
  35001. * An array holding the (9) SH coefficients.
  35002. *
  35003. * @type {Array<Vector3>}
  35004. */
  35005. this.coefficients = [];
  35006. for ( let i = 0; i < 9; i ++ ) {
  35007. this.coefficients.push( new Vector3() );
  35008. }
  35009. }
  35010. /**
  35011. * Sets the given SH coefficients to this instance by copying
  35012. * the values.
  35013. *
  35014. * @param {Array<Vector3>} coefficients - The SH coefficients.
  35015. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35016. */
  35017. set( coefficients ) {
  35018. for ( let i = 0; i < 9; i ++ ) {
  35019. this.coefficients[ i ].copy( coefficients[ i ] );
  35020. }
  35021. return this;
  35022. }
  35023. /**
  35024. * Sets all SH coefficients to `0`.
  35025. *
  35026. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35027. */
  35028. zero() {
  35029. for ( let i = 0; i < 9; i ++ ) {
  35030. this.coefficients[ i ].set( 0, 0, 0 );
  35031. }
  35032. return this;
  35033. }
  35034. /**
  35035. * Returns the radiance in the direction of the given normal.
  35036. *
  35037. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  35038. * @param {Vector3} target - The target vector that is used to store the method's result.
  35039. * @return {Vector3} The radiance.
  35040. */
  35041. getAt( normal, target ) {
  35042. // normal is assumed to be unit length
  35043. const x = normal.x, y = normal.y, z = normal.z;
  35044. const coeff = this.coefficients;
  35045. // band 0
  35046. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  35047. // band 1
  35048. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  35049. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  35050. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  35051. // band 2
  35052. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  35053. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  35054. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  35055. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  35056. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  35057. return target;
  35058. }
  35059. /**
  35060. * Returns the irradiance (radiance convolved with cosine lobe) in the
  35061. * direction of the given normal.
  35062. *
  35063. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  35064. * @param {Vector3} target - The target vector that is used to store the method's result.
  35065. * @return {Vector3} The irradiance.
  35066. */
  35067. getIrradianceAt( normal, target ) {
  35068. // normal is assumed to be unit length
  35069. const x = normal.x, y = normal.y, z = normal.z;
  35070. const coeff = this.coefficients;
  35071. // band 0
  35072. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  35073. // band 1
  35074. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  35075. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  35076. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  35077. // band 2
  35078. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  35079. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  35080. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  35081. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  35082. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  35083. return target;
  35084. }
  35085. /**
  35086. * Adds the given SH to this instance.
  35087. *
  35088. * @param {SphericalHarmonics3} sh - The SH to add.
  35089. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35090. */
  35091. add( sh ) {
  35092. for ( let i = 0; i < 9; i ++ ) {
  35093. this.coefficients[ i ].add( sh.coefficients[ i ] );
  35094. }
  35095. return this;
  35096. }
  35097. /**
  35098. * A convenience method for performing {@link SphericalHarmonics3#add} and
  35099. * {@link SphericalHarmonics3#scale} at once.
  35100. *
  35101. * @param {SphericalHarmonics3} sh - The SH to add.
  35102. * @param {number} s - The scale factor.
  35103. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35104. */
  35105. addScaledSH( sh, s ) {
  35106. for ( let i = 0; i < 9; i ++ ) {
  35107. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  35108. }
  35109. return this;
  35110. }
  35111. /**
  35112. * Scales this SH by the given scale factor.
  35113. *
  35114. * @param {number} s - The scale factor.
  35115. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35116. */
  35117. scale( s ) {
  35118. for ( let i = 0; i < 9; i ++ ) {
  35119. this.coefficients[ i ].multiplyScalar( s );
  35120. }
  35121. return this;
  35122. }
  35123. /**
  35124. * Linear interpolates between the given SH and this instance by the given
  35125. * alpha factor.
  35126. *
  35127. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  35128. * @param {number} alpha - The alpha factor.
  35129. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35130. */
  35131. lerp( sh, alpha ) {
  35132. for ( let i = 0; i < 9; i ++ ) {
  35133. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  35134. }
  35135. return this;
  35136. }
  35137. /**
  35138. * Returns `true` if this spherical harmonics is equal with the given one.
  35139. *
  35140. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  35141. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  35142. */
  35143. equals( sh ) {
  35144. for ( let i = 0; i < 9; i ++ ) {
  35145. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  35146. return false;
  35147. }
  35148. }
  35149. return true;
  35150. }
  35151. /**
  35152. * Copies the values of the given spherical harmonics to this instance.
  35153. *
  35154. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  35155. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35156. */
  35157. copy( sh ) {
  35158. return this.set( sh.coefficients );
  35159. }
  35160. /**
  35161. * Returns a new spherical harmonics with copied values from this instance.
  35162. *
  35163. * @return {SphericalHarmonics3} A clone of this instance.
  35164. */
  35165. clone() {
  35166. return new this.constructor().copy( this );
  35167. }
  35168. /**
  35169. * Sets the SH coefficients of this instance from the given array.
  35170. *
  35171. * @param {Array<number>} array - An array holding the SH coefficients.
  35172. * @param {number} [offset=0] - The array offset where to start copying.
  35173. * @return {SphericalHarmonics3} A clone of this instance.
  35174. */
  35175. fromArray( array, offset = 0 ) {
  35176. const coefficients = this.coefficients;
  35177. for ( let i = 0; i < 9; i ++ ) {
  35178. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  35179. }
  35180. return this;
  35181. }
  35182. /**
  35183. * Returns an array with the SH coefficients, or copies them into the provided
  35184. * array. The coefficients are represented as numbers.
  35185. *
  35186. * @param {Array<number>} [array=[]] - The target array.
  35187. * @param {number} [offset=0] - The array offset where to start copying.
  35188. * @return {Array<number>} An array with flat SH coefficients.
  35189. */
  35190. toArray( array = [], offset = 0 ) {
  35191. const coefficients = this.coefficients;
  35192. for ( let i = 0; i < 9; i ++ ) {
  35193. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  35194. }
  35195. return array;
  35196. }
  35197. /**
  35198. * Computes the SH basis for the given normal vector.
  35199. *
  35200. * @param {Vector3} normal - The normal.
  35201. * @param {Array<number>} shBasis - The target array holding the SH basis.
  35202. */
  35203. static getBasisAt( normal, shBasis ) {
  35204. // normal is assumed to be unit length
  35205. const x = normal.x, y = normal.y, z = normal.z;
  35206. // band 0
  35207. shBasis[ 0 ] = 0.282095;
  35208. // band 1
  35209. shBasis[ 1 ] = 0.488603 * y;
  35210. shBasis[ 2 ] = 0.488603 * z;
  35211. shBasis[ 3 ] = 0.488603 * x;
  35212. // band 2
  35213. shBasis[ 4 ] = 1.092548 * x * y;
  35214. shBasis[ 5 ] = 1.092548 * y * z;
  35215. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  35216. shBasis[ 7 ] = 1.092548 * x * z;
  35217. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  35218. }
  35219. }
  35220. /**
  35221. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  35222. * classical light sources (e.g. directional, point or spot lights), light
  35223. * probes do not emit light. Instead they store information about light
  35224. * passing through 3D space. During rendering, the light that hits a 3D
  35225. * object is approximated by using the data from the light probe.
  35226. *
  35227. * Light probes are usually created from (radiance) environment maps. The
  35228. * class {@link LightProbeGenerator} can be used to create light probes from
  35229. * cube textures or render targets. However, light estimation data could also
  35230. * be provided in other forms e.g. by WebXR. This enables the rendering of
  35231. * augmented reality content that reacts to real world lighting.
  35232. *
  35233. * The current probe implementation in three.js supports so-called diffuse
  35234. * light probes. This type of light probe is functionally equivalent to an
  35235. * irradiance environment map.
  35236. *
  35237. * @augments Light
  35238. */
  35239. class LightProbe extends Light {
  35240. /**
  35241. * Constructs a new light probe.
  35242. *
  35243. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  35244. * @param {number} [intensity=1] - The light's strength/intensity.
  35245. */
  35246. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  35247. super( undefined, intensity );
  35248. /**
  35249. * This flag can be used for type testing.
  35250. *
  35251. * @type {boolean}
  35252. * @readonly
  35253. * @default true
  35254. */
  35255. this.isLightProbe = true;
  35256. /**
  35257. * A light probe uses spherical harmonics to encode lighting information.
  35258. *
  35259. * @type {SphericalHarmonics3}
  35260. */
  35261. this.sh = sh;
  35262. }
  35263. copy( source ) {
  35264. super.copy( source );
  35265. this.sh.copy( source.sh );
  35266. return this;
  35267. }
  35268. toJSON( meta ) {
  35269. const data = super.toJSON( meta );
  35270. data.object.sh = this.sh.toArray();
  35271. return data;
  35272. }
  35273. }
  35274. const _customMaterials = {};
  35275. /**
  35276. * Class for loading materials. The files are internally
  35277. * loaded via {@link FileLoader}.
  35278. *
  35279. * ```js
  35280. * const loader = new THREE.MaterialLoader();
  35281. * const material = await loader.loadAsync( 'material.json' );
  35282. * ```
  35283. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  35284. *
  35285. * @augments Loader
  35286. */
  35287. class MaterialLoader extends Loader {
  35288. /**
  35289. * Constructs a new material loader.
  35290. *
  35291. * @param {LoadingManager} [manager] - The loading manager.
  35292. */
  35293. constructor( manager ) {
  35294. super( manager );
  35295. /**
  35296. * A dictionary holding textures used by the material.
  35297. *
  35298. * @type {Object<string,Texture>}
  35299. */
  35300. this.textures = {};
  35301. }
  35302. /**
  35303. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  35304. *
  35305. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35306. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  35307. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35308. * @param {onErrorCallback} onError - Executed when errors occur.
  35309. */
  35310. load( url, onLoad, onProgress, onError ) {
  35311. const scope = this;
  35312. const loader = new FileLoader( scope.manager );
  35313. loader.setPath( scope.path );
  35314. loader.setRequestHeader( scope.requestHeader );
  35315. loader.setWithCredentials( scope.withCredentials );
  35316. loader.load( url, function ( text ) {
  35317. try {
  35318. onLoad( scope.parse( JSON.parse( text ) ) );
  35319. } catch ( e ) {
  35320. if ( onError ) {
  35321. onError( e );
  35322. } else {
  35323. error( e );
  35324. }
  35325. scope.manager.itemError( url );
  35326. }
  35327. }, onProgress, onError );
  35328. }
  35329. /**
  35330. * Parses the given JSON object and returns a material.
  35331. *
  35332. * @param {Object} json - The serialized material.
  35333. * @return {Material} The parsed material.
  35334. */
  35335. parse( json ) {
  35336. const material = this.createMaterialFromType( json.type );
  35337. material.fromJSON( json, this.textures );
  35338. return material;
  35339. }
  35340. /**
  35341. * Textures are not embedded in the material JSON so they have
  35342. * to be injected before the loading process starts.
  35343. *
  35344. * @param {Object} value - A dictionary holding textures for material properties.
  35345. * @return {MaterialLoader} A reference to this material loader.
  35346. */
  35347. setTextures( value ) {
  35348. this.textures = value;
  35349. return this;
  35350. }
  35351. /**
  35352. * Creates a material for the given type.
  35353. *
  35354. * @param {string} type - The material type.
  35355. * @return {Material} The new material.
  35356. */
  35357. createMaterialFromType( type ) {
  35358. return MaterialLoader.createMaterialFromType( type );
  35359. }
  35360. /**
  35361. * Creates a material for the given type.
  35362. *
  35363. * @static
  35364. * @param {string} type - The material type.
  35365. * @return {Material} The new material.
  35366. */
  35367. static createMaterialFromType( type ) {
  35368. const materialLib = {
  35369. ShadowMaterial,
  35370. SpriteMaterial,
  35371. RawShaderMaterial,
  35372. ShaderMaterial,
  35373. PointsMaterial,
  35374. MeshPhysicalMaterial,
  35375. MeshStandardMaterial,
  35376. MeshPhongMaterial,
  35377. MeshToonMaterial,
  35378. MeshNormalMaterial,
  35379. MeshLambertMaterial,
  35380. MeshDepthMaterial,
  35381. MeshDistanceMaterial,
  35382. MeshBasicMaterial,
  35383. MeshMatcapMaterial,
  35384. LineDashedMaterial,
  35385. LineBasicMaterial,
  35386. Material,
  35387. ... _customMaterials
  35388. };
  35389. const MaterialType = materialLib[ type ];
  35390. let materialInstance;
  35391. if ( MaterialType === undefined ) {
  35392. warnOnce( `MaterialLoader: Unknown material type "${ type }". Use .registerMaterial() before starting the deserialization process.` );
  35393. materialInstance = new Material();
  35394. } else {
  35395. materialInstance = new MaterialType();
  35396. }
  35397. return materialInstance;
  35398. }
  35399. /**
  35400. * Registers the given material at the internal
  35401. * material library.
  35402. *
  35403. * @static
  35404. * @param {string} type - The material type.
  35405. * @param {Material.constructor} materialClass - The material class.
  35406. */
  35407. static registerMaterial( type, materialClass ) {
  35408. _customMaterials[ type ] = materialClass;
  35409. }
  35410. }
  35411. /**
  35412. * A class with loader utility functions.
  35413. */
  35414. class LoaderUtils {
  35415. /**
  35416. * Extracts the base URL from the given URL.
  35417. *
  35418. * @param {string} url -The URL to extract the base URL from.
  35419. * @return {string} The extracted base URL.
  35420. */
  35421. static extractUrlBase( url ) {
  35422. const index = url.lastIndexOf( '/' );
  35423. if ( index === -1 ) return './';
  35424. return url.slice( 0, index + 1 );
  35425. }
  35426. /**
  35427. * Resolves relative URLs against the given path. Absolute paths, data urls,
  35428. * and blob URLs will be returned as is. Invalid URLs will return an empty
  35429. * string.
  35430. *
  35431. * @param {string} url -The URL to resolve.
  35432. * @param {string} path - The base path for relative URLs to be resolved against.
  35433. * @return {string} The resolved URL.
  35434. */
  35435. static resolveURL( url, path ) {
  35436. // Invalid URL
  35437. if ( typeof url !== 'string' || url === '' ) return '';
  35438. // Host Relative URL
  35439. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35440. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35441. }
  35442. // Absolute URL http://,https://,//
  35443. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35444. // Data URI
  35445. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35446. // Blob URL
  35447. if ( /^blob:.*$/i.test( url ) ) return url;
  35448. // Relative URL
  35449. return path + url;
  35450. }
  35451. }
  35452. /**
  35453. * An instanced version of a geometry.
  35454. */
  35455. class InstancedBufferGeometry extends BufferGeometry {
  35456. /**
  35457. * Constructs a new instanced buffer geometry.
  35458. */
  35459. constructor() {
  35460. super();
  35461. /**
  35462. * This flag can be used for type testing.
  35463. *
  35464. * @type {boolean}
  35465. * @readonly
  35466. * @default true
  35467. */
  35468. this.isInstancedBufferGeometry = true;
  35469. this.type = 'InstancedBufferGeometry';
  35470. /**
  35471. * The instance count.
  35472. *
  35473. * @type {number}
  35474. * @default Infinity
  35475. */
  35476. this.instanceCount = Infinity;
  35477. }
  35478. copy( source ) {
  35479. super.copy( source );
  35480. this.instanceCount = source.instanceCount;
  35481. return this;
  35482. }
  35483. toJSON() {
  35484. const data = super.toJSON();
  35485. data.instanceCount = this.instanceCount;
  35486. data.isInstancedBufferGeometry = true;
  35487. return data;
  35488. }
  35489. }
  35490. /**
  35491. * Class for loading geometries. The files are internally
  35492. * loaded via {@link FileLoader}.
  35493. *
  35494. * ```js
  35495. * const loader = new THREE.BufferGeometryLoader();
  35496. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35497. *
  35498. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35499. * const object = new THREE.Mesh( geometry, material );
  35500. * scene.add( object );
  35501. * ```
  35502. *
  35503. * @augments Loader
  35504. */
  35505. class BufferGeometryLoader extends Loader {
  35506. /**
  35507. * Constructs a new geometry loader.
  35508. *
  35509. * @param {LoadingManager} [manager] - The loading manager.
  35510. */
  35511. constructor( manager ) {
  35512. super( manager );
  35513. }
  35514. /**
  35515. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35516. *
  35517. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35518. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35519. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35520. * @param {onErrorCallback} onError - Executed when errors occur.
  35521. */
  35522. load( url, onLoad, onProgress, onError ) {
  35523. const scope = this;
  35524. const loader = new FileLoader( scope.manager );
  35525. loader.setPath( scope.path );
  35526. loader.setRequestHeader( scope.requestHeader );
  35527. loader.setWithCredentials( scope.withCredentials );
  35528. loader.load( url, function ( text ) {
  35529. try {
  35530. onLoad( scope.parse( JSON.parse( text ) ) );
  35531. } catch ( e ) {
  35532. if ( onError ) {
  35533. onError( e );
  35534. } else {
  35535. error( e );
  35536. }
  35537. scope.manager.itemError( url );
  35538. }
  35539. }, onProgress, onError );
  35540. }
  35541. /**
  35542. * Parses the given JSON object and returns a geometry.
  35543. *
  35544. * @param {Object} json - The serialized geometry.
  35545. * @return {BufferGeometry} The parsed geometry.
  35546. */
  35547. parse( json ) {
  35548. const interleavedBufferMap = {};
  35549. const arrayBufferMap = {};
  35550. function getInterleavedBuffer( json, uuid ) {
  35551. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35552. const interleavedBuffers = json.interleavedBuffers;
  35553. const interleavedBuffer = interleavedBuffers[ uuid ];
  35554. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35555. const array = getTypedArray( interleavedBuffer.type, buffer );
  35556. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35557. ib.uuid = interleavedBuffer.uuid;
  35558. interleavedBufferMap[ uuid ] = ib;
  35559. return ib;
  35560. }
  35561. function getArrayBuffer( json, uuid ) {
  35562. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35563. const arrayBuffers = json.arrayBuffers;
  35564. const arrayBuffer = arrayBuffers[ uuid ];
  35565. const ab = new Uint32Array( arrayBuffer ).buffer;
  35566. arrayBufferMap[ uuid ] = ab;
  35567. return ab;
  35568. }
  35569. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35570. const index = json.data.index;
  35571. if ( index !== undefined ) {
  35572. const typedArray = getTypedArray( index.type, index.array );
  35573. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35574. }
  35575. const attributes = json.data.attributes;
  35576. for ( const key in attributes ) {
  35577. const attribute = attributes[ key ];
  35578. let bufferAttribute;
  35579. if ( attribute.isInterleavedBufferAttribute ) {
  35580. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35581. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35582. } else {
  35583. const typedArray = getTypedArray( attribute.type, attribute.array );
  35584. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35585. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35586. }
  35587. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35588. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35589. geometry.setAttribute( key, bufferAttribute );
  35590. }
  35591. const morphAttributes = json.data.morphAttributes;
  35592. if ( morphAttributes ) {
  35593. for ( const key in morphAttributes ) {
  35594. const attributeArray = morphAttributes[ key ];
  35595. const array = [];
  35596. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35597. const attribute = attributeArray[ i ];
  35598. let bufferAttribute;
  35599. if ( attribute.isInterleavedBufferAttribute ) {
  35600. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35601. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35602. } else {
  35603. const typedArray = getTypedArray( attribute.type, attribute.array );
  35604. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35605. }
  35606. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35607. array.push( bufferAttribute );
  35608. }
  35609. geometry.morphAttributes[ key ] = array;
  35610. }
  35611. }
  35612. const morphTargetsRelative = json.data.morphTargetsRelative;
  35613. if ( morphTargetsRelative ) {
  35614. geometry.morphTargetsRelative = true;
  35615. }
  35616. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35617. if ( groups !== undefined ) {
  35618. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35619. const group = groups[ i ];
  35620. geometry.addGroup( group.start, group.count, group.materialIndex );
  35621. }
  35622. }
  35623. const boundingSphere = json.data.boundingSphere;
  35624. if ( boundingSphere !== undefined ) {
  35625. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35626. }
  35627. if ( json.name ) geometry.name = json.name;
  35628. if ( json.userData ) geometry.userData = json.userData;
  35629. return geometry;
  35630. }
  35631. }
  35632. const _customGeometries = {};
  35633. /**
  35634. * 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).
  35635. * The files are internally loaded via {@link FileLoader}.
  35636. *
  35637. * ```js
  35638. * const loader = new THREE.ObjectLoader();
  35639. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35640. * scene.add( obj );
  35641. *
  35642. * // Alternatively, to parse a previously loaded JSON structure
  35643. * const object = await loader.parseAsync( a_json_object );
  35644. * scene.add( object );
  35645. * ```
  35646. *
  35647. * @augments Loader
  35648. */
  35649. class ObjectLoader extends Loader {
  35650. /**
  35651. * Constructs a new object loader.
  35652. *
  35653. * @param {LoadingManager} [manager] - The loading manager.
  35654. */
  35655. constructor( manager ) {
  35656. super( manager );
  35657. }
  35658. /**
  35659. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35660. *
  35661. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35662. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35663. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35664. * @param {onErrorCallback} onError - Executed when errors occur.
  35665. */
  35666. load( url, onLoad, onProgress, onError ) {
  35667. const scope = this;
  35668. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35669. this.resourcePath = this.resourcePath || path;
  35670. const loader = new FileLoader( this.manager );
  35671. loader.setPath( this.path );
  35672. loader.setRequestHeader( this.requestHeader );
  35673. loader.setWithCredentials( this.withCredentials );
  35674. loader.load( url, function ( text ) {
  35675. let json = null;
  35676. try {
  35677. json = JSON.parse( text );
  35678. } catch ( e ) {
  35679. if ( onError !== undefined ) onError( e );
  35680. error( 'ObjectLoader: Can\'t parse ' + url + '.', e.message );
  35681. return;
  35682. }
  35683. const metadata = json.metadata;
  35684. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35685. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35686. error( 'ObjectLoader: Can\'t load ' + url );
  35687. return;
  35688. }
  35689. scope.parse( json, onLoad );
  35690. }, onProgress, onError );
  35691. }
  35692. /**
  35693. * Async version of {@link ObjectLoader#load}.
  35694. *
  35695. * @async
  35696. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35697. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35698. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35699. */
  35700. async loadAsync( url, onProgress ) {
  35701. const scope = this;
  35702. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35703. this.resourcePath = this.resourcePath || path;
  35704. const loader = new FileLoader( this.manager );
  35705. loader.setPath( this.path );
  35706. loader.setRequestHeader( this.requestHeader );
  35707. loader.setWithCredentials( this.withCredentials );
  35708. const text = await loader.loadAsync( url, onProgress );
  35709. let json;
  35710. try {
  35711. json = JSON.parse( text );
  35712. } catch ( e ) {
  35713. throw new Error( 'THREE.ObjectLoader: Can\'t parse ' + url + '. ' + e.message );
  35714. }
  35715. const metadata = json.metadata;
  35716. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35717. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35718. }
  35719. return await scope.parseAsync( json );
  35720. }
  35721. /**
  35722. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35723. * but can also be used directly to parse a previously loaded JSON structure.
  35724. *
  35725. * @param {Object} json - The serialized 3D object.
  35726. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35727. * @return {Object3D} The parsed 3D object.
  35728. */
  35729. parse( json, onLoad ) {
  35730. const animations = this.parseAnimations( json.animations );
  35731. const shapes = this.parseShapes( json.shapes );
  35732. const geometries = this.parseGeometries( json.geometries, shapes );
  35733. const images = this.parseImages( json.images, function () {
  35734. if ( onLoad !== undefined ) onLoad( object );
  35735. } );
  35736. const textures = this.parseTextures( json.textures, images );
  35737. const materials = this.parseMaterials( json.materials, textures );
  35738. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35739. const skeletons = this.parseSkeletons( json.skeletons, object );
  35740. this.bindSkeletons( object, skeletons );
  35741. this.bindLightTargets( object );
  35742. //
  35743. if ( onLoad !== undefined ) {
  35744. let hasImages = false;
  35745. for ( const uuid in images ) {
  35746. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35747. hasImages = true;
  35748. break;
  35749. }
  35750. }
  35751. if ( hasImages === false ) onLoad( object );
  35752. }
  35753. return object;
  35754. }
  35755. /**
  35756. * Async version of {@link ObjectLoader#parse}.
  35757. *
  35758. * @param {Object} json - The serialized 3D object.
  35759. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35760. */
  35761. async parseAsync( json ) {
  35762. const animations = this.parseAnimations( json.animations );
  35763. const shapes = this.parseShapes( json.shapes );
  35764. const geometries = this.parseGeometries( json.geometries, shapes );
  35765. const images = await this.parseImagesAsync( json.images );
  35766. const textures = this.parseTextures( json.textures, images );
  35767. const materials = this.parseMaterials( json.materials, textures );
  35768. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35769. const skeletons = this.parseSkeletons( json.skeletons, object );
  35770. this.bindSkeletons( object, skeletons );
  35771. this.bindLightTargets( object );
  35772. return object;
  35773. }
  35774. /**
  35775. * Registers the given geometry at the internal
  35776. * geometry library.
  35777. *
  35778. * @static
  35779. * @param {string} type - The geometry type.
  35780. * @param {BufferGeometry.constructor} geometryClass - The geometry class.
  35781. */
  35782. static registerGeometry( type, geometryClass ) {
  35783. _customGeometries[ type ] = geometryClass;
  35784. }
  35785. // internals
  35786. parseShapes( json ) {
  35787. const shapes = {};
  35788. if ( json !== undefined ) {
  35789. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35790. const shape = new Shape().fromJSON( json[ i ] );
  35791. shapes[ shape.uuid ] = shape;
  35792. }
  35793. }
  35794. return shapes;
  35795. }
  35796. parseSkeletons( json, object ) {
  35797. const skeletons = {};
  35798. const bones = {};
  35799. // generate bone lookup table
  35800. object.traverse( function ( child ) {
  35801. if ( child.isBone ) bones[ child.uuid ] = child;
  35802. } );
  35803. // create skeletons
  35804. if ( json !== undefined ) {
  35805. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35806. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35807. skeletons[ skeleton.uuid ] = skeleton;
  35808. }
  35809. }
  35810. return skeletons;
  35811. }
  35812. parseGeometries( json, shapes ) {
  35813. const geometries = {};
  35814. if ( json !== undefined ) {
  35815. const bufferGeometryLoader = new BufferGeometryLoader();
  35816. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35817. let geometry;
  35818. const data = json[ i ];
  35819. switch ( data.type ) {
  35820. case 'BufferGeometry':
  35821. case 'InstancedBufferGeometry':
  35822. geometry = bufferGeometryLoader.parse( data );
  35823. break;
  35824. default:
  35825. if ( data.type in Geometries ) {
  35826. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35827. } else if ( data.type in _customGeometries ) {
  35828. geometry = _customGeometries[ data.type ].fromJSON( data, shapes );
  35829. } else {
  35830. warn( `ObjectLoader: Unknown geometry type "${ data.type }". Use .registerGeometry() before starting the deserialization process.` );
  35831. }
  35832. }
  35833. geometry.uuid = data.uuid;
  35834. if ( data.name !== undefined ) geometry.name = data.name;
  35835. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35836. geometries[ data.uuid ] = geometry;
  35837. }
  35838. }
  35839. return geometries;
  35840. }
  35841. parseMaterials( json, textures ) {
  35842. const cache = {}; // MultiMaterial
  35843. const materials = {};
  35844. if ( json !== undefined ) {
  35845. const loader = new MaterialLoader();
  35846. loader.setTextures( textures );
  35847. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35848. const data = json[ i ];
  35849. if ( cache[ data.uuid ] === undefined ) {
  35850. cache[ data.uuid ] = loader.parse( data );
  35851. }
  35852. materials[ data.uuid ] = cache[ data.uuid ];
  35853. }
  35854. }
  35855. return materials;
  35856. }
  35857. parseAnimations( json ) {
  35858. const animations = {};
  35859. if ( json !== undefined ) {
  35860. for ( let i = 0; i < json.length; i ++ ) {
  35861. const data = json[ i ];
  35862. const clip = AnimationClip.parse( data );
  35863. animations[ clip.uuid ] = clip;
  35864. }
  35865. }
  35866. return animations;
  35867. }
  35868. parseImages( json, onLoad ) {
  35869. const scope = this;
  35870. const images = {};
  35871. let loader;
  35872. function loadImage( url ) {
  35873. url = scope.manager.resolveURL( url );
  35874. scope.manager.itemStart( url );
  35875. return loader.load( url, function () {
  35876. scope.manager.itemEnd( url );
  35877. }, undefined, function () {
  35878. scope.manager.itemError( url );
  35879. scope.manager.itemEnd( url );
  35880. } );
  35881. }
  35882. function deserializeImage( image ) {
  35883. if ( typeof image === 'string' ) {
  35884. const url = image;
  35885. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35886. return loadImage( path );
  35887. } else {
  35888. if ( image.data ) {
  35889. return {
  35890. data: getTypedArray( image.type, image.data ),
  35891. width: image.width,
  35892. height: image.height
  35893. };
  35894. } else {
  35895. return null;
  35896. }
  35897. }
  35898. }
  35899. if ( json !== undefined && json.length > 0 ) {
  35900. const manager = new LoadingManager( onLoad );
  35901. loader = new ImageLoader( manager );
  35902. loader.setCrossOrigin( this.crossOrigin );
  35903. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35904. const image = json[ i ];
  35905. const url = image.url;
  35906. if ( Array.isArray( url ) ) {
  35907. // load array of images e.g CubeTexture
  35908. const imageArray = [];
  35909. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35910. const currentUrl = url[ j ];
  35911. const deserializedImage = deserializeImage( currentUrl );
  35912. if ( deserializedImage !== null ) {
  35913. if ( deserializedImage instanceof HTMLImageElement ) {
  35914. imageArray.push( deserializedImage );
  35915. } else {
  35916. // special case: handle array of data textures for cube textures
  35917. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35918. }
  35919. }
  35920. }
  35921. images[ image.uuid ] = new Source( imageArray );
  35922. } else {
  35923. // load single image
  35924. const deserializedImage = deserializeImage( image.url );
  35925. images[ image.uuid ] = new Source( deserializedImage );
  35926. }
  35927. }
  35928. }
  35929. return images;
  35930. }
  35931. async parseImagesAsync( json ) {
  35932. const scope = this;
  35933. const images = {};
  35934. let loader;
  35935. async function deserializeImage( image ) {
  35936. if ( typeof image === 'string' ) {
  35937. const url = image;
  35938. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35939. return await loader.loadAsync( path );
  35940. } else {
  35941. if ( image.data ) {
  35942. return {
  35943. data: getTypedArray( image.type, image.data ),
  35944. width: image.width,
  35945. height: image.height
  35946. };
  35947. } else {
  35948. return null;
  35949. }
  35950. }
  35951. }
  35952. if ( json !== undefined && json.length > 0 ) {
  35953. loader = new ImageLoader( this.manager );
  35954. loader.setCrossOrigin( this.crossOrigin );
  35955. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35956. const image = json[ i ];
  35957. const url = image.url;
  35958. if ( Array.isArray( url ) ) {
  35959. // load array of images e.g CubeTexture
  35960. const imageArray = [];
  35961. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35962. const currentUrl = url[ j ];
  35963. const deserializedImage = await deserializeImage( currentUrl );
  35964. if ( deserializedImage !== null ) {
  35965. if ( deserializedImage instanceof HTMLImageElement ) {
  35966. imageArray.push( deserializedImage );
  35967. } else {
  35968. // special case: handle array of data textures for cube textures
  35969. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35970. }
  35971. }
  35972. }
  35973. images[ image.uuid ] = new Source( imageArray );
  35974. } else {
  35975. // load single image
  35976. const deserializedImage = await deserializeImage( image.url );
  35977. images[ image.uuid ] = new Source( deserializedImage );
  35978. }
  35979. }
  35980. }
  35981. return images;
  35982. }
  35983. parseTextures( json, images ) {
  35984. function parseConstant( value, type ) {
  35985. if ( typeof value === 'number' ) return value;
  35986. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35987. return type[ value ];
  35988. }
  35989. const textures = {};
  35990. if ( json !== undefined ) {
  35991. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35992. const data = json[ i ];
  35993. if ( data.image === undefined ) {
  35994. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35995. }
  35996. if ( images[ data.image ] === undefined ) {
  35997. warn( 'ObjectLoader: Undefined image', data.image );
  35998. }
  35999. const source = images[ data.image ];
  36000. const image = source.data;
  36001. let texture;
  36002. if ( Array.isArray( image ) ) {
  36003. texture = new CubeTexture();
  36004. if ( image.length === 6 ) texture.needsUpdate = true;
  36005. } else {
  36006. if ( image && image.data ) {
  36007. texture = new DataTexture();
  36008. } else {
  36009. texture = new Texture();
  36010. }
  36011. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  36012. }
  36013. texture.source = source;
  36014. texture.uuid = data.uuid;
  36015. if ( data.name !== undefined ) texture.name = data.name;
  36016. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  36017. if ( data.channel !== undefined ) texture.channel = data.channel;
  36018. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  36019. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  36020. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  36021. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  36022. if ( data.wrap !== undefined ) {
  36023. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  36024. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  36025. }
  36026. if ( data.format !== undefined ) texture.format = data.format;
  36027. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  36028. if ( data.type !== undefined ) texture.type = data.type;
  36029. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  36030. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  36031. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  36032. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  36033. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  36034. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  36035. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  36036. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  36037. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  36038. if ( data.normalized !== undefined ) texture.normalized = data.normalized;
  36039. if ( data.userData !== undefined ) texture.userData = data.userData;
  36040. textures[ data.uuid ] = texture;
  36041. }
  36042. }
  36043. return textures;
  36044. }
  36045. parseObject( data, geometries, materials, textures, animations ) {
  36046. let object;
  36047. function getGeometry( name ) {
  36048. if ( geometries[ name ] === undefined ) {
  36049. warn( 'ObjectLoader: Undefined geometry', name );
  36050. }
  36051. return geometries[ name ];
  36052. }
  36053. function getMaterial( name ) {
  36054. if ( name === undefined ) return undefined;
  36055. if ( Array.isArray( name ) ) {
  36056. const array = [];
  36057. for ( let i = 0, l = name.length; i < l; i ++ ) {
  36058. const uuid = name[ i ];
  36059. if ( materials[ uuid ] === undefined ) {
  36060. warn( 'ObjectLoader: Undefined material', uuid );
  36061. }
  36062. array.push( materials[ uuid ] );
  36063. }
  36064. return array;
  36065. }
  36066. if ( materials[ name ] === undefined ) {
  36067. warn( 'ObjectLoader: Undefined material', name );
  36068. }
  36069. return materials[ name ];
  36070. }
  36071. function getTexture( uuid ) {
  36072. if ( textures[ uuid ] === undefined ) {
  36073. warn( 'ObjectLoader: Undefined texture', uuid );
  36074. }
  36075. return textures[ uuid ];
  36076. }
  36077. let geometry, material;
  36078. switch ( data.type ) {
  36079. case 'Scene':
  36080. object = new Scene();
  36081. if ( data.background !== undefined ) {
  36082. if ( Number.isInteger( data.background ) ) {
  36083. object.background = new Color( data.background );
  36084. } else {
  36085. object.background = getTexture( data.background );
  36086. }
  36087. }
  36088. if ( data.environment !== undefined ) {
  36089. object.environment = getTexture( data.environment );
  36090. }
  36091. if ( data.fog !== undefined ) {
  36092. if ( data.fog.type === 'Fog' ) {
  36093. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  36094. } else if ( data.fog.type === 'FogExp2' ) {
  36095. object.fog = new FogExp2( data.fog.color, data.fog.density );
  36096. }
  36097. if ( data.fog.name !== '' ) {
  36098. object.fog.name = data.fog.name;
  36099. }
  36100. }
  36101. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  36102. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  36103. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  36104. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  36105. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  36106. break;
  36107. case 'PerspectiveCamera':
  36108. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  36109. if ( data.focus !== undefined ) object.focus = data.focus;
  36110. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  36111. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  36112. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  36113. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  36114. break;
  36115. case 'OrthographicCamera':
  36116. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  36117. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  36118. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  36119. break;
  36120. case 'AmbientLight':
  36121. object = new AmbientLight( data.color, data.intensity );
  36122. break;
  36123. case 'DirectionalLight':
  36124. object = new DirectionalLight( data.color, data.intensity );
  36125. object.target = data.target || '';
  36126. break;
  36127. case 'PointLight':
  36128. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  36129. break;
  36130. case 'RectAreaLight':
  36131. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  36132. break;
  36133. case 'SpotLight':
  36134. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  36135. object.target = data.target || '';
  36136. break;
  36137. case 'HemisphereLight':
  36138. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  36139. break;
  36140. case 'LightProbe':
  36141. const sh = new SphericalHarmonics3().fromArray( data.sh );
  36142. object = new LightProbe( sh, data.intensity );
  36143. break;
  36144. case 'SkinnedMesh':
  36145. geometry = getGeometry( data.geometry );
  36146. material = getMaterial( data.material );
  36147. object = new SkinnedMesh( geometry, material );
  36148. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  36149. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  36150. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  36151. break;
  36152. case 'Mesh':
  36153. geometry = getGeometry( data.geometry );
  36154. material = getMaterial( data.material );
  36155. object = new Mesh( geometry, material );
  36156. break;
  36157. case 'InstancedMesh':
  36158. geometry = getGeometry( data.geometry );
  36159. material = getMaterial( data.material );
  36160. const count = data.count;
  36161. const instanceMatrix = data.instanceMatrix;
  36162. const instanceColor = data.instanceColor;
  36163. object = new InstancedMesh( geometry, material, count );
  36164. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  36165. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  36166. break;
  36167. case 'BatchedMesh':
  36168. geometry = getGeometry( data.geometry );
  36169. material = getMaterial( data.material );
  36170. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  36171. object.geometry = geometry;
  36172. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  36173. object.sortObjects = data.sortObjects;
  36174. object._drawRanges = data.drawRanges;
  36175. object._reservedRanges = data.reservedRanges;
  36176. object._geometryInfo = data.geometryInfo.map( info => {
  36177. let box = null;
  36178. let sphere = null;
  36179. if ( info.boundingBox !== undefined ) {
  36180. box = new Box3().fromJSON( info.boundingBox );
  36181. }
  36182. if ( info.boundingSphere !== undefined ) {
  36183. sphere = new Sphere().fromJSON( info.boundingSphere );
  36184. }
  36185. return {
  36186. ...info,
  36187. boundingBox: box,
  36188. boundingSphere: sphere
  36189. };
  36190. } );
  36191. object._instanceInfo = data.instanceInfo;
  36192. object._availableInstanceIds = data._availableInstanceIds;
  36193. object._availableGeometryIds = data._availableGeometryIds;
  36194. object._nextIndexStart = data.nextIndexStart;
  36195. object._nextVertexStart = data.nextVertexStart;
  36196. object._geometryCount = data.geometryCount;
  36197. object._maxInstanceCount = data.maxInstanceCount;
  36198. object._maxVertexCount = data.maxVertexCount;
  36199. object._maxIndexCount = data.maxIndexCount;
  36200. object._geometryInitialized = data.geometryInitialized;
  36201. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  36202. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  36203. if ( data.colorsTexture !== undefined ) {
  36204. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  36205. }
  36206. if ( data.boundingSphere !== undefined ) {
  36207. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  36208. }
  36209. if ( data.boundingBox !== undefined ) {
  36210. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  36211. }
  36212. break;
  36213. case 'LOD':
  36214. object = new LOD();
  36215. break;
  36216. case 'Line':
  36217. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  36218. break;
  36219. case 'LineLoop':
  36220. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  36221. break;
  36222. case 'LineSegments':
  36223. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  36224. break;
  36225. case 'PointCloud':
  36226. case 'Points':
  36227. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  36228. break;
  36229. case 'Sprite':
  36230. object = new Sprite( getMaterial( data.material ) );
  36231. break;
  36232. case 'Group':
  36233. object = new Group();
  36234. break;
  36235. case 'Bone':
  36236. object = new Bone();
  36237. break;
  36238. default:
  36239. object = new Object3D();
  36240. }
  36241. object.uuid = data.uuid;
  36242. if ( data.name !== undefined ) object.name = data.name;
  36243. if ( data.matrix !== undefined ) {
  36244. object.matrix.fromArray( data.matrix );
  36245. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  36246. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  36247. } else {
  36248. if ( data.position !== undefined ) object.position.fromArray( data.position );
  36249. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  36250. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  36251. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  36252. }
  36253. if ( data.up !== undefined ) object.up.fromArray( data.up );
  36254. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  36255. if ( data.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, data.morphTargetDictionary );
  36256. if ( data.morphTargetInfluences !== undefined ) object.morphTargetInfluences = data.morphTargetInfluences.slice();
  36257. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  36258. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  36259. if ( data.shadow ) {
  36260. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  36261. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  36262. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  36263. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  36264. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  36265. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  36266. }
  36267. if ( data.visible !== undefined ) object.visible = data.visible;
  36268. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  36269. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  36270. if ( data.static !== undefined ) object.static = data.static;
  36271. if ( data.userData !== undefined ) object.userData = data.userData;
  36272. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  36273. if ( data.children !== undefined ) {
  36274. const children = data.children;
  36275. for ( let i = 0; i < children.length; i ++ ) {
  36276. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  36277. }
  36278. }
  36279. if ( data.animations !== undefined ) {
  36280. const objectAnimations = data.animations;
  36281. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  36282. const uuid = objectAnimations[ i ];
  36283. object.animations.push( animations[ uuid ] );
  36284. }
  36285. }
  36286. if ( data.type === 'LOD' ) {
  36287. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  36288. const levels = data.levels;
  36289. for ( let l = 0; l < levels.length; l ++ ) {
  36290. const level = levels[ l ];
  36291. const child = object.getObjectByProperty( 'uuid', level.object );
  36292. if ( child !== undefined ) {
  36293. object.addLevel( child, level.distance, level.hysteresis );
  36294. }
  36295. }
  36296. }
  36297. return object;
  36298. }
  36299. bindSkeletons( object, skeletons ) {
  36300. if ( Object.keys( skeletons ).length === 0 ) return;
  36301. object.traverse( function ( child ) {
  36302. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  36303. const skeleton = skeletons[ child.skeleton ];
  36304. if ( skeleton === undefined ) {
  36305. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  36306. } else {
  36307. child.bind( skeleton, child.bindMatrix );
  36308. }
  36309. }
  36310. } );
  36311. }
  36312. bindLightTargets( object ) {
  36313. object.traverse( function ( child ) {
  36314. if ( child.isDirectionalLight || child.isSpotLight ) {
  36315. const uuid = child.target;
  36316. const target = object.getObjectByProperty( 'uuid', uuid );
  36317. if ( target !== undefined ) {
  36318. child.target = target;
  36319. } else {
  36320. child.target = new Object3D();
  36321. }
  36322. }
  36323. } );
  36324. }
  36325. }
  36326. const TEXTURE_MAPPING = {
  36327. UVMapping: UVMapping,
  36328. CubeReflectionMapping: CubeReflectionMapping,
  36329. CubeRefractionMapping: CubeRefractionMapping,
  36330. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  36331. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  36332. CubeUVReflectionMapping: CubeUVReflectionMapping
  36333. };
  36334. const TEXTURE_WRAPPING = {
  36335. RepeatWrapping: RepeatWrapping,
  36336. ClampToEdgeWrapping: ClampToEdgeWrapping,
  36337. MirroredRepeatWrapping: MirroredRepeatWrapping
  36338. };
  36339. const TEXTURE_FILTER = {
  36340. NearestFilter: NearestFilter,
  36341. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  36342. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  36343. LinearFilter: LinearFilter,
  36344. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  36345. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  36346. };
  36347. const _errorMap = new WeakMap();
  36348. /**
  36349. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  36350. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  36351. * textures for rendering.
  36352. *
  36353. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  36354. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  36355. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  36356. *
  36357. * To match the default behaviour of {@link Texture}, the following options are needed:
  36358. *
  36359. * ```js
  36360. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  36361. * ```
  36362. *
  36363. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  36364. *
  36365. * ```js
  36366. * const loader = new THREE.ImageBitmapLoader();
  36367. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  36368. * const imageBitmap = await loader.loadAsync( 'image.png' );
  36369. *
  36370. * const texture = new THREE.Texture( imageBitmap );
  36371. * texture.needsUpdate = true;
  36372. * ```
  36373. *
  36374. * @augments Loader
  36375. */
  36376. class ImageBitmapLoader extends Loader {
  36377. /**
  36378. * Constructs a new image bitmap loader.
  36379. *
  36380. * @param {LoadingManager} [manager] - The loading manager.
  36381. */
  36382. constructor( manager ) {
  36383. super( manager );
  36384. /**
  36385. * This flag can be used for type testing.
  36386. *
  36387. * @type {boolean}
  36388. * @readonly
  36389. * @default true
  36390. */
  36391. this.isImageBitmapLoader = true;
  36392. if ( typeof createImageBitmap === 'undefined' ) {
  36393. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  36394. }
  36395. if ( typeof fetch === 'undefined' ) {
  36396. warn( 'ImageBitmapLoader: fetch() not supported.' );
  36397. }
  36398. /**
  36399. * Represents the loader options.
  36400. *
  36401. * @type {Object}
  36402. * @default {premultiplyAlpha:'none'}
  36403. */
  36404. this.options = { premultiplyAlpha: 'none' };
  36405. /**
  36406. * Used for aborting requests.
  36407. *
  36408. * @private
  36409. * @type {AbortController}
  36410. */
  36411. this._abortController = new AbortController();
  36412. }
  36413. /**
  36414. * Sets the given loader options. The structure of the object must match the `options` parameter of
  36415. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  36416. *
  36417. * Note: When caching is enabled, the cache key is based on the URL only. Loading the same URL with
  36418. * different options will return the cached result of the first request.
  36419. *
  36420. * @param {Object} options - The loader options to set.
  36421. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  36422. */
  36423. setOptions( options ) {
  36424. this.options = options;
  36425. return this;
  36426. }
  36427. /**
  36428. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  36429. *
  36430. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36431. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  36432. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  36433. * @param {onErrorCallback} onError - Executed when errors occur.
  36434. */
  36435. load( url, onLoad, onProgress, onError ) {
  36436. if ( url === undefined ) url = '';
  36437. if ( this.path !== undefined ) url = this.path + url;
  36438. url = this.manager.resolveURL( url );
  36439. const scope = this;
  36440. const cached = Cache.get( `image-bitmap:${url}` );
  36441. if ( cached !== undefined ) {
  36442. scope.manager.itemStart( url );
  36443. // If cached is a promise, wait for it to resolve
  36444. if ( cached.then ) {
  36445. cached.then( imageBitmap => {
  36446. // check if there is an error for the cached promise
  36447. if ( _errorMap.has( cached ) === true ) {
  36448. if ( onError ) onError( _errorMap.get( cached ) );
  36449. scope.manager.itemError( url );
  36450. scope.manager.itemEnd( url );
  36451. } else {
  36452. if ( onLoad ) onLoad( imageBitmap );
  36453. scope.manager.itemEnd( url );
  36454. }
  36455. } );
  36456. return;
  36457. }
  36458. // If cached is not a promise (i.e., it's already an imageBitmap)
  36459. setTimeout( function () {
  36460. if ( onLoad ) onLoad( cached );
  36461. scope.manager.itemEnd( url );
  36462. }, 0 );
  36463. return;
  36464. }
  36465. const fetchOptions = {};
  36466. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36467. fetchOptions.headers = this.requestHeader;
  36468. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36469. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36470. return res.blob();
  36471. } ).then( function ( blob ) {
  36472. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36473. } ).then( function ( imageBitmap ) {
  36474. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36475. if ( onLoad ) onLoad( imageBitmap );
  36476. scope.manager.itemEnd( url );
  36477. } ).catch( function ( e ) {
  36478. if ( onError ) onError( e );
  36479. _errorMap.set( promise, e );
  36480. Cache.remove( `image-bitmap:${url}` );
  36481. scope.manager.itemError( url );
  36482. scope.manager.itemEnd( url );
  36483. } );
  36484. Cache.add( `image-bitmap:${url}`, promise );
  36485. scope.manager.itemStart( url );
  36486. }
  36487. /**
  36488. * Aborts ongoing fetch requests.
  36489. *
  36490. * @return {ImageBitmapLoader} A reference to this instance.
  36491. */
  36492. abort() {
  36493. this._abortController.abort();
  36494. this._abortController = new AbortController();
  36495. return this;
  36496. }
  36497. }
  36498. let _context;
  36499. /**
  36500. * Manages the global audio context in the engine.
  36501. *
  36502. * @hideconstructor
  36503. */
  36504. class AudioContext {
  36505. /**
  36506. * Returns the global native audio context.
  36507. *
  36508. * @return {Window.AudioContext} The native audio context.
  36509. */
  36510. static getContext() {
  36511. if ( _context === undefined ) {
  36512. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36513. }
  36514. return _context;
  36515. }
  36516. /**
  36517. * Allows to set the global native audio context from outside.
  36518. *
  36519. * @param {Window.AudioContext} value - The native context to set.
  36520. */
  36521. static setContext( value ) {
  36522. _context = value;
  36523. }
  36524. }
  36525. /**
  36526. * Class for loading audio buffers. Audios are internally
  36527. * loaded via {@link FileLoader}.
  36528. *
  36529. * ```js
  36530. * const audioListener = new THREE.AudioListener();
  36531. * const ambientSound = new THREE.Audio( audioListener );
  36532. *
  36533. * const loader = new THREE.AudioLoader();
  36534. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36535. *
  36536. * ambientSound.setBuffer( audioBuffer );
  36537. * ambientSound.play();
  36538. * ```
  36539. *
  36540. * @augments Loader
  36541. */
  36542. class AudioLoader extends Loader {
  36543. /**
  36544. * Constructs a new audio loader.
  36545. *
  36546. * @param {LoadingManager} [manager] - The loading manager.
  36547. */
  36548. constructor( manager ) {
  36549. super( manager );
  36550. }
  36551. /**
  36552. * Starts loading from the given URL and passes the loaded audio buffer
  36553. * to the `onLoad()` callback.
  36554. *
  36555. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36556. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36557. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36558. * @param {onErrorCallback} onError - Executed when errors occur.
  36559. */
  36560. load( url, onLoad, onProgress, onError ) {
  36561. const scope = this;
  36562. const loader = new FileLoader( this.manager );
  36563. loader.setResponseType( 'arraybuffer' );
  36564. loader.setPath( this.path );
  36565. loader.setRequestHeader( this.requestHeader );
  36566. loader.setWithCredentials( this.withCredentials );
  36567. loader.load( url, function ( buffer ) {
  36568. try {
  36569. // Create a copy of the buffer. The `decodeAudioData` method
  36570. // detaches the buffer when complete, preventing reuse.
  36571. const bufferCopy = buffer.slice( 0 );
  36572. const context = AudioContext.getContext();
  36573. const decodeUrl = url + '#decode';
  36574. scope.manager.itemStart( decodeUrl ); // prevent loading manager from completing too early, see #33378
  36575. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36576. onLoad( audioBuffer );
  36577. scope.manager.itemEnd( decodeUrl );
  36578. } ).catch( function ( e ) {
  36579. handleError( e );
  36580. scope.manager.itemEnd( decodeUrl );
  36581. } );
  36582. } catch ( e ) {
  36583. handleError( e );
  36584. }
  36585. }, onProgress, onError );
  36586. function handleError( e ) {
  36587. if ( onError ) {
  36588. onError( e );
  36589. } else {
  36590. error( e );
  36591. }
  36592. scope.manager.itemError( url );
  36593. }
  36594. }
  36595. }
  36596. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36597. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36598. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36599. /**
  36600. * A special type of camera that uses two perspective cameras with
  36601. * stereoscopic projection. Can be used for rendering stereo effects
  36602. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36603. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36604. */
  36605. class StereoCamera {
  36606. /**
  36607. * Constructs a new stereo camera.
  36608. */
  36609. constructor() {
  36610. /**
  36611. * The type property is used for detecting the object type
  36612. * in context of serialization/deserialization.
  36613. *
  36614. * @type {string}
  36615. * @readonly
  36616. */
  36617. this.type = 'StereoCamera';
  36618. /**
  36619. * The aspect.
  36620. *
  36621. * @type {number}
  36622. * @default 1
  36623. */
  36624. this.aspect = 1;
  36625. /**
  36626. * The eye separation which represents the distance
  36627. * between the left and right camera.
  36628. *
  36629. * @type {number}
  36630. * @default 0.064
  36631. */
  36632. this.eyeSep = 0.064;
  36633. /**
  36634. * The camera representing the left eye. This is added to layer `1` so objects to be
  36635. * rendered by the left camera must also be added to this layer.
  36636. *
  36637. * @type {PerspectiveCamera}
  36638. */
  36639. this.cameraL = new PerspectiveCamera();
  36640. this.cameraL.layers.enable( 1 );
  36641. this.cameraL.matrixAutoUpdate = false;
  36642. /**
  36643. * The camera representing the right eye. This is added to layer `2` so objects to be
  36644. * rendered by the right camera must also be added to this layer.
  36645. *
  36646. * @type {PerspectiveCamera}
  36647. */
  36648. this.cameraR = new PerspectiveCamera();
  36649. this.cameraR.layers.enable( 2 );
  36650. this.cameraR.matrixAutoUpdate = false;
  36651. this._cache = {
  36652. focus: null,
  36653. fov: null,
  36654. aspect: null,
  36655. near: null,
  36656. far: null,
  36657. zoom: null,
  36658. eyeSep: null
  36659. };
  36660. }
  36661. /**
  36662. * Updates the stereo camera based on the given perspective camera.
  36663. *
  36664. * @param {PerspectiveCamera} camera - The perspective camera.
  36665. */
  36666. update( camera ) {
  36667. const cache = this._cache;
  36668. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36669. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36670. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36671. if ( needsUpdate ) {
  36672. cache.focus = camera.focus;
  36673. cache.fov = camera.fov;
  36674. cache.aspect = camera.aspect * this.aspect;
  36675. cache.near = camera.near;
  36676. cache.far = camera.far;
  36677. cache.zoom = camera.zoom;
  36678. cache.eyeSep = this.eyeSep;
  36679. // Off-axis stereoscopic effect based on
  36680. // http://paulbourke.net/stereographics/stereorender/
  36681. _projectionMatrix.copy( camera.projectionMatrix );
  36682. const eyeSepHalf = cache.eyeSep / 2;
  36683. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36684. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36685. let xmin, xmax;
  36686. // translate xOffset
  36687. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36688. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36689. // for left eye
  36690. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36691. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36692. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36693. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36694. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36695. // for right eye
  36696. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36697. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36698. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36699. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36700. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36701. }
  36702. this.cameraL.matrix.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36703. this.cameraL.matrixWorldNeedsUpdate = true;
  36704. this.cameraR.matrix.copy( camera.matrixWorld ).multiply( _eyeRight );
  36705. this.cameraR.matrixWorldNeedsUpdate = true;
  36706. }
  36707. }
  36708. const fov = -90; // negative fov is not an error
  36709. const aspect = 1;
  36710. /**
  36711. * A special type of camera that is positioned in 3D space to render its surroundings into a
  36712. * cube render target. The render target can then be used as an environment map for rendering
  36713. * realtime reflections in your scene.
  36714. *
  36715. * ```js
  36716. * // Create cube render target
  36717. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  36718. *
  36719. * // Create cube camera
  36720. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  36721. * scene.add( cubeCamera );
  36722. *
  36723. * // Create car
  36724. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  36725. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  36726. * scene.add( car );
  36727. *
  36728. * // Update the render target cube
  36729. * car.visible = false;
  36730. * cubeCamera.position.copy( car.position );
  36731. * cubeCamera.update( renderer, scene );
  36732. *
  36733. * // Render the scene
  36734. * car.visible = true;
  36735. * renderer.render( scene, camera );
  36736. * ```
  36737. *
  36738. * @augments Object3D
  36739. */
  36740. class CubeCamera extends Object3D {
  36741. /**
  36742. * Constructs a new cube camera.
  36743. *
  36744. * @param {number} near - The camera's near plane.
  36745. * @param {number} far - The camera's far plane.
  36746. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  36747. */
  36748. constructor( near, far, renderTarget ) {
  36749. super();
  36750. this.type = 'CubeCamera';
  36751. /**
  36752. * A reference to the cube render target.
  36753. *
  36754. * @type {WebGLCubeRenderTarget}
  36755. */
  36756. this.renderTarget = renderTarget;
  36757. /**
  36758. * The current active coordinate system.
  36759. *
  36760. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  36761. * @default null
  36762. */
  36763. this.coordinateSystem = null;
  36764. /**
  36765. * The current active mipmap level
  36766. *
  36767. * @type {number}
  36768. * @default 0
  36769. */
  36770. this.activeMipmapLevel = 0;
  36771. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  36772. cameraPX.layers = this.layers;
  36773. this.add( cameraPX );
  36774. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  36775. cameraNX.layers = this.layers;
  36776. this.add( cameraNX );
  36777. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  36778. cameraPY.layers = this.layers;
  36779. this.add( cameraPY );
  36780. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  36781. cameraNY.layers = this.layers;
  36782. this.add( cameraNY );
  36783. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  36784. cameraPZ.layers = this.layers;
  36785. this.add( cameraPZ );
  36786. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  36787. cameraNZ.layers = this.layers;
  36788. this.add( cameraNZ );
  36789. }
  36790. /**
  36791. * Must be called when the coordinate system of the cube camera is changed.
  36792. */
  36793. updateCoordinateSystem() {
  36794. const coordinateSystem = this.coordinateSystem;
  36795. const cameras = this.children.concat();
  36796. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  36797. for ( const camera of cameras ) this.remove( camera );
  36798. if ( coordinateSystem === WebGLCoordinateSystem ) {
  36799. cameraPX.up.set( 0, 1, 0 );
  36800. cameraPX.lookAt( 1, 0, 0 );
  36801. cameraNX.up.set( 0, 1, 0 );
  36802. cameraNX.lookAt( -1, 0, 0 );
  36803. cameraPY.up.set( 0, 0, -1 );
  36804. cameraPY.lookAt( 0, 1, 0 );
  36805. cameraNY.up.set( 0, 0, 1 );
  36806. cameraNY.lookAt( 0, -1, 0 );
  36807. cameraPZ.up.set( 0, 1, 0 );
  36808. cameraPZ.lookAt( 0, 0, 1 );
  36809. cameraNZ.up.set( 0, 1, 0 );
  36810. cameraNZ.lookAt( 0, 0, -1 );
  36811. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  36812. cameraPX.up.set( 0, -1, 0 );
  36813. cameraPX.lookAt( -1, 0, 0 );
  36814. cameraNX.up.set( 0, -1, 0 );
  36815. cameraNX.lookAt( 1, 0, 0 );
  36816. cameraPY.up.set( 0, 0, 1 );
  36817. cameraPY.lookAt( 0, 1, 0 );
  36818. cameraNY.up.set( 0, 0, -1 );
  36819. cameraNY.lookAt( 0, -1, 0 );
  36820. cameraPZ.up.set( 0, -1, 0 );
  36821. cameraPZ.lookAt( 0, 0, 1 );
  36822. cameraNZ.up.set( 0, -1, 0 );
  36823. cameraNZ.lookAt( 0, 0, -1 );
  36824. } else {
  36825. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  36826. }
  36827. for ( const camera of cameras ) {
  36828. this.add( camera );
  36829. camera.updateMatrixWorld();
  36830. }
  36831. }
  36832. /**
  36833. * Calling this method will render the given scene with the given renderer
  36834. * into the cube render target of the camera.
  36835. *
  36836. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  36837. * @param {Scene} scene - The scene to render.
  36838. */
  36839. update( renderer, scene ) {
  36840. if ( this.parent === null ) this.updateMatrixWorld();
  36841. const { renderTarget, activeMipmapLevel } = this;
  36842. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  36843. this.coordinateSystem = renderer.coordinateSystem;
  36844. this.updateCoordinateSystem();
  36845. }
  36846. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  36847. const currentRenderTarget = renderer.getRenderTarget();
  36848. const currentActiveCubeFace = renderer.getActiveCubeFace();
  36849. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  36850. const currentXrEnabled = renderer.xr.enabled;
  36851. renderer.xr.enabled = false;
  36852. const generateMipmaps = renderTarget.texture.generateMipmaps;
  36853. renderTarget.texture.generateMipmaps = false;
  36854. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  36855. let reversedDepthBuffer = false;
  36856. if ( renderer.isWebGLRenderer === true ) {
  36857. reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  36858. } else {
  36859. reversedDepthBuffer = renderer.reversedDepthBuffer;
  36860. }
  36861. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  36862. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36863. renderer.render( scene, cameraPX );
  36864. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  36865. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36866. renderer.render( scene, cameraNX );
  36867. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  36868. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36869. renderer.render( scene, cameraPY );
  36870. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  36871. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36872. renderer.render( scene, cameraNY );
  36873. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  36874. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36875. renderer.render( scene, cameraPZ );
  36876. // mipmaps are generated during the last call of render()
  36877. // at this point, all sides of the cube render target are defined
  36878. renderTarget.texture.generateMipmaps = generateMipmaps;
  36879. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  36880. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36881. renderer.render( scene, cameraNZ );
  36882. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  36883. renderer.xr.enabled = currentXrEnabled;
  36884. renderTarget.texture.needsPMREMUpdate = true;
  36885. }
  36886. }
  36887. /**
  36888. * This type of camera can be used in order to efficiently render a scene with a
  36889. * predefined set of cameras. This is an important performance aspect for
  36890. * rendering VR scenes.
  36891. *
  36892. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36893. * to define for each sub camera the `viewport` property which determines the
  36894. * part of the viewport that is rendered with this camera.
  36895. *
  36896. * @augments PerspectiveCamera
  36897. */
  36898. class ArrayCamera extends PerspectiveCamera {
  36899. /**
  36900. * Constructs a new array camera.
  36901. *
  36902. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36903. */
  36904. constructor( array = [] ) {
  36905. super();
  36906. /**
  36907. * This flag can be used for type testing.
  36908. *
  36909. * @type {boolean}
  36910. * @readonly
  36911. * @default true
  36912. */
  36913. this.isArrayCamera = true;
  36914. /**
  36915. * Whether this camera is used with multiview rendering or not.
  36916. *
  36917. * @type {boolean}
  36918. * @readonly
  36919. * @default false
  36920. */
  36921. this.isMultiViewCamera = false;
  36922. /**
  36923. * An array of perspective sub cameras.
  36924. *
  36925. * @type {Array<PerspectiveCamera>}
  36926. */
  36927. this.cameras = array;
  36928. }
  36929. }
  36930. /**
  36931. * This class is an alternative to {@link Clock} with a different API design and behavior.
  36932. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  36933. *
  36934. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  36935. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  36936. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  36937. * is inactive (e.g. tab switched or browser hidden).
  36938. *
  36939. * ```js
  36940. * const timer = new Timer();
  36941. * timer.connect( document ); // use Page Visibility API
  36942. * ```
  36943. */
  36944. class Timer {
  36945. /**
  36946. * Constructs a new timer.
  36947. */
  36948. constructor() {
  36949. this._previousTime = 0;
  36950. this._currentTime = 0;
  36951. this._startTime = performance.now();
  36952. this._delta = 0;
  36953. this._elapsed = 0;
  36954. this._timescale = 1;
  36955. this._document = null;
  36956. this._pageVisibilityHandler = null;
  36957. }
  36958. /**
  36959. * Connect the timer to the given document.Calling this method is not mandatory to
  36960. * use the timer but enables the usage of the Page Visibility API to avoid large time
  36961. * delta values.
  36962. *
  36963. * @param {Document} document - The document.
  36964. */
  36965. connect( document ) {
  36966. this._document = document;
  36967. // use Page Visibility API to avoid large time delta values
  36968. if ( document.hidden !== undefined ) {
  36969. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  36970. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  36971. }
  36972. }
  36973. /**
  36974. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  36975. */
  36976. disconnect() {
  36977. if ( this._pageVisibilityHandler !== null ) {
  36978. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  36979. this._pageVisibilityHandler = null;
  36980. }
  36981. this._document = null;
  36982. }
  36983. /**
  36984. * Returns the time delta in seconds.
  36985. *
  36986. * @return {number} The time delta in second.
  36987. */
  36988. getDelta() {
  36989. return this._delta / 1000;
  36990. }
  36991. /**
  36992. * Returns the elapsed time in seconds.
  36993. *
  36994. * @return {number} The elapsed time in second.
  36995. */
  36996. getElapsed() {
  36997. return this._elapsed / 1000;
  36998. }
  36999. /**
  37000. * Returns the timescale.
  37001. *
  37002. * @return {number} The timescale.
  37003. */
  37004. getTimescale() {
  37005. return this._timescale;
  37006. }
  37007. /**
  37008. * Sets the given timescale which scale the time delta computation
  37009. * in `update()`.
  37010. *
  37011. * @param {number} timescale - The timescale to set.
  37012. * @return {Timer} A reference to this timer.
  37013. */
  37014. setTimescale( timescale ) {
  37015. this._timescale = timescale;
  37016. return this;
  37017. }
  37018. /**
  37019. * Resets the time computation for the current simulation step.
  37020. *
  37021. * @return {Timer} A reference to this timer.
  37022. */
  37023. reset() {
  37024. this._currentTime = performance.now() - this._startTime;
  37025. return this;
  37026. }
  37027. /**
  37028. * Can be used to free all internal resources. Usually called when
  37029. * the timer instance isn't required anymore.
  37030. */
  37031. dispose() {
  37032. this.disconnect();
  37033. }
  37034. /**
  37035. * Updates the internal state of the timer. This method should be called
  37036. * once per simulation step and before you perform queries against the timer
  37037. * (e.g. via `getDelta()`).
  37038. *
  37039. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  37040. * from the `requestAnimationFrame` callback argument. If not provided, the current
  37041. * time will be determined with `performance.now`.
  37042. * @return {Timer} A reference to this timer.
  37043. */
  37044. update( timestamp ) {
  37045. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  37046. this._delta = 0;
  37047. } else {
  37048. this._previousTime = this._currentTime;
  37049. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  37050. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  37051. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  37052. }
  37053. return this;
  37054. }
  37055. }
  37056. function handleVisibilityChange() {
  37057. if ( this._document.hidden === false ) this.reset();
  37058. }
  37059. const _position$1 = /*@__PURE__*/ new Vector3();
  37060. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  37061. const _scale$1 = /*@__PURE__*/ new Vector3();
  37062. const _forward = /*@__PURE__*/ new Vector3();
  37063. const _up = /*@__PURE__*/ new Vector3();
  37064. /**
  37065. * The class represents a virtual listener of the all positional and non-positional audio effects
  37066. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  37067. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  37068. *
  37069. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  37070. * camera represents the 3D transformation of the listener.
  37071. *
  37072. * @augments Object3D
  37073. */
  37074. class AudioListener extends Object3D {
  37075. /**
  37076. * Constructs a new audio listener.
  37077. */
  37078. constructor() {
  37079. super();
  37080. this.type = 'AudioListener';
  37081. /**
  37082. * The native audio context.
  37083. *
  37084. * @type {AudioContext}
  37085. * @readonly
  37086. */
  37087. this.context = AudioContext.getContext();
  37088. /**
  37089. * The gain node used for volume control.
  37090. *
  37091. * @type {GainNode}
  37092. * @readonly
  37093. */
  37094. this.gain = this.context.createGain();
  37095. this.gain.connect( this.context.destination );
  37096. /**
  37097. * An optional filter.
  37098. *
  37099. * Defined via {@link AudioListener#setFilter}.
  37100. *
  37101. * @type {?AudioNode}
  37102. * @default null
  37103. * @readonly
  37104. */
  37105. this.filter = null;
  37106. /**
  37107. * Time delta values required for `linearRampToValueAtTime()` usage.
  37108. *
  37109. * @type {number}
  37110. * @default 0
  37111. * @readonly
  37112. */
  37113. this.timeDelta = 0;
  37114. // private
  37115. this._timer = new Timer();
  37116. }
  37117. /**
  37118. * Returns the listener's input node.
  37119. *
  37120. * This method is used by other audio nodes to connect to this listener.
  37121. *
  37122. * @return {GainNode} The input node.
  37123. */
  37124. getInput() {
  37125. return this.gain;
  37126. }
  37127. /**
  37128. * Removes the current filter from this listener.
  37129. *
  37130. * @return {AudioListener} A reference to this listener.
  37131. */
  37132. removeFilter() {
  37133. if ( this.filter !== null ) {
  37134. this.gain.disconnect( this.filter );
  37135. this.filter.disconnect( this.context.destination );
  37136. this.gain.connect( this.context.destination );
  37137. this.filter = null;
  37138. }
  37139. return this;
  37140. }
  37141. /**
  37142. * Returns the current set filter.
  37143. *
  37144. * @return {?AudioNode} The filter.
  37145. */
  37146. getFilter() {
  37147. return this.filter;
  37148. }
  37149. /**
  37150. * Sets the given filter to this listener.
  37151. *
  37152. * @param {AudioNode} value - The filter to set.
  37153. * @return {AudioListener} A reference to this listener.
  37154. */
  37155. setFilter( value ) {
  37156. if ( this.filter !== null ) {
  37157. this.gain.disconnect( this.filter );
  37158. this.filter.disconnect( this.context.destination );
  37159. } else {
  37160. this.gain.disconnect( this.context.destination );
  37161. }
  37162. this.filter = value;
  37163. this.gain.connect( this.filter );
  37164. this.filter.connect( this.context.destination );
  37165. return this;
  37166. }
  37167. /**
  37168. * Returns the applications master volume.
  37169. *
  37170. * @return {number} The master volume.
  37171. */
  37172. getMasterVolume() {
  37173. return this.gain.gain.value;
  37174. }
  37175. /**
  37176. * Sets the applications master volume. This volume setting affects
  37177. * all audio nodes in the scene.
  37178. *
  37179. * @param {number} value - The master volume to set.
  37180. * @return {AudioListener} A reference to this listener.
  37181. */
  37182. setMasterVolume( value ) {
  37183. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37184. return this;
  37185. }
  37186. updateMatrixWorld( force ) {
  37187. super.updateMatrixWorld( force );
  37188. this._timer.update();
  37189. const listener = this.context.listener;
  37190. this.timeDelta = this._timer.getDelta();
  37191. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  37192. // the initial forward and up directions must be orthogonal
  37193. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  37194. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  37195. if ( listener.positionX ) {
  37196. // code path for Chrome (see #14393)
  37197. const endTime = this.context.currentTime + this.timeDelta;
  37198. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  37199. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  37200. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  37201. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  37202. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  37203. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  37204. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  37205. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  37206. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  37207. } else {
  37208. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  37209. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  37210. }
  37211. }
  37212. }
  37213. /**
  37214. * Represents a non-positional ( global ) audio object.
  37215. *
  37216. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  37217. *
  37218. * ```js
  37219. * // create an AudioListener and add it to the camera
  37220. * const listener = new THREE.AudioListener();
  37221. * camera.add( listener );
  37222. *
  37223. * // create a global audio source
  37224. * const sound = new THREE.Audio( listener );
  37225. *
  37226. * // load a sound and set it as the Audio object's buffer
  37227. * const audioLoader = new THREE.AudioLoader();
  37228. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37229. * sound.setBuffer( buffer );
  37230. * sound.setLoop( true );
  37231. * sound.setVolume( 0.5 );
  37232. * sound.play();
  37233. * });
  37234. * ```
  37235. *
  37236. * @augments Object3D
  37237. */
  37238. class Audio extends Object3D {
  37239. /**
  37240. * Constructs a new audio.
  37241. *
  37242. * @param {AudioListener} listener - The global audio listener.
  37243. */
  37244. constructor( listener ) {
  37245. super();
  37246. this.type = 'Audio';
  37247. /**
  37248. * The global audio listener.
  37249. *
  37250. * @type {AudioListener}
  37251. * @readonly
  37252. */
  37253. this.listener = listener;
  37254. /**
  37255. * The audio context.
  37256. *
  37257. * @type {AudioContext}
  37258. * @readonly
  37259. */
  37260. this.context = listener.context;
  37261. /**
  37262. * The gain node used for volume control.
  37263. *
  37264. * @type {GainNode}
  37265. * @readonly
  37266. */
  37267. this.gain = this.context.createGain();
  37268. this.gain.connect( listener.getInput() );
  37269. /**
  37270. * Whether to start playback automatically or not.
  37271. *
  37272. * @type {boolean}
  37273. * @default false
  37274. */
  37275. this.autoplay = false;
  37276. /**
  37277. * A reference to an audio buffer.
  37278. *
  37279. * Defined via {@link Audio#setBuffer}.
  37280. *
  37281. * @type {?AudioBuffer}
  37282. * @default null
  37283. * @readonly
  37284. */
  37285. this.buffer = null;
  37286. /**
  37287. * Modify pitch, measured in cents. +/- 100 is a semitone.
  37288. * +/- 1200 is an octave.
  37289. *
  37290. * Defined via {@link Audio#setDetune}.
  37291. *
  37292. * @type {number}
  37293. * @default 0
  37294. * @readonly
  37295. */
  37296. this.detune = 0;
  37297. /**
  37298. * Whether the audio should loop or not.
  37299. *
  37300. * Defined via {@link Audio#setLoop}.
  37301. *
  37302. * @type {boolean}
  37303. * @default false
  37304. * @readonly
  37305. */
  37306. this.loop = false;
  37307. /**
  37308. * Defines where in the audio buffer the replay should
  37309. * start, in seconds.
  37310. *
  37311. * @type {number}
  37312. * @default 0
  37313. */
  37314. this.loopStart = 0;
  37315. /**
  37316. * Defines where in the audio buffer the replay should
  37317. * stop, in seconds.
  37318. *
  37319. * @type {number}
  37320. * @default 0
  37321. */
  37322. this.loopEnd = 0;
  37323. /**
  37324. * An offset to the time within the audio buffer the playback
  37325. * should begin, in seconds.
  37326. *
  37327. * @type {number}
  37328. * @default 0
  37329. */
  37330. this.offset = 0;
  37331. /**
  37332. * Overrides the default duration of the audio.
  37333. *
  37334. * @type {undefined|number}
  37335. * @default undefined
  37336. */
  37337. this.duration = undefined;
  37338. /**
  37339. * The playback speed.
  37340. *
  37341. * Defined via {@link Audio#setPlaybackRate}.
  37342. *
  37343. * @type {number}
  37344. * @readonly
  37345. * @default 1
  37346. */
  37347. this.playbackRate = 1;
  37348. /**
  37349. * Indicates whether the audio is playing or not.
  37350. *
  37351. * This flag will be automatically set when using {@link Audio#play},
  37352. * {@link Audio#pause}, {@link Audio#stop}.
  37353. *
  37354. * @type {boolean}
  37355. * @readonly
  37356. * @default false
  37357. */
  37358. this.isPlaying = false;
  37359. /**
  37360. * Indicates whether the audio playback can be controlled
  37361. * with method like {@link Audio#play} or {@link Audio#pause}.
  37362. *
  37363. * This flag will be automatically set when audio sources are
  37364. * defined.
  37365. *
  37366. * @type {boolean}
  37367. * @readonly
  37368. * @default true
  37369. */
  37370. this.hasPlaybackControl = true;
  37371. /**
  37372. * Holds a reference to the current audio source.
  37373. *
  37374. * The property is automatically by one of the `set*()` methods.
  37375. *
  37376. * @type {?AudioNode}
  37377. * @readonly
  37378. * @default null
  37379. */
  37380. this.source = null;
  37381. /**
  37382. * Defines the source type.
  37383. *
  37384. * The property is automatically set by one of the `set*()` methods.
  37385. *
  37386. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  37387. * @readonly
  37388. * @default 'empty'
  37389. */
  37390. this.sourceType = 'empty';
  37391. this._startedAt = 0;
  37392. this._progress = 0;
  37393. this._connected = false;
  37394. /**
  37395. * Can be used to apply a variety of low-order filters to create
  37396. * more complex sound effects e.g. via `BiquadFilterNode`.
  37397. *
  37398. * The property is automatically set by {@link Audio#setFilters}.
  37399. *
  37400. * @type {Array<AudioNode>}
  37401. * @readonly
  37402. */
  37403. this.filters = [];
  37404. }
  37405. /**
  37406. * Returns the output audio node.
  37407. *
  37408. * @return {GainNode} The output node.
  37409. */
  37410. getOutput() {
  37411. return this.gain;
  37412. }
  37413. /**
  37414. * Sets the given audio node as the source of this instance.
  37415. *
  37416. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  37417. *
  37418. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  37419. * @return {Audio} A reference to this instance.
  37420. */
  37421. setNodeSource( audioNode ) {
  37422. this.hasPlaybackControl = false;
  37423. this.sourceType = 'audioNode';
  37424. this.source = audioNode;
  37425. this.connect();
  37426. return this;
  37427. }
  37428. /**
  37429. * Sets the given media element as the source of this instance.
  37430. *
  37431. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  37432. *
  37433. * @param {HTMLMediaElement} mediaElement - The media element.
  37434. * @return {Audio} A reference to this instance.
  37435. */
  37436. setMediaElementSource( mediaElement ) {
  37437. this.hasPlaybackControl = false;
  37438. this.sourceType = 'mediaNode';
  37439. this.source = this.context.createMediaElementSource( mediaElement );
  37440. this.connect();
  37441. return this;
  37442. }
  37443. /**
  37444. * Sets the given media stream as the source of this instance.
  37445. *
  37446. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  37447. *
  37448. * @param {MediaStream} mediaStream - The media stream.
  37449. * @return {Audio} A reference to this instance.
  37450. */
  37451. setMediaStreamSource( mediaStream ) {
  37452. this.hasPlaybackControl = false;
  37453. this.sourceType = 'mediaStreamNode';
  37454. this.source = this.context.createMediaStreamSource( mediaStream );
  37455. this.connect();
  37456. return this;
  37457. }
  37458. /**
  37459. * Sets the given audio buffer as the source of this instance.
  37460. *
  37461. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  37462. *
  37463. * @param {AudioBuffer} audioBuffer - The audio buffer.
  37464. * @return {Audio} A reference to this instance.
  37465. */
  37466. setBuffer( audioBuffer ) {
  37467. this.buffer = audioBuffer;
  37468. this.sourceType = 'buffer';
  37469. if ( this.autoplay ) this.play();
  37470. return this;
  37471. }
  37472. /**
  37473. * Starts the playback of the audio.
  37474. *
  37475. * Can only be used with compatible audio sources that allow playback control.
  37476. *
  37477. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  37478. * @return {Audio|undefined} A reference to this instance.
  37479. */
  37480. play( delay = 0 ) {
  37481. if ( this.isPlaying === true ) {
  37482. warn( 'Audio: Audio is already playing.' );
  37483. return;
  37484. }
  37485. if ( this.hasPlaybackControl === false ) {
  37486. warn( 'Audio: this Audio has no playback control.' );
  37487. return;
  37488. }
  37489. this._startedAt = this.context.currentTime + delay;
  37490. const source = this.context.createBufferSource();
  37491. source.buffer = this.buffer;
  37492. source.loop = this.loop;
  37493. source.loopStart = this.loopStart;
  37494. source.loopEnd = this.loopEnd;
  37495. source.onended = this.onEnded.bind( this );
  37496. source.start( this._startedAt, this._progress + this.offset, this.duration );
  37497. this.isPlaying = true;
  37498. this.source = source;
  37499. this.setDetune( this.detune );
  37500. this.setPlaybackRate( this.playbackRate );
  37501. return this.connect();
  37502. }
  37503. /**
  37504. * Pauses the playback of the audio.
  37505. *
  37506. * Can only be used with compatible audio sources that allow playback control.
  37507. *
  37508. * @return {Audio|undefined} A reference to this instance.
  37509. */
  37510. pause() {
  37511. if ( this.hasPlaybackControl === false ) {
  37512. warn( 'Audio: this Audio has no playback control.' );
  37513. return;
  37514. }
  37515. if ( this.isPlaying === true ) {
  37516. // update current progress
  37517. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  37518. if ( this.loop === true ) {
  37519. // ensure _progress does not exceed duration with looped audios
  37520. this._progress = this._progress % ( this.duration || this.buffer.duration );
  37521. }
  37522. this.source.stop();
  37523. this.source.onended = null;
  37524. this.isPlaying = false;
  37525. }
  37526. return this;
  37527. }
  37528. /**
  37529. * Stops the playback of the audio.
  37530. *
  37531. * Can only be used with compatible audio sources that allow playback control.
  37532. *
  37533. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  37534. * @return {Audio|undefined} A reference to this instance.
  37535. */
  37536. stop( delay = 0 ) {
  37537. if ( this.hasPlaybackControl === false ) {
  37538. warn( 'Audio: this Audio has no playback control.' );
  37539. return;
  37540. }
  37541. this._progress = 0;
  37542. if ( this.source !== null ) {
  37543. this.source.stop( this.context.currentTime + delay );
  37544. this.source.onended = null;
  37545. }
  37546. this.isPlaying = false;
  37547. return this;
  37548. }
  37549. /**
  37550. * Connects to the audio source. This is used internally on
  37551. * initialisation and when setting / removing filters.
  37552. *
  37553. * @return {Audio} A reference to this instance.
  37554. */
  37555. connect() {
  37556. if ( this.filters.length > 0 ) {
  37557. this.source.connect( this.filters[ 0 ] );
  37558. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37559. this.filters[ i - 1 ].connect( this.filters[ i ] );
  37560. }
  37561. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  37562. } else {
  37563. this.source.connect( this.getOutput() );
  37564. }
  37565. this._connected = true;
  37566. return this;
  37567. }
  37568. /**
  37569. * Disconnects to the audio source. This is used internally on
  37570. * initialisation and when setting / removing filters.
  37571. *
  37572. * @return {Audio|undefined} A reference to this instance.
  37573. */
  37574. disconnect() {
  37575. if ( this._connected === false ) {
  37576. return;
  37577. }
  37578. if ( this.filters.length > 0 ) {
  37579. this.source.disconnect( this.filters[ 0 ] );
  37580. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37581. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  37582. }
  37583. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  37584. } else {
  37585. this.source.disconnect( this.getOutput() );
  37586. }
  37587. this._connected = false;
  37588. return this;
  37589. }
  37590. /**
  37591. * Returns the current set filters.
  37592. *
  37593. * @return {Array<AudioNode>} The list of filters.
  37594. */
  37595. getFilters() {
  37596. return this.filters;
  37597. }
  37598. /**
  37599. * Sets an array of filters and connects them with the audio source.
  37600. *
  37601. * @param {Array<AudioNode>} [value] - A list of filters.
  37602. * @return {Audio} A reference to this instance.
  37603. */
  37604. setFilters( value ) {
  37605. if ( ! value ) value = [];
  37606. if ( this._connected === true ) {
  37607. this.disconnect();
  37608. this.filters = value.slice();
  37609. this.connect();
  37610. } else {
  37611. this.filters = value.slice();
  37612. }
  37613. return this;
  37614. }
  37615. /**
  37616. * Defines the detuning of oscillation in cents.
  37617. *
  37618. * @param {number} value - The detuning of oscillation in cents.
  37619. * @return {Audio} A reference to this instance.
  37620. */
  37621. setDetune( value ) {
  37622. this.detune = value;
  37623. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37624. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37625. }
  37626. return this;
  37627. }
  37628. /**
  37629. * Returns the detuning of oscillation in cents.
  37630. *
  37631. * @return {number} The detuning of oscillation in cents.
  37632. */
  37633. getDetune() {
  37634. return this.detune;
  37635. }
  37636. /**
  37637. * Returns the first filter in the list of filters.
  37638. *
  37639. * @return {AudioNode|undefined} The first filter in the list of filters.
  37640. */
  37641. getFilter() {
  37642. return this.getFilters()[ 0 ];
  37643. }
  37644. /**
  37645. * Applies a single filter node to the audio.
  37646. *
  37647. * @param {AudioNode} [filter] - The filter to set.
  37648. * @return {Audio} A reference to this instance.
  37649. */
  37650. setFilter( filter ) {
  37651. return this.setFilters( filter ? [ filter ] : [] );
  37652. }
  37653. /**
  37654. * Sets the playback rate.
  37655. *
  37656. * Can only be used with compatible audio sources that allow playback control.
  37657. *
  37658. * @param {number} [value] - The playback rate to set.
  37659. * @return {Audio|undefined} A reference to this instance.
  37660. */
  37661. setPlaybackRate( value ) {
  37662. if ( this.hasPlaybackControl === false ) {
  37663. warn( 'Audio: this Audio has no playback control.' );
  37664. return;
  37665. }
  37666. this.playbackRate = value;
  37667. if ( this.isPlaying === true ) {
  37668. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37669. }
  37670. return this;
  37671. }
  37672. /**
  37673. * Returns the current playback rate.
  37674. * @return {number} The playback rate.
  37675. */
  37676. getPlaybackRate() {
  37677. return this.playbackRate;
  37678. }
  37679. /**
  37680. * Automatically called when playback finished.
  37681. */
  37682. onEnded() {
  37683. this.isPlaying = false;
  37684. this._progress = 0;
  37685. }
  37686. /**
  37687. * Returns the loop flag.
  37688. *
  37689. * Can only be used with compatible audio sources that allow playback control.
  37690. *
  37691. * @return {boolean} Whether the audio should loop or not.
  37692. */
  37693. getLoop() {
  37694. if ( this.hasPlaybackControl === false ) {
  37695. warn( 'Audio: this Audio has no playback control.' );
  37696. return false;
  37697. }
  37698. return this.loop;
  37699. }
  37700. /**
  37701. * Sets the loop flag.
  37702. *
  37703. * Can only be used with compatible audio sources that allow playback control.
  37704. *
  37705. * @param {boolean} value - Whether the audio should loop or not.
  37706. * @return {Audio|undefined} A reference to this instance.
  37707. */
  37708. setLoop( value ) {
  37709. if ( this.hasPlaybackControl === false ) {
  37710. warn( 'Audio: this Audio has no playback control.' );
  37711. return;
  37712. }
  37713. this.loop = value;
  37714. if ( this.isPlaying === true ) {
  37715. this.source.loop = this.loop;
  37716. }
  37717. return this;
  37718. }
  37719. /**
  37720. * Sets the loop start value which defines where in the audio buffer the replay should
  37721. * start, in seconds.
  37722. *
  37723. * @param {number} value - The loop start value.
  37724. * @return {Audio} A reference to this instance.
  37725. */
  37726. setLoopStart( value ) {
  37727. this.loopStart = value;
  37728. return this;
  37729. }
  37730. /**
  37731. * Sets the loop end value which defines where in the audio buffer the replay should
  37732. * stop, in seconds.
  37733. *
  37734. * @param {number} value - The loop end value.
  37735. * @return {Audio} A reference to this instance.
  37736. */
  37737. setLoopEnd( value ) {
  37738. this.loopEnd = value;
  37739. return this;
  37740. }
  37741. /**
  37742. * Returns the volume.
  37743. *
  37744. * @return {number} The volume.
  37745. */
  37746. getVolume() {
  37747. return this.gain.gain.value;
  37748. }
  37749. /**
  37750. * Sets the volume.
  37751. *
  37752. * @param {number} value - The volume to set.
  37753. * @return {Audio} A reference to this instance.
  37754. */
  37755. setVolume( value ) {
  37756. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37757. return this;
  37758. }
  37759. copy( source, recursive ) {
  37760. super.copy( source, recursive );
  37761. if ( source.sourceType !== 'buffer' ) {
  37762. warn( 'Audio: Audio source type cannot be copied.' );
  37763. return this;
  37764. }
  37765. this.autoplay = source.autoplay;
  37766. this.buffer = source.buffer;
  37767. this.detune = source.detune;
  37768. this.loop = source.loop;
  37769. this.loopStart = source.loopStart;
  37770. this.loopEnd = source.loopEnd;
  37771. this.offset = source.offset;
  37772. this.duration = source.duration;
  37773. this.playbackRate = source.playbackRate;
  37774. this.hasPlaybackControl = source.hasPlaybackControl;
  37775. this.sourceType = source.sourceType;
  37776. this.filters = source.filters.slice();
  37777. return this;
  37778. }
  37779. clone( recursive ) {
  37780. return new this.constructor( this.listener ).copy( this, recursive );
  37781. }
  37782. }
  37783. const _position = /*@__PURE__*/ new Vector3();
  37784. const _quaternion = /*@__PURE__*/ new Quaternion();
  37785. const _scale = /*@__PURE__*/ new Vector3();
  37786. const _orientation = /*@__PURE__*/ new Vector3();
  37787. /**
  37788. * Represents a positional audio object.
  37789. *
  37790. * ```js
  37791. * // create an AudioListener and add it to the camera
  37792. * const listener = new THREE.AudioListener();
  37793. * camera.add( listener );
  37794. *
  37795. * // create the PositionalAudio object (passing in the listener)
  37796. * const sound = new THREE.PositionalAudio( listener );
  37797. *
  37798. * // load a sound and set it as the PositionalAudio object's buffer
  37799. * const audioLoader = new THREE.AudioLoader();
  37800. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37801. * sound.setBuffer( buffer );
  37802. * sound.setRefDistance( 20 );
  37803. * sound.play();
  37804. * });
  37805. *
  37806. * // create an object for the sound to play from
  37807. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37808. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37809. * const mesh = new THREE.Mesh( sphere, material );
  37810. * scene.add( mesh );
  37811. *
  37812. * // finally add the sound to the mesh
  37813. * mesh.add( sound );
  37814. *
  37815. * @augments Audio
  37816. */
  37817. class PositionalAudio extends Audio {
  37818. /**
  37819. * Constructs a positional audio.
  37820. *
  37821. * @param {AudioListener} listener - The global audio listener.
  37822. */
  37823. constructor( listener ) {
  37824. super( listener );
  37825. /**
  37826. * The panner node represents the location, direction, and behavior of an audio
  37827. * source in 3D space.
  37828. *
  37829. * @type {PannerNode}
  37830. * @readonly
  37831. */
  37832. this.panner = this.context.createPanner();
  37833. this.panner.panningModel = 'HRTF';
  37834. this.panner.connect( this.gain );
  37835. }
  37836. connect() {
  37837. super.connect();
  37838. this.panner.connect( this.gain );
  37839. return this;
  37840. }
  37841. disconnect() {
  37842. super.disconnect();
  37843. this.panner.disconnect( this.gain );
  37844. return this;
  37845. }
  37846. getOutput() {
  37847. return this.panner;
  37848. }
  37849. /**
  37850. * Returns the current reference distance.
  37851. *
  37852. * @return {number} The reference distance.
  37853. */
  37854. getRefDistance() {
  37855. return this.panner.refDistance;
  37856. }
  37857. /**
  37858. * Defines the reference distance for reducing volume as the audio source moves
  37859. * further from the listener – i.e. the distance at which the volume reduction
  37860. * starts taking effect.
  37861. *
  37862. * @param {number} value - The reference distance to set.
  37863. * @return {PositionalAudio} A reference to this instance.
  37864. */
  37865. setRefDistance( value ) {
  37866. this.panner.refDistance = value;
  37867. return this;
  37868. }
  37869. /**
  37870. * Returns the current rolloff factor.
  37871. *
  37872. * @return {number} The rolloff factor.
  37873. */
  37874. getRolloffFactor() {
  37875. return this.panner.rolloffFactor;
  37876. }
  37877. /**
  37878. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37879. *
  37880. * @param {number} value - The rolloff factor.
  37881. * @return {PositionalAudio} A reference to this instance.
  37882. */
  37883. setRolloffFactor( value ) {
  37884. this.panner.rolloffFactor = value;
  37885. return this;
  37886. }
  37887. /**
  37888. * Returns the current distance model.
  37889. *
  37890. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37891. */
  37892. getDistanceModel() {
  37893. return this.panner.distanceModel;
  37894. }
  37895. /**
  37896. * Defines which algorithm to use to reduce the volume of the audio source
  37897. * as it moves away from the listener.
  37898. *
  37899. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37900. * for more details.
  37901. *
  37902. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37903. * @return {PositionalAudio} A reference to this instance.
  37904. */
  37905. setDistanceModel( value ) {
  37906. this.panner.distanceModel = value;
  37907. return this;
  37908. }
  37909. /**
  37910. * Returns the current max distance.
  37911. *
  37912. * @return {number} The max distance.
  37913. */
  37914. getMaxDistance() {
  37915. return this.panner.maxDistance;
  37916. }
  37917. /**
  37918. * Defines the maximum distance between the audio source and the listener,
  37919. * after which the volume is not reduced any further.
  37920. *
  37921. * This value is used only by the `linear` distance model.
  37922. *
  37923. * @param {number} value - The max distance.
  37924. * @return {PositionalAudio} A reference to this instance.
  37925. */
  37926. setMaxDistance( value ) {
  37927. this.panner.maxDistance = value;
  37928. return this;
  37929. }
  37930. /**
  37931. * Sets the directional cone in which the audio can be listened.
  37932. *
  37933. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37934. * @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.
  37935. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37936. * @return {PositionalAudio} A reference to this instance.
  37937. */
  37938. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37939. this.panner.coneInnerAngle = coneInnerAngle;
  37940. this.panner.coneOuterAngle = coneOuterAngle;
  37941. this.panner.coneOuterGain = coneOuterGain;
  37942. return this;
  37943. }
  37944. updateMatrixWorld( force ) {
  37945. super.updateMatrixWorld( force );
  37946. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37947. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37948. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37949. const panner = this.panner;
  37950. if ( panner.positionX ) {
  37951. // code path for Chrome and Firefox (see #14393)
  37952. const endTime = this.context.currentTime + this.listener.timeDelta;
  37953. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37954. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37955. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37956. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37957. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37958. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37959. } else {
  37960. panner.setPosition( _position.x, _position.y, _position.z );
  37961. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37962. }
  37963. }
  37964. }
  37965. /**
  37966. * This class can be used to analyse audio data.
  37967. *
  37968. * ```js
  37969. * // create an AudioListener and add it to the camera
  37970. * const listener = new THREE.AudioListener();
  37971. * camera.add( listener );
  37972. *
  37973. * // create an Audio source
  37974. * const sound = new THREE.Audio( listener );
  37975. *
  37976. * // load a sound and set it as the Audio object's buffer
  37977. * const audioLoader = new THREE.AudioLoader();
  37978. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37979. * sound.setBuffer( buffer );
  37980. * sound.setLoop(true);
  37981. * sound.setVolume(0.5);
  37982. * sound.play();
  37983. * });
  37984. *
  37985. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37986. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37987. *
  37988. * // get the average frequency of the sound
  37989. * const data = analyser.getAverageFrequency();
  37990. * ```
  37991. */
  37992. class AudioAnalyser {
  37993. /**
  37994. * Constructs a new audio analyzer.
  37995. *
  37996. * @param {Audio} audio - The audio to analyze.
  37997. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37998. */
  37999. constructor( audio, fftSize = 2048 ) {
  38000. /**
  38001. * The global audio listener.
  38002. *
  38003. * @type {AnalyserNode}
  38004. */
  38005. this.analyser = audio.context.createAnalyser();
  38006. this.analyser.fftSize = fftSize;
  38007. /**
  38008. * Holds the analyzed data.
  38009. *
  38010. * @type {Uint8Array}
  38011. */
  38012. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  38013. audio.getOutput().connect( this.analyser );
  38014. }
  38015. /**
  38016. * Returns an array with frequency data of the audio.
  38017. *
  38018. * Each item in the array represents the decibel value for a specific frequency.
  38019. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  38020. * For example, for 48000 sample rate, the last item of the array will represent
  38021. * the decibel value for 24000 Hz.
  38022. *
  38023. * @return {Uint8Array} The frequency data.
  38024. */
  38025. getFrequencyData() {
  38026. this.analyser.getByteFrequencyData( this.data );
  38027. return this.data;
  38028. }
  38029. /**
  38030. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  38031. *
  38032. * @return {number} The average frequency.
  38033. */
  38034. getAverageFrequency() {
  38035. let value = 0;
  38036. const data = this.getFrequencyData();
  38037. for ( let i = 0; i < data.length; i ++ ) {
  38038. value += data[ i ];
  38039. }
  38040. return value / data.length;
  38041. }
  38042. }
  38043. /**
  38044. * Buffered scene graph property that allows weighted accumulation; used internally.
  38045. */
  38046. class PropertyMixer {
  38047. /**
  38048. * Constructs a new property mixer.
  38049. *
  38050. * @param {PropertyBinding} binding - The property binding.
  38051. * @param {string} typeName - The keyframe track type name.
  38052. * @param {number} valueSize - The keyframe track value size.
  38053. */
  38054. constructor( binding, typeName, valueSize ) {
  38055. /**
  38056. * The property binding.
  38057. *
  38058. * @type {PropertyBinding}
  38059. */
  38060. this.binding = binding;
  38061. /**
  38062. * The keyframe track value size.
  38063. *
  38064. * @type {number}
  38065. */
  38066. this.valueSize = valueSize;
  38067. let mixFunction,
  38068. mixFunctionAdditive,
  38069. setIdentity;
  38070. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  38071. //
  38072. // interpolators can use .buffer as their .result
  38073. // the data then goes to 'incoming'
  38074. //
  38075. // 'accu0' and 'accu1' are used frame-interleaved for
  38076. // the cumulative result and are compared to detect
  38077. // changes
  38078. //
  38079. // 'orig' stores the original state of the property
  38080. //
  38081. // 'add' is used for additive cumulative results
  38082. //
  38083. // 'work' is optional and is only present for quaternion types. It is used
  38084. // to store intermediate quaternion multiplication results
  38085. switch ( typeName ) {
  38086. case 'quaternion':
  38087. mixFunction = this._slerp;
  38088. mixFunctionAdditive = this._slerpAdditive;
  38089. setIdentity = this._setAdditiveIdentityQuaternion;
  38090. this.buffer = new Float64Array( valueSize * 6 );
  38091. this._workIndex = 5;
  38092. break;
  38093. case 'string':
  38094. case 'bool':
  38095. mixFunction = this._select;
  38096. // Use the regular mix function and for additive on these types,
  38097. // additive is not relevant for non-numeric types
  38098. mixFunctionAdditive = this._select;
  38099. setIdentity = this._setAdditiveIdentityOther;
  38100. this.buffer = new Array( valueSize * 5 );
  38101. break;
  38102. default:
  38103. mixFunction = this._lerp;
  38104. mixFunctionAdditive = this._lerpAdditive;
  38105. setIdentity = this._setAdditiveIdentityNumeric;
  38106. this.buffer = new Float64Array( valueSize * 5 );
  38107. }
  38108. this._mixBufferRegion = mixFunction;
  38109. this._mixBufferRegionAdditive = mixFunctionAdditive;
  38110. this._setIdentity = setIdentity;
  38111. this._origIndex = 3;
  38112. this._addIndex = 4;
  38113. /**
  38114. * Accumulated weight of the property binding.
  38115. *
  38116. * @type {number}
  38117. * @default 0
  38118. */
  38119. this.cumulativeWeight = 0;
  38120. /**
  38121. * Accumulated additive weight of the property binding.
  38122. *
  38123. * @type {number}
  38124. * @default 0
  38125. */
  38126. this.cumulativeWeightAdditive = 0;
  38127. /**
  38128. * Number of active keyframe tracks currently using this property binding.
  38129. *
  38130. * @type {number}
  38131. * @default 0
  38132. */
  38133. this.useCount = 0;
  38134. /**
  38135. * Number of keyframe tracks referencing this property binding.
  38136. *
  38137. * @type {number}
  38138. * @default 0
  38139. */
  38140. this.referenceCount = 0;
  38141. }
  38142. /**
  38143. * Accumulates data in the `incoming` region into `accu<i>`.
  38144. *
  38145. * @param {number} accuIndex - The accumulation index.
  38146. * @param {number} weight - The weight.
  38147. */
  38148. accumulate( accuIndex, weight ) {
  38149. // note: happily accumulating nothing when weight = 0, the caller knows
  38150. // the weight and shouldn't have made the call in the first place
  38151. const buffer = this.buffer,
  38152. stride = this.valueSize,
  38153. offset = accuIndex * stride + stride;
  38154. let currentWeight = this.cumulativeWeight;
  38155. if ( currentWeight === 0 ) {
  38156. // accuN := incoming * weight
  38157. for ( let i = 0; i !== stride; ++ i ) {
  38158. buffer[ offset + i ] = buffer[ i ];
  38159. }
  38160. currentWeight = weight;
  38161. } else {
  38162. // accuN := accuN + incoming * weight
  38163. currentWeight += weight;
  38164. const mix = weight / currentWeight;
  38165. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  38166. }
  38167. this.cumulativeWeight = currentWeight;
  38168. }
  38169. /**
  38170. * Accumulates data in the `incoming` region into `add`.
  38171. *
  38172. * @param {number} weight - The weight.
  38173. */
  38174. accumulateAdditive( weight ) {
  38175. const buffer = this.buffer,
  38176. stride = this.valueSize,
  38177. offset = stride * this._addIndex;
  38178. if ( this.cumulativeWeightAdditive === 0 ) {
  38179. // add = identity
  38180. this._setIdentity();
  38181. }
  38182. // add := add + incoming * weight
  38183. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  38184. this.cumulativeWeightAdditive += weight;
  38185. }
  38186. /**
  38187. * Applies the state of `accu<i>` to the binding when accus differ.
  38188. *
  38189. * @param {number} accuIndex - The accumulation index.
  38190. */
  38191. apply( accuIndex ) {
  38192. const stride = this.valueSize,
  38193. buffer = this.buffer,
  38194. offset = accuIndex * stride + stride,
  38195. weight = this.cumulativeWeight,
  38196. weightAdditive = this.cumulativeWeightAdditive,
  38197. binding = this.binding;
  38198. this.cumulativeWeight = 0;
  38199. this.cumulativeWeightAdditive = 0;
  38200. if ( weight < 1 ) {
  38201. // accuN := accuN + original * ( 1 - cumulativeWeight )
  38202. const originalValueOffset = stride * this._origIndex;
  38203. this._mixBufferRegion(
  38204. buffer, offset, originalValueOffset, 1 - weight, stride );
  38205. }
  38206. if ( weightAdditive > 0 ) {
  38207. // accuN := accuN + additive accuN
  38208. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  38209. }
  38210. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  38211. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  38212. // value has changed -> update scene graph
  38213. binding.setValue( buffer, offset );
  38214. break;
  38215. }
  38216. }
  38217. }
  38218. /**
  38219. * Remembers the state of the bound property and copy it to both accus.
  38220. */
  38221. saveOriginalState() {
  38222. const binding = this.binding;
  38223. const buffer = this.buffer,
  38224. stride = this.valueSize,
  38225. originalValueOffset = stride * this._origIndex;
  38226. binding.getValue( buffer, originalValueOffset );
  38227. // accu[0..1] := orig -- initially detect changes against the original
  38228. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  38229. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  38230. }
  38231. // Add to identity for additive
  38232. this._setIdentity();
  38233. this.cumulativeWeight = 0;
  38234. this.cumulativeWeightAdditive = 0;
  38235. }
  38236. /**
  38237. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  38238. */
  38239. restoreOriginalState() {
  38240. const originalValueOffset = this.valueSize * 3;
  38241. this.binding.setValue( this.buffer, originalValueOffset );
  38242. }
  38243. // internals
  38244. _setAdditiveIdentityNumeric() {
  38245. const startIndex = this._addIndex * this.valueSize;
  38246. const endIndex = startIndex + this.valueSize;
  38247. for ( let i = startIndex; i < endIndex; i ++ ) {
  38248. this.buffer[ i ] = 0;
  38249. }
  38250. }
  38251. _setAdditiveIdentityQuaternion() {
  38252. this._setAdditiveIdentityNumeric();
  38253. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  38254. }
  38255. _setAdditiveIdentityOther() {
  38256. const startIndex = this._origIndex * this.valueSize;
  38257. const targetIndex = this._addIndex * this.valueSize;
  38258. for ( let i = 0; i < this.valueSize; i ++ ) {
  38259. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  38260. }
  38261. }
  38262. // mix functions
  38263. _select( buffer, dstOffset, srcOffset, t, stride ) {
  38264. if ( t >= 0.5 ) {
  38265. for ( let i = 0; i !== stride; ++ i ) {
  38266. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  38267. }
  38268. }
  38269. }
  38270. _slerp( buffer, dstOffset, srcOffset, t ) {
  38271. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  38272. }
  38273. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  38274. const workOffset = this._workIndex * stride;
  38275. // Store result in intermediate buffer offset
  38276. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  38277. // Slerp to the intermediate result
  38278. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  38279. }
  38280. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  38281. const s = 1 - t;
  38282. for ( let i = 0; i !== stride; ++ i ) {
  38283. const j = dstOffset + i;
  38284. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  38285. }
  38286. }
  38287. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  38288. for ( let i = 0; i !== stride; ++ i ) {
  38289. const j = dstOffset + i;
  38290. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  38291. }
  38292. }
  38293. }
  38294. // Characters [].:/ are reserved for track binding syntax.
  38295. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  38296. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  38297. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  38298. // only latin characters, and the unicode \p{L} is not yet supported. So
  38299. // instead, we exclude reserved characters and match everything else.
  38300. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  38301. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  38302. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  38303. // be matched to parse the rest of the track name.
  38304. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  38305. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  38306. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  38307. // Object on target node, and accessor. May not contain reserved
  38308. // characters. Accessor may contain any character except closing bracket.
  38309. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  38310. // Property and accessor. May not contain reserved characters. Accessor may
  38311. // contain any non-bracket characters.
  38312. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  38313. const _trackRe = new RegExp( ''
  38314. + '^'
  38315. + _directoryRe
  38316. + _nodeRe
  38317. + _objectRe
  38318. + _propertyRe
  38319. + '$'
  38320. );
  38321. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  38322. class Composite {
  38323. constructor( targetGroup, path, optionalParsedPath ) {
  38324. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  38325. this._targetGroup = targetGroup;
  38326. this._bindings = targetGroup.subscribe_( path, parsedPath );
  38327. }
  38328. getValue( array, offset ) {
  38329. this.bind(); // bind all binding
  38330. const firstValidIndex = this._targetGroup.nCachedObjects_,
  38331. binding = this._bindings[ firstValidIndex ];
  38332. // and only call .getValue on the first
  38333. if ( binding !== undefined ) binding.getValue( array, offset );
  38334. }
  38335. setValue( array, offset ) {
  38336. const bindings = this._bindings;
  38337. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38338. bindings[ i ].setValue( array, offset );
  38339. }
  38340. }
  38341. bind() {
  38342. const bindings = this._bindings;
  38343. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38344. bindings[ i ].bind();
  38345. }
  38346. }
  38347. unbind() {
  38348. const bindings = this._bindings;
  38349. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38350. bindings[ i ].unbind();
  38351. }
  38352. }
  38353. }
  38354. // Note: This class uses a State pattern on a per-method basis:
  38355. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  38356. // prototype version of these methods with one that represents
  38357. // the bound state. When the property is not found, the methods
  38358. // become no-ops.
  38359. /**
  38360. * This holds a reference to a real property in the scene graph; used internally.
  38361. */
  38362. class PropertyBinding {
  38363. /**
  38364. * Constructs a new property binding.
  38365. *
  38366. * @param {Object} rootNode - The root node.
  38367. * @param {string} path - The path.
  38368. * @param {?Object} [parsedPath] - The parsed path.
  38369. */
  38370. constructor( rootNode, path, parsedPath ) {
  38371. /**
  38372. * The object path to the animated property.
  38373. *
  38374. * @type {string}
  38375. */
  38376. this.path = path;
  38377. /**
  38378. * An object holding information about the path.
  38379. *
  38380. * @type {Object}
  38381. */
  38382. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  38383. /**
  38384. * The object owns the animated property.
  38385. *
  38386. * @type {?Object}
  38387. */
  38388. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  38389. /**
  38390. * The root node.
  38391. *
  38392. * @type {Object3D|Skeleton}
  38393. */
  38394. this.rootNode = rootNode;
  38395. // initial state of these methods that calls 'bind'
  38396. this.getValue = this._getValue_unbound;
  38397. this.setValue = this._setValue_unbound;
  38398. }
  38399. /**
  38400. * Factory method for creating a property binding from the given parameters.
  38401. *
  38402. * @static
  38403. * @param {Object} root - The root node.
  38404. * @param {string} path - The path.
  38405. * @param {?Object} [parsedPath] - The parsed path.
  38406. * @return {PropertyBinding|Composite} The created property binding or composite.
  38407. */
  38408. static create( root, path, parsedPath ) {
  38409. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  38410. return new PropertyBinding( root, path, parsedPath );
  38411. } else {
  38412. return new PropertyBinding.Composite( root, path, parsedPath );
  38413. }
  38414. }
  38415. /**
  38416. * Replaces spaces with underscores and removes unsupported characters from
  38417. * node names, to ensure compatibility with parseTrackName().
  38418. *
  38419. * @param {string} name - Node name to be sanitized.
  38420. * @return {string} The sanitized node name.
  38421. */
  38422. static sanitizeNodeName( name ) {
  38423. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  38424. }
  38425. /**
  38426. * Parses the given track name (an object path to an animated property) and
  38427. * returns an object with information about the path. Matches strings in the following forms:
  38428. *
  38429. * - nodeName.property
  38430. * - nodeName.property[accessor]
  38431. * - nodeName.material.property[accessor]
  38432. * - uuid.property[accessor]
  38433. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  38434. * - parentName/nodeName.property
  38435. * - parentName/parentName/nodeName.property[index]
  38436. * - .bone[Armature.DEF_cog].position
  38437. * - scene:helium_balloon_model:helium_balloon_model.position
  38438. *
  38439. * @static
  38440. * @param {string} trackName - The track name to parse.
  38441. * @return {Object} The parsed track name as an object.
  38442. */
  38443. static parseTrackName( trackName ) {
  38444. const matches = _trackRe.exec( trackName );
  38445. if ( matches === null ) {
  38446. throw new Error( 'THREE.PropertyBinding: Cannot parse trackName: ' + trackName );
  38447. }
  38448. const results = {
  38449. // directoryName: matches[ 1 ], // (tschw) currently unused
  38450. nodeName: matches[ 2 ],
  38451. objectName: matches[ 3 ],
  38452. objectIndex: matches[ 4 ],
  38453. propertyName: matches[ 5 ], // required
  38454. propertyIndex: matches[ 6 ]
  38455. };
  38456. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  38457. if ( lastDot !== undefined && lastDot !== -1 ) {
  38458. const objectName = results.nodeName.substring( lastDot + 1 );
  38459. // Object names must be checked against an allowlist. Otherwise, there
  38460. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  38461. // 'bar' could be the objectName, or part of a nodeName (which can
  38462. // include '.' characters).
  38463. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  38464. results.nodeName = results.nodeName.substring( 0, lastDot );
  38465. results.objectName = objectName;
  38466. }
  38467. }
  38468. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  38469. throw new Error( 'THREE.PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  38470. }
  38471. return results;
  38472. }
  38473. /**
  38474. * Searches for a node in the hierarchy of the given root object by the given
  38475. * node name.
  38476. *
  38477. * @static
  38478. * @param {Object} root - The root object.
  38479. * @param {string|number} nodeName - The name of the node.
  38480. * @return {?Object} The found node. Returns `null` if no object was found.
  38481. */
  38482. static findNode( root, nodeName ) {
  38483. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  38484. return root;
  38485. }
  38486. // search into skeleton bones.
  38487. if ( root.skeleton ) {
  38488. const bone = root.skeleton.getBoneByName( nodeName );
  38489. if ( bone !== undefined ) {
  38490. return bone;
  38491. }
  38492. }
  38493. // search into node subtree.
  38494. if ( root.children ) {
  38495. const searchNodeSubtree = function ( children ) {
  38496. for ( let i = 0; i < children.length; i ++ ) {
  38497. const childNode = children[ i ];
  38498. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  38499. return childNode;
  38500. }
  38501. const result = searchNodeSubtree( childNode.children );
  38502. if ( result ) return result;
  38503. }
  38504. return null;
  38505. };
  38506. const subTreeNode = searchNodeSubtree( root.children );
  38507. if ( subTreeNode ) {
  38508. return subTreeNode;
  38509. }
  38510. }
  38511. return null;
  38512. }
  38513. // these are used to "bind" a nonexistent property
  38514. _getValue_unavailable() {}
  38515. _setValue_unavailable() {}
  38516. // Getters
  38517. _getValue_direct( buffer, offset ) {
  38518. buffer[ offset ] = this.targetObject[ this.propertyName ];
  38519. }
  38520. _getValue_array( buffer, offset ) {
  38521. const source = this.resolvedProperty;
  38522. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  38523. buffer[ offset ++ ] = source[ i ];
  38524. }
  38525. }
  38526. _getValue_arrayElement( buffer, offset ) {
  38527. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  38528. }
  38529. _getValue_toArray( buffer, offset ) {
  38530. this.resolvedProperty.toArray( buffer, offset );
  38531. }
  38532. // Direct
  38533. _setValue_direct( buffer, offset ) {
  38534. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38535. }
  38536. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  38537. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38538. this.targetObject.needsUpdate = true;
  38539. }
  38540. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38541. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38542. this.targetObject.matrixWorldNeedsUpdate = true;
  38543. }
  38544. // EntireArray
  38545. _setValue_array( buffer, offset ) {
  38546. const dest = this.resolvedProperty;
  38547. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38548. dest[ i ] = buffer[ offset ++ ];
  38549. }
  38550. }
  38551. _setValue_array_setNeedsUpdate( buffer, offset ) {
  38552. const dest = this.resolvedProperty;
  38553. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38554. dest[ i ] = buffer[ offset ++ ];
  38555. }
  38556. this.targetObject.needsUpdate = true;
  38557. }
  38558. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38559. const dest = this.resolvedProperty;
  38560. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38561. dest[ i ] = buffer[ offset ++ ];
  38562. }
  38563. this.targetObject.matrixWorldNeedsUpdate = true;
  38564. }
  38565. // ArrayElement
  38566. _setValue_arrayElement( buffer, offset ) {
  38567. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38568. }
  38569. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  38570. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38571. this.targetObject.needsUpdate = true;
  38572. }
  38573. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38574. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38575. this.targetObject.matrixWorldNeedsUpdate = true;
  38576. }
  38577. // HasToFromArray
  38578. _setValue_fromArray( buffer, offset ) {
  38579. this.resolvedProperty.fromArray( buffer, offset );
  38580. }
  38581. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  38582. this.resolvedProperty.fromArray( buffer, offset );
  38583. this.targetObject.needsUpdate = true;
  38584. }
  38585. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38586. this.resolvedProperty.fromArray( buffer, offset );
  38587. this.targetObject.matrixWorldNeedsUpdate = true;
  38588. }
  38589. _getValue_unbound( targetArray, offset ) {
  38590. this.bind();
  38591. this.getValue( targetArray, offset );
  38592. }
  38593. _setValue_unbound( sourceArray, offset ) {
  38594. this.bind();
  38595. this.setValue( sourceArray, offset );
  38596. }
  38597. /**
  38598. * Creates a getter / setter pair for the property tracked by this binding.
  38599. */
  38600. bind() {
  38601. let targetObject = this.node;
  38602. const parsedPath = this.parsedPath;
  38603. const objectName = parsedPath.objectName;
  38604. const propertyName = parsedPath.propertyName;
  38605. let propertyIndex = parsedPath.propertyIndex;
  38606. if ( ! targetObject ) {
  38607. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38608. this.node = targetObject;
  38609. }
  38610. // set fail state so we can just 'return' on error
  38611. this.getValue = this._getValue_unavailable;
  38612. this.setValue = this._setValue_unavailable;
  38613. // ensure there is a value node
  38614. if ( ! targetObject ) {
  38615. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38616. return;
  38617. }
  38618. if ( objectName ) {
  38619. let objectIndex = parsedPath.objectIndex;
  38620. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38621. switch ( objectName ) {
  38622. case 'materials':
  38623. if ( ! targetObject.material ) {
  38624. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38625. return;
  38626. }
  38627. if ( ! targetObject.material.materials ) {
  38628. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38629. return;
  38630. }
  38631. targetObject = targetObject.material.materials;
  38632. break;
  38633. case 'bones':
  38634. if ( ! targetObject.skeleton ) {
  38635. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38636. return;
  38637. }
  38638. // potential future optimization: skip this if propertyIndex is already an integer
  38639. // and convert the integer string to a true integer.
  38640. targetObject = targetObject.skeleton.bones;
  38641. // support resolving morphTarget names into indices.
  38642. for ( let i = 0; i < targetObject.length; i ++ ) {
  38643. if ( targetObject[ i ].name === objectIndex ) {
  38644. objectIndex = i;
  38645. break;
  38646. }
  38647. }
  38648. break;
  38649. case 'map':
  38650. if ( 'map' in targetObject ) {
  38651. targetObject = targetObject.map;
  38652. break;
  38653. }
  38654. if ( ! targetObject.material ) {
  38655. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38656. return;
  38657. }
  38658. if ( ! targetObject.material.map ) {
  38659. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38660. return;
  38661. }
  38662. targetObject = targetObject.material.map;
  38663. break;
  38664. default:
  38665. if ( targetObject[ objectName ] === undefined ) {
  38666. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38667. return;
  38668. }
  38669. targetObject = targetObject[ objectName ];
  38670. }
  38671. if ( objectIndex !== undefined ) {
  38672. if ( targetObject[ objectIndex ] === undefined ) {
  38673. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38674. return;
  38675. }
  38676. targetObject = targetObject[ objectIndex ];
  38677. }
  38678. }
  38679. // resolve property
  38680. const nodeProperty = targetObject[ propertyName ];
  38681. if ( nodeProperty === undefined ) {
  38682. const nodeName = parsedPath.nodeName;
  38683. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38684. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38685. return;
  38686. }
  38687. // determine versioning scheme
  38688. let versioning = this.Versioning.None;
  38689. this.targetObject = targetObject;
  38690. if ( targetObject.isMaterial === true ) {
  38691. versioning = this.Versioning.NeedsUpdate;
  38692. } else if ( targetObject.isObject3D === true ) {
  38693. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38694. }
  38695. // determine how the property gets bound
  38696. let bindingType = this.BindingType.Direct;
  38697. if ( propertyIndex !== undefined ) {
  38698. // access a sub element of the property array (only primitives are supported right now)
  38699. if ( propertyName === 'morphTargetInfluences' ) {
  38700. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38701. // support resolving morphTarget names into indices.
  38702. if ( ! targetObject.geometry ) {
  38703. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38704. return;
  38705. }
  38706. if ( ! targetObject.geometry.morphAttributes ) {
  38707. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38708. return;
  38709. }
  38710. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38711. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38712. }
  38713. }
  38714. bindingType = this.BindingType.ArrayElement;
  38715. this.resolvedProperty = nodeProperty;
  38716. this.propertyIndex = propertyIndex;
  38717. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38718. // must use copy for Object3D.Euler/Quaternion
  38719. bindingType = this.BindingType.HasFromToArray;
  38720. this.resolvedProperty = nodeProperty;
  38721. } else if ( Array.isArray( nodeProperty ) ) {
  38722. bindingType = this.BindingType.EntireArray;
  38723. this.resolvedProperty = nodeProperty;
  38724. } else {
  38725. this.propertyName = propertyName;
  38726. }
  38727. // select getter / setter
  38728. this.getValue = this.GetterByBindingType[ bindingType ];
  38729. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38730. }
  38731. /**
  38732. * Unbinds the property.
  38733. */
  38734. unbind() {
  38735. this.node = null;
  38736. // back to the prototype version of getValue / setValue
  38737. // note: avoiding to mutate the shape of 'this' via 'delete'
  38738. this.getValue = this._getValue_unbound;
  38739. this.setValue = this._setValue_unbound;
  38740. }
  38741. }
  38742. PropertyBinding.Composite = Composite;
  38743. PropertyBinding.prototype.BindingType = {
  38744. Direct: 0,
  38745. EntireArray: 1,
  38746. ArrayElement: 2,
  38747. HasFromToArray: 3
  38748. };
  38749. PropertyBinding.prototype.Versioning = {
  38750. None: 0,
  38751. NeedsUpdate: 1,
  38752. MatrixWorldNeedsUpdate: 2
  38753. };
  38754. PropertyBinding.prototype.GetterByBindingType = [
  38755. PropertyBinding.prototype._getValue_direct,
  38756. PropertyBinding.prototype._getValue_array,
  38757. PropertyBinding.prototype._getValue_arrayElement,
  38758. PropertyBinding.prototype._getValue_toArray,
  38759. ];
  38760. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38761. [
  38762. // Direct
  38763. PropertyBinding.prototype._setValue_direct,
  38764. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38765. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38766. ], [
  38767. // EntireArray
  38768. PropertyBinding.prototype._setValue_array,
  38769. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38770. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38771. ], [
  38772. // ArrayElement
  38773. PropertyBinding.prototype._setValue_arrayElement,
  38774. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38775. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38776. ], [
  38777. // HasToFromArray
  38778. PropertyBinding.prototype._setValue_fromArray,
  38779. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38780. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38781. ]
  38782. ];
  38783. /**
  38784. * A group of objects that receives a shared animation state.
  38785. *
  38786. * Usage:
  38787. *
  38788. * - Add objects you would otherwise pass as 'root' to the
  38789. * constructor or the .clipAction method of AnimationMixer.
  38790. * - Instead pass this object as 'root'.
  38791. * - You can also add and remove objects later when the mixer is running.
  38792. *
  38793. * Note:
  38794. *
  38795. * - Objects of this class appear as one object to the mixer,
  38796. * so cache control of the individual objects must be done on the group.
  38797. *
  38798. * Limitation:
  38799. *
  38800. * - The animated properties must be compatible among the all objects in the group.
  38801. * - A single property can either be controlled through a target group or directly, but not both.
  38802. */
  38803. class AnimationObjectGroup {
  38804. /**
  38805. * Constructs a new animation group.
  38806. *
  38807. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38808. */
  38809. constructor() {
  38810. /**
  38811. * This flag can be used for type testing.
  38812. *
  38813. * @type {boolean}
  38814. * @readonly
  38815. * @default true
  38816. */
  38817. this.isAnimationObjectGroup = true;
  38818. /**
  38819. * The UUID of the 3D object.
  38820. *
  38821. * @type {string}
  38822. * @readonly
  38823. */
  38824. this.uuid = generateUUID();
  38825. // cached objects followed by the active ones
  38826. this._objects = Array.prototype.slice.call( arguments );
  38827. this.nCachedObjects_ = 0; // threshold
  38828. // note: read by PropertyBinding.Composite
  38829. const indices = {};
  38830. this._indicesByUUID = indices; // for bookkeeping
  38831. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38832. indices[ arguments[ i ].uuid ] = i;
  38833. }
  38834. this._paths = []; // inside: string
  38835. this._parsedPaths = []; // inside: { we don't care, here }
  38836. this._bindings = []; // inside: Array< PropertyBinding >
  38837. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38838. const scope = this;
  38839. this.stats = {
  38840. objects: {
  38841. get total() {
  38842. return scope._objects.length;
  38843. },
  38844. get inUse() {
  38845. return this.total - scope.nCachedObjects_;
  38846. }
  38847. },
  38848. get bindingsPerObject() {
  38849. return scope._bindings.length;
  38850. }
  38851. };
  38852. }
  38853. /**
  38854. * Adds an arbitrary number of objects to this animation group.
  38855. *
  38856. * @param {...Object3D} arguments - The 3D objects to add.
  38857. */
  38858. add() {
  38859. const objects = this._objects,
  38860. indicesByUUID = this._indicesByUUID,
  38861. paths = this._paths,
  38862. parsedPaths = this._parsedPaths,
  38863. bindings = this._bindings,
  38864. nBindings = bindings.length;
  38865. let knownObject = undefined,
  38866. nObjects = objects.length,
  38867. nCachedObjects = this.nCachedObjects_;
  38868. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38869. const object = arguments[ i ],
  38870. uuid = object.uuid;
  38871. let index = indicesByUUID[ uuid ];
  38872. if ( index === undefined ) {
  38873. // unknown object -> add it to the ACTIVE region
  38874. index = nObjects ++;
  38875. indicesByUUID[ uuid ] = index;
  38876. objects.push( object );
  38877. // accounting is done, now do the same for all bindings
  38878. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38879. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38880. }
  38881. } else if ( index < nCachedObjects ) {
  38882. knownObject = objects[ index ];
  38883. // move existing object to the ACTIVE region
  38884. const firstActiveIndex = -- nCachedObjects,
  38885. lastCachedObject = objects[ firstActiveIndex ];
  38886. indicesByUUID[ lastCachedObject.uuid ] = index;
  38887. objects[ index ] = lastCachedObject;
  38888. indicesByUUID[ uuid ] = firstActiveIndex;
  38889. objects[ firstActiveIndex ] = object;
  38890. // accounting is done, now do the same for all bindings
  38891. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38892. const bindingsForPath = bindings[ j ],
  38893. lastCached = bindingsForPath[ firstActiveIndex ];
  38894. let binding = bindingsForPath[ index ];
  38895. bindingsForPath[ index ] = lastCached;
  38896. if ( binding === undefined ) {
  38897. // since we do not bother to create new bindings
  38898. // for objects that are cached, the binding may
  38899. // or may not exist
  38900. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38901. }
  38902. bindingsForPath[ firstActiveIndex ] = binding;
  38903. }
  38904. } else if ( objects[ index ] !== knownObject ) {
  38905. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38906. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38907. } // else the object is already where we want it to be
  38908. } // for arguments
  38909. this.nCachedObjects_ = nCachedObjects;
  38910. }
  38911. /**
  38912. * Removes an arbitrary number of objects to this animation group
  38913. *
  38914. * @param {...Object3D} arguments - The 3D objects to remove.
  38915. */
  38916. remove() {
  38917. const objects = this._objects,
  38918. indicesByUUID = this._indicesByUUID,
  38919. bindings = this._bindings,
  38920. nBindings = bindings.length;
  38921. let nCachedObjects = this.nCachedObjects_;
  38922. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38923. const object = arguments[ i ],
  38924. uuid = object.uuid,
  38925. index = indicesByUUID[ uuid ];
  38926. if ( index !== undefined && index >= nCachedObjects ) {
  38927. // move existing object into the CACHED region
  38928. const lastCachedIndex = nCachedObjects ++,
  38929. firstActiveObject = objects[ lastCachedIndex ];
  38930. indicesByUUID[ firstActiveObject.uuid ] = index;
  38931. objects[ index ] = firstActiveObject;
  38932. indicesByUUID[ uuid ] = lastCachedIndex;
  38933. objects[ lastCachedIndex ] = object;
  38934. // accounting is done, now do the same for all bindings
  38935. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38936. const bindingsForPath = bindings[ j ],
  38937. firstActive = bindingsForPath[ lastCachedIndex ],
  38938. binding = bindingsForPath[ index ];
  38939. bindingsForPath[ index ] = firstActive;
  38940. bindingsForPath[ lastCachedIndex ] = binding;
  38941. }
  38942. }
  38943. } // for arguments
  38944. this.nCachedObjects_ = nCachedObjects;
  38945. }
  38946. /**
  38947. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38948. *
  38949. * @param {...Object3D} arguments - The 3D objects to uncache.
  38950. */
  38951. uncache() {
  38952. const objects = this._objects,
  38953. indicesByUUID = this._indicesByUUID,
  38954. bindings = this._bindings,
  38955. nBindings = bindings.length;
  38956. let nCachedObjects = this.nCachedObjects_,
  38957. nObjects = objects.length;
  38958. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38959. const object = arguments[ i ],
  38960. uuid = object.uuid,
  38961. index = indicesByUUID[ uuid ];
  38962. if ( index !== undefined ) {
  38963. delete indicesByUUID[ uuid ];
  38964. if ( index < nCachedObjects ) {
  38965. // object is cached, shrink the CACHED region
  38966. const firstActiveIndex = -- nCachedObjects,
  38967. lastCachedObject = objects[ firstActiveIndex ],
  38968. lastIndex = -- nObjects,
  38969. lastObject = objects[ lastIndex ];
  38970. // last cached object takes this object's place
  38971. indicesByUUID[ lastCachedObject.uuid ] = index;
  38972. objects[ index ] = lastCachedObject;
  38973. // last object goes to the activated slot and pop
  38974. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38975. objects[ firstActiveIndex ] = lastObject;
  38976. objects.pop();
  38977. // accounting is done, now do the same for all bindings
  38978. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38979. const bindingsForPath = bindings[ j ],
  38980. lastCached = bindingsForPath[ firstActiveIndex ],
  38981. last = bindingsForPath[ lastIndex ];
  38982. bindingsForPath[ index ] = lastCached;
  38983. bindingsForPath[ firstActiveIndex ] = last;
  38984. bindingsForPath.pop();
  38985. }
  38986. } else {
  38987. // object is active, just swap with the last and pop
  38988. const lastIndex = -- nObjects,
  38989. lastObject = objects[ lastIndex ];
  38990. if ( lastIndex > 0 ) {
  38991. indicesByUUID[ lastObject.uuid ] = index;
  38992. }
  38993. objects[ index ] = lastObject;
  38994. objects.pop();
  38995. // accounting is done, now do the same for all bindings
  38996. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38997. const bindingsForPath = bindings[ j ];
  38998. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38999. bindingsForPath.pop();
  39000. }
  39001. } // cached or active
  39002. } // if object is known
  39003. } // for arguments
  39004. this.nCachedObjects_ = nCachedObjects;
  39005. }
  39006. // Internal interface used by befriended PropertyBinding.Composite:
  39007. subscribe_( path, parsedPath ) {
  39008. // returns an array of bindings for the given path that is changed
  39009. // according to the contained objects in the group
  39010. const indicesByPath = this._bindingsIndicesByPath;
  39011. let index = indicesByPath[ path ];
  39012. const bindings = this._bindings;
  39013. if ( index !== undefined ) return bindings[ index ];
  39014. const paths = this._paths,
  39015. parsedPaths = this._parsedPaths,
  39016. objects = this._objects,
  39017. nObjects = objects.length,
  39018. nCachedObjects = this.nCachedObjects_,
  39019. bindingsForPath = new Array( nObjects );
  39020. index = bindings.length;
  39021. indicesByPath[ path ] = index;
  39022. paths.push( path );
  39023. parsedPaths.push( parsedPath );
  39024. bindings.push( bindingsForPath );
  39025. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  39026. const object = objects[ i ];
  39027. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  39028. }
  39029. return bindingsForPath;
  39030. }
  39031. unsubscribe_( path ) {
  39032. // tells the group to forget about a property path and no longer
  39033. // update the array previously obtained with 'subscribe_'
  39034. const indicesByPath = this._bindingsIndicesByPath,
  39035. index = indicesByPath[ path ];
  39036. if ( index !== undefined ) {
  39037. const paths = this._paths,
  39038. parsedPaths = this._parsedPaths,
  39039. bindings = this._bindings,
  39040. lastBindingsIndex = bindings.length - 1,
  39041. lastBindings = bindings[ lastBindingsIndex ],
  39042. lastBindingsPath = path[ lastBindingsIndex ];
  39043. indicesByPath[ lastBindingsPath ] = index;
  39044. bindings[ index ] = lastBindings;
  39045. bindings.pop();
  39046. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  39047. parsedPaths.pop();
  39048. paths[ index ] = paths[ lastBindingsIndex ];
  39049. paths.pop();
  39050. }
  39051. }
  39052. }
  39053. /**
  39054. * An instance of `AnimationAction` schedules the playback of an animation which is
  39055. * stored in {@link AnimationClip}.
  39056. */
  39057. class AnimationAction {
  39058. /**
  39059. * Constructs a new animation action.
  39060. *
  39061. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  39062. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  39063. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  39064. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39065. */
  39066. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  39067. this._mixer = mixer;
  39068. this._clip = clip;
  39069. this._localRoot = localRoot;
  39070. /**
  39071. * Defines how the animation is blended/combined when two or more animations
  39072. * are simultaneously played.
  39073. *
  39074. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  39075. */
  39076. this.blendMode = blendMode;
  39077. const tracks = clip.tracks,
  39078. nTracks = tracks.length,
  39079. interpolants = new Array( nTracks );
  39080. const interpolantSettings = {
  39081. endingStart: ZeroCurvatureEnding,
  39082. endingEnd: ZeroCurvatureEnding
  39083. };
  39084. for ( let i = 0; i !== nTracks; ++ i ) {
  39085. const interpolant = tracks[ i ].createInterpolant( null );
  39086. interpolants[ i ] = interpolant;
  39087. interpolant.settings = interpolantSettings;
  39088. }
  39089. this._interpolantSettings = interpolantSettings;
  39090. this._interpolants = interpolants; // bound by the mixer
  39091. // inside: PropertyMixer (managed by the mixer)
  39092. this._propertyBindings = new Array( nTracks );
  39093. this._cacheIndex = null; // for the memory manager
  39094. this._byClipCacheIndex = null; // for the memory manager
  39095. this._timeScaleInterpolant = null;
  39096. this._restoreTimeScale = null;
  39097. this._weightInterpolant = null;
  39098. /**
  39099. * The loop mode, set via {@link AnimationAction#setLoop}.
  39100. *
  39101. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  39102. * @default LoopRepeat
  39103. */
  39104. this.loop = LoopRepeat;
  39105. this._loopCount = -1;
  39106. // global mixer time when the action is to be started
  39107. // it's set back to 'null' upon start of the action
  39108. this._startTime = null;
  39109. /**
  39110. * The local time of this action (in seconds, starting with `0`).
  39111. *
  39112. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  39113. * loop state).
  39114. *
  39115. * @type {number}
  39116. * @default Infinity
  39117. */
  39118. this.time = 0;
  39119. /**
  39120. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  39121. * animation to pause. Negative values cause the animation to play backwards.
  39122. *
  39123. * @type {number}
  39124. * @default 1
  39125. */
  39126. this.timeScale = 1;
  39127. this._effectiveTimeScale = 1;
  39128. /**
  39129. * The degree of influence of this action (in the interval `[0, 1]`). Values
  39130. * between `0` (no impact) and `1` (full impact) can be used to blend between
  39131. * several actions.
  39132. *
  39133. * @type {number}
  39134. * @default 1
  39135. */
  39136. this.weight = 1;
  39137. this._effectiveWeight = 1;
  39138. /**
  39139. * The number of repetitions of the performed clip over the course of this action.
  39140. * Can be set via {@link AnimationAction#setLoop}.
  39141. *
  39142. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  39143. * `THREE:LoopOnce`.
  39144. *
  39145. * @type {number}
  39146. * @default Infinity
  39147. */
  39148. this.repetitions = Infinity;
  39149. /**
  39150. * If set to `true`, the playback of the action is paused.
  39151. *
  39152. * @type {boolean}
  39153. * @default false
  39154. */
  39155. this.paused = false;
  39156. /**
  39157. * If set to `false`, the action is disabled so it has no impact.
  39158. *
  39159. * When the action is re-enabled, the animation continues from its current
  39160. * time (setting `enabled` to `false` doesn't reset the action).
  39161. *
  39162. * @type {boolean}
  39163. * @default true
  39164. */
  39165. this.enabled = true;
  39166. /**
  39167. * If set to true the animation will automatically be paused on its last frame.
  39168. *
  39169. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  39170. * to `false` when the last loop of the action has finished, so that this action has
  39171. * no further impact.
  39172. *
  39173. * Note: This member has no impact if the action is interrupted (it
  39174. * has only an effect if its last loop has really finished).
  39175. *
  39176. * @type {boolean}
  39177. * @default false
  39178. */
  39179. this.clampWhenFinished = false;
  39180. /**
  39181. * Enables smooth interpolation without separate clips for start, loop and end.
  39182. *
  39183. * @type {boolean}
  39184. * @default true
  39185. */
  39186. this.zeroSlopeAtStart = true;
  39187. /**
  39188. * Enables smooth interpolation without separate clips for start, loop and end.
  39189. *
  39190. * @type {boolean}
  39191. * @default true
  39192. */
  39193. this.zeroSlopeAtEnd = true;
  39194. }
  39195. /**
  39196. * Starts the playback of the animation.
  39197. *
  39198. * @return {AnimationAction} A reference to this animation action.
  39199. */
  39200. play() {
  39201. this._mixer._activateAction( this );
  39202. return this;
  39203. }
  39204. /**
  39205. * Stops the playback of the animation.
  39206. *
  39207. * @return {AnimationAction} A reference to this animation action.
  39208. */
  39209. stop() {
  39210. this._mixer._deactivateAction( this );
  39211. return this.reset();
  39212. }
  39213. /**
  39214. * Resets the playback of the animation.
  39215. *
  39216. * @return {AnimationAction} A reference to this animation action.
  39217. */
  39218. reset() {
  39219. this.paused = false;
  39220. this.enabled = true;
  39221. this.time = 0; // restart clip
  39222. this._loopCount = -1;// forget previous loops
  39223. this._startTime = null;// forget scheduling
  39224. return this.stopFading().stopWarping();
  39225. }
  39226. /**
  39227. * Returns `true` if the animation is running.
  39228. *
  39229. * @return {boolean} Whether the animation is running or not.
  39230. */
  39231. isRunning() {
  39232. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  39233. this._startTime === null && this._mixer._isActiveAction( this );
  39234. }
  39235. /**
  39236. * Returns `true` when {@link AnimationAction#play} has been called.
  39237. *
  39238. * @return {boolean} Whether the animation is scheduled or not.
  39239. */
  39240. isScheduled() {
  39241. return this._mixer._isActiveAction( this );
  39242. }
  39243. /**
  39244. * Defines the time when the animation should start.
  39245. *
  39246. * @param {number} time - The start time in seconds.
  39247. * @return {AnimationAction} A reference to this animation action.
  39248. */
  39249. startAt( time ) {
  39250. this._startTime = time;
  39251. return this;
  39252. }
  39253. /**
  39254. * Configures the loop settings for this action.
  39255. *
  39256. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  39257. * @param {number} repetitions - The number of repetitions.
  39258. * @return {AnimationAction} A reference to this animation action.
  39259. */
  39260. setLoop( mode, repetitions ) {
  39261. this.loop = mode;
  39262. this.repetitions = repetitions;
  39263. return this;
  39264. }
  39265. /**
  39266. * Sets the effective weight of this action.
  39267. *
  39268. * An action has no effect and thus an effective weight of zero when the
  39269. * action is disabled.
  39270. *
  39271. * @param {number} weight - The weight to set.
  39272. * @return {AnimationAction} A reference to this animation action.
  39273. */
  39274. setEffectiveWeight( weight ) {
  39275. this.weight = weight;
  39276. // note: same logic as when updated at runtime
  39277. this._effectiveWeight = this.enabled ? weight : 0;
  39278. return this.stopFading();
  39279. }
  39280. /**
  39281. * Returns the effective weight of this action.
  39282. *
  39283. * @return {number} The effective weight.
  39284. */
  39285. getEffectiveWeight() {
  39286. return this._effectiveWeight;
  39287. }
  39288. /**
  39289. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  39290. * within the passed time interval.
  39291. *
  39292. * @param {number} duration - The duration of the fade.
  39293. * @return {AnimationAction} A reference to this animation action.
  39294. */
  39295. fadeIn( duration ) {
  39296. return this._scheduleFading( duration, 0, 1 );
  39297. }
  39298. /**
  39299. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  39300. * within the passed time interval.
  39301. *
  39302. * @param {number} duration - The duration of the fade.
  39303. * @return {AnimationAction} A reference to this animation action.
  39304. */
  39305. fadeOut( duration ) {
  39306. return this._scheduleFading( duration, 1, 0 );
  39307. }
  39308. /**
  39309. * Causes this action to fade in and the given action to fade out,
  39310. * within the passed time interval.
  39311. *
  39312. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  39313. * @param {number} duration - The duration of the fade.
  39314. * @param {boolean} [warp=false] - Whether warping should be used or not.
  39315. * @return {AnimationAction} A reference to this animation action.
  39316. */
  39317. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  39318. fadeOutAction.fadeOut( duration );
  39319. this.fadeIn( duration );
  39320. if ( warp === true ) {
  39321. const fadeInDuration = this._clip.duration,
  39322. fadeOutDuration = fadeOutAction._clip.duration,
  39323. startEndRatio = fadeOutDuration / fadeInDuration,
  39324. endStartRatio = fadeInDuration / fadeOutDuration;
  39325. fadeOutAction._restoreTimeScale = fadeOutAction.timeScale;
  39326. this._restoreTimeScale = this.timeScale;
  39327. fadeOutAction.warp( 1.0, startEndRatio, duration );
  39328. this.warp( endStartRatio, 1.0, duration );
  39329. }
  39330. return this;
  39331. }
  39332. /**
  39333. * Causes this action to fade out and the given action to fade in,
  39334. * within the passed time interval.
  39335. *
  39336. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  39337. * @param {number} duration - The duration of the fade.
  39338. * @param {boolean} [warp=false] - Whether warping should be used or not.
  39339. * @return {AnimationAction} A reference to this animation action.
  39340. */
  39341. crossFadeTo( fadeInAction, duration, warp = false ) {
  39342. return fadeInAction.crossFadeFrom( this, duration, warp );
  39343. }
  39344. /**
  39345. * Stops any fading which is applied to this action.
  39346. *
  39347. * @return {AnimationAction} A reference to this animation action.
  39348. */
  39349. stopFading() {
  39350. const weightInterpolant = this._weightInterpolant;
  39351. if ( weightInterpolant !== null ) {
  39352. this._weightInterpolant = null;
  39353. this._mixer._takeBackControlInterpolant( weightInterpolant );
  39354. }
  39355. return this;
  39356. }
  39357. /**
  39358. * Sets the effective time scale of this action.
  39359. *
  39360. * An action has no effect and thus an effective time scale of zero when the
  39361. * action is paused.
  39362. *
  39363. * @param {number} timeScale - The time scale to set.
  39364. * @return {AnimationAction} A reference to this animation action.
  39365. */
  39366. setEffectiveTimeScale( timeScale ) {
  39367. this.timeScale = timeScale;
  39368. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  39369. return this.stopWarping();
  39370. }
  39371. /**
  39372. * Returns the effective time scale of this action.
  39373. *
  39374. * @return {number} The effective time scale.
  39375. */
  39376. getEffectiveTimeScale() {
  39377. return this._effectiveTimeScale;
  39378. }
  39379. /**
  39380. * Sets the duration for a single loop of this action.
  39381. *
  39382. * @param {number} duration - The duration to set.
  39383. * @return {AnimationAction} A reference to this animation action.
  39384. */
  39385. setDuration( duration ) {
  39386. this.timeScale = this._clip.duration / duration;
  39387. return this.stopWarping();
  39388. }
  39389. /**
  39390. * Synchronizes this action with the passed other action.
  39391. *
  39392. * @param {AnimationAction} action - The action to sync with.
  39393. * @return {AnimationAction} A reference to this animation action.
  39394. */
  39395. syncWith( action ) {
  39396. this.time = action.time;
  39397. this.timeScale = action.timeScale;
  39398. return this.stopWarping();
  39399. }
  39400. /**
  39401. * Decelerates this animation's speed to `0` within the passed time interval.
  39402. *
  39403. * @param {number} duration - The duration.
  39404. * @return {AnimationAction} A reference to this animation action.
  39405. */
  39406. halt( duration ) {
  39407. return this.warp( this._effectiveTimeScale, 0, duration );
  39408. }
  39409. /**
  39410. * Changes the playback speed, within the passed time interval, by modifying
  39411. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  39412. * `endTimeScale`.
  39413. *
  39414. * @param {number} startTimeScale - The start time scale.
  39415. * @param {number} endTimeScale - The end time scale.
  39416. * @param {number} duration - The duration.
  39417. * @return {AnimationAction} A reference to this animation action.
  39418. */
  39419. warp( startTimeScale, endTimeScale, duration ) {
  39420. const mixer = this._mixer,
  39421. now = mixer.time,
  39422. timeScale = this.timeScale;
  39423. let interpolant = this._timeScaleInterpolant;
  39424. if ( interpolant === null ) {
  39425. interpolant = mixer._lendControlInterpolant();
  39426. this._timeScaleInterpolant = interpolant;
  39427. }
  39428. const times = interpolant.parameterPositions,
  39429. values = interpolant.sampleValues;
  39430. times[ 0 ] = now;
  39431. times[ 1 ] = now + duration;
  39432. values[ 0 ] = startTimeScale / timeScale;
  39433. values[ 1 ] = endTimeScale / timeScale;
  39434. return this;
  39435. }
  39436. /**
  39437. * Stops any scheduled warping which is applied to this action.
  39438. *
  39439. * @return {AnimationAction} A reference to this animation action.
  39440. */
  39441. stopWarping() {
  39442. const timeScaleInterpolant = this._timeScaleInterpolant;
  39443. if ( timeScaleInterpolant !== null ) {
  39444. this._timeScaleInterpolant = null;
  39445. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  39446. }
  39447. this._restoreTimeScale = null;
  39448. return this;
  39449. }
  39450. /**
  39451. * Returns the animation mixer of this animation action.
  39452. *
  39453. * @return {AnimationMixer} The animation mixer.
  39454. */
  39455. getMixer() {
  39456. return this._mixer;
  39457. }
  39458. /**
  39459. * Returns the animation clip of this animation action.
  39460. *
  39461. * @return {AnimationClip} The animation clip.
  39462. */
  39463. getClip() {
  39464. return this._clip;
  39465. }
  39466. /**
  39467. * Returns the root object of this animation action.
  39468. *
  39469. * @return {Object3D} The root object.
  39470. */
  39471. getRoot() {
  39472. return this._localRoot || this._mixer._root;
  39473. }
  39474. // Internal
  39475. _update( time, deltaTime, timeDirection, accuIndex ) {
  39476. // called by the mixer
  39477. if ( ! this.enabled ) {
  39478. // call ._updateWeight() to update ._effectiveWeight
  39479. this._updateWeight( time );
  39480. return;
  39481. }
  39482. const startTime = this._startTime;
  39483. if ( startTime !== null ) {
  39484. // check for scheduled start of action
  39485. const timeRunning = ( time - startTime ) * timeDirection;
  39486. if ( timeRunning < 0 || timeDirection === 0 ) {
  39487. deltaTime = 0;
  39488. } else {
  39489. this._startTime = null; // unschedule
  39490. deltaTime = timeDirection * timeRunning;
  39491. }
  39492. }
  39493. // apply time scale and advance time
  39494. deltaTime *= this._updateTimeScale( time );
  39495. const clipTime = this._updateTime( deltaTime );
  39496. // note: _updateTime may disable the action resulting in
  39497. // an effective weight of 0
  39498. const weight = this._updateWeight( time );
  39499. if ( weight > 0 ) {
  39500. const interpolants = this._interpolants;
  39501. const propertyMixers = this._propertyBindings;
  39502. switch ( this.blendMode ) {
  39503. case AdditiveAnimationBlendMode:
  39504. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39505. interpolants[ j ].evaluate( clipTime );
  39506. propertyMixers[ j ].accumulateAdditive( weight );
  39507. }
  39508. break;
  39509. case NormalAnimationBlendMode:
  39510. default:
  39511. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39512. interpolants[ j ].evaluate( clipTime );
  39513. propertyMixers[ j ].accumulate( accuIndex, weight );
  39514. }
  39515. }
  39516. }
  39517. }
  39518. _updateWeight( time ) {
  39519. let weight = 0;
  39520. if ( this.enabled ) {
  39521. weight = this.weight;
  39522. const interpolant = this._weightInterpolant;
  39523. if ( interpolant !== null ) {
  39524. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39525. weight *= interpolantValue;
  39526. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39527. this.stopFading();
  39528. if ( interpolantValue === 0 ) {
  39529. // faded out, disable
  39530. this.enabled = false;
  39531. }
  39532. }
  39533. }
  39534. }
  39535. this._effectiveWeight = weight;
  39536. return weight;
  39537. }
  39538. _updateTimeScale( time ) {
  39539. let timeScale = 0;
  39540. if ( ! this.paused ) {
  39541. timeScale = this.timeScale;
  39542. const interpolant = this._timeScaleInterpolant;
  39543. if ( interpolant !== null ) {
  39544. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39545. timeScale *= interpolantValue;
  39546. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39547. if ( timeScale === 0 ) {
  39548. // motion has halted, pause
  39549. this.paused = true;
  39550. } else {
  39551. if ( this._restoreTimeScale !== null ) {
  39552. timeScale = this._restoreTimeScale;
  39553. }
  39554. // warp done - apply final time scale
  39555. this.timeScale = timeScale;
  39556. }
  39557. this.stopWarping();
  39558. }
  39559. }
  39560. }
  39561. this._effectiveTimeScale = timeScale;
  39562. return timeScale;
  39563. }
  39564. _updateTime( deltaTime ) {
  39565. const duration = this._clip.duration;
  39566. const loop = this.loop;
  39567. let time = this.time + deltaTime;
  39568. let loopCount = this._loopCount;
  39569. const pingPong = ( loop === LoopPingPong );
  39570. if ( deltaTime === 0 ) {
  39571. if ( loopCount === -1 ) return time;
  39572. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  39573. }
  39574. if ( loop === LoopOnce ) {
  39575. if ( loopCount === -1 ) {
  39576. // just started
  39577. this._loopCount = 0;
  39578. this._setEndings( true, true, false );
  39579. }
  39580. handle_stop: {
  39581. if ( time >= duration ) {
  39582. time = duration;
  39583. } else if ( time < 0 ) {
  39584. time = 0;
  39585. } else {
  39586. this.time = time;
  39587. break handle_stop;
  39588. }
  39589. if ( this.clampWhenFinished ) this.paused = true;
  39590. else this.enabled = false;
  39591. this.time = time;
  39592. this._mixer.dispatchEvent( {
  39593. type: 'finished', action: this,
  39594. direction: deltaTime < 0 ? -1 : 1
  39595. } );
  39596. }
  39597. } else { // repetitive Repeat or PingPong
  39598. if ( loopCount === -1 ) {
  39599. // just started
  39600. if ( deltaTime >= 0 ) {
  39601. loopCount = 0;
  39602. this._setEndings( true, this.repetitions === 0, pingPong );
  39603. } else {
  39604. // when looping in reverse direction, the initial
  39605. // transition through zero counts as a repetition,
  39606. // so leave loopCount at -1
  39607. this._setEndings( this.repetitions === 0, true, pingPong );
  39608. }
  39609. }
  39610. if ( time >= duration || time < 0 ) {
  39611. // wrap around
  39612. const loopDelta = Math.floor( time / duration ); // signed
  39613. time -= duration * loopDelta;
  39614. loopCount += Math.abs( loopDelta );
  39615. const pending = this.repetitions - loopCount;
  39616. if ( pending <= 0 ) {
  39617. // have to stop (switch state, clamp time, fire event)
  39618. if ( this.clampWhenFinished ) this.paused = true;
  39619. else this.enabled = false;
  39620. time = deltaTime > 0 ? duration : 0;
  39621. this.time = time;
  39622. this._mixer.dispatchEvent( {
  39623. type: 'finished', action: this,
  39624. direction: deltaTime > 0 ? 1 : -1
  39625. } );
  39626. } else {
  39627. // keep running
  39628. if ( pending === 1 ) {
  39629. // entering the last round
  39630. const atStart = deltaTime < 0;
  39631. this._setEndings( atStart, ! atStart, pingPong );
  39632. } else {
  39633. this._setEndings( false, false, pingPong );
  39634. }
  39635. this._loopCount = loopCount;
  39636. this.time = time;
  39637. this._mixer.dispatchEvent( {
  39638. type: 'loop', action: this, loopDelta: loopDelta
  39639. } );
  39640. }
  39641. } else {
  39642. this._loopCount = loopCount;
  39643. this.time = time;
  39644. }
  39645. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39646. // invert time for the "pong round"
  39647. return duration - time;
  39648. }
  39649. }
  39650. return time;
  39651. }
  39652. _setEndings( atStart, atEnd, pingPong ) {
  39653. const settings = this._interpolantSettings;
  39654. if ( pingPong ) {
  39655. settings.endingStart = ZeroSlopeEnding;
  39656. settings.endingEnd = ZeroSlopeEnding;
  39657. } else {
  39658. // assuming for LoopOnce atStart == atEnd == true
  39659. if ( atStart ) {
  39660. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39661. } else {
  39662. settings.endingStart = WrapAroundEnding;
  39663. }
  39664. if ( atEnd ) {
  39665. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39666. } else {
  39667. settings.endingEnd = WrapAroundEnding;
  39668. }
  39669. }
  39670. }
  39671. _scheduleFading( duration, weightNow, weightThen ) {
  39672. const mixer = this._mixer, now = mixer.time;
  39673. let interpolant = this._weightInterpolant;
  39674. if ( interpolant === null ) {
  39675. interpolant = mixer._lendControlInterpolant();
  39676. this._weightInterpolant = interpolant;
  39677. }
  39678. const times = interpolant.parameterPositions,
  39679. values = interpolant.sampleValues;
  39680. times[ 0 ] = now;
  39681. values[ 0 ] = weightNow;
  39682. times[ 1 ] = now + duration;
  39683. values[ 1 ] = weightThen;
  39684. return this;
  39685. }
  39686. }
  39687. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39688. /**
  39689. * `AnimationMixer` is a player for animations on a particular object in
  39690. * the scene. When multiple objects in the scene are animated independently,
  39691. * one `AnimationMixer` may be used for each object.
  39692. */
  39693. class AnimationMixer extends EventDispatcher {
  39694. /**
  39695. * Constructs a new animation mixer.
  39696. *
  39697. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39698. */
  39699. constructor( root ) {
  39700. super();
  39701. this._root = root;
  39702. this._initMemoryManager();
  39703. this._accuIndex = 0;
  39704. /**
  39705. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39706. *
  39707. * @type {number}
  39708. * @default 0
  39709. */
  39710. this.time = 0;
  39711. /**
  39712. * A scaling factor for the global time.
  39713. *
  39714. * Note: Setting this member to `0` and later back to `1` is a
  39715. * possibility to pause/unpause all actions that are controlled by this
  39716. * mixer.
  39717. *
  39718. * @type {number}
  39719. * @default 1
  39720. */
  39721. this.timeScale = 1.0;
  39722. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39723. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39724. }
  39725. }
  39726. _bindAction( action, prototypeAction ) {
  39727. const root = action._localRoot || this._root,
  39728. tracks = action._clip.tracks,
  39729. nTracks = tracks.length,
  39730. bindings = action._propertyBindings,
  39731. interpolants = action._interpolants,
  39732. rootUuid = root.uuid,
  39733. bindingsByRoot = this._bindingsByRootAndName;
  39734. let bindingsByName = bindingsByRoot[ rootUuid ];
  39735. if ( bindingsByName === undefined ) {
  39736. bindingsByName = {};
  39737. bindingsByRoot[ rootUuid ] = bindingsByName;
  39738. }
  39739. for ( let i = 0; i !== nTracks; ++ i ) {
  39740. const track = tracks[ i ],
  39741. trackName = track.name;
  39742. let binding = bindingsByName[ trackName ];
  39743. if ( binding !== undefined ) {
  39744. ++ binding.referenceCount;
  39745. bindings[ i ] = binding;
  39746. } else {
  39747. binding = bindings[ i ];
  39748. if ( binding !== undefined ) {
  39749. // existing binding, make sure the cache knows
  39750. if ( binding._cacheIndex === null ) {
  39751. ++ binding.referenceCount;
  39752. this._addInactiveBinding( binding, rootUuid, trackName );
  39753. }
  39754. continue;
  39755. }
  39756. const path = prototypeAction && prototypeAction.
  39757. _propertyBindings[ i ].binding.parsedPath;
  39758. binding = new PropertyMixer(
  39759. PropertyBinding.create( root, trackName, path ),
  39760. track.ValueTypeName, track.getValueSize() );
  39761. ++ binding.referenceCount;
  39762. this._addInactiveBinding( binding, rootUuid, trackName );
  39763. bindings[ i ] = binding;
  39764. }
  39765. interpolants[ i ].resultBuffer = binding.buffer;
  39766. }
  39767. }
  39768. _activateAction( action ) {
  39769. if ( ! this._isActiveAction( action ) ) {
  39770. if ( action._cacheIndex === null ) {
  39771. // this action has been forgotten by the cache, but the user
  39772. // appears to be still using it -> rebind
  39773. const rootUuid = ( action._localRoot || this._root ).uuid,
  39774. clipUuid = action._clip.uuid,
  39775. actionsForClip = this._actionsByClip[ clipUuid ];
  39776. this._bindAction( action,
  39777. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39778. this._addInactiveAction( action, clipUuid, rootUuid );
  39779. }
  39780. const bindings = action._propertyBindings;
  39781. // increment reference counts / sort out state
  39782. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39783. const binding = bindings[ i ];
  39784. if ( binding.useCount ++ === 0 ) {
  39785. this._lendBinding( binding );
  39786. binding.saveOriginalState();
  39787. }
  39788. }
  39789. this._lendAction( action );
  39790. }
  39791. }
  39792. _deactivateAction( action ) {
  39793. if ( this._isActiveAction( action ) ) {
  39794. const bindings = action._propertyBindings;
  39795. // decrement reference counts / sort out state
  39796. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39797. const binding = bindings[ i ];
  39798. if ( -- binding.useCount === 0 ) {
  39799. binding.restoreOriginalState();
  39800. this._takeBackBinding( binding );
  39801. }
  39802. }
  39803. this._takeBackAction( action );
  39804. }
  39805. }
  39806. // Memory manager
  39807. _initMemoryManager() {
  39808. this._actions = []; // 'nActiveActions' followed by inactive ones
  39809. this._nActiveActions = 0;
  39810. this._actionsByClip = {};
  39811. // inside:
  39812. // {
  39813. // knownActions: Array< AnimationAction > - used as prototypes
  39814. // actionByRoot: AnimationAction - lookup
  39815. // }
  39816. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39817. this._nActiveBindings = 0;
  39818. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39819. this._controlInterpolants = []; // same game as above
  39820. this._nActiveControlInterpolants = 0;
  39821. const scope = this;
  39822. this.stats = {
  39823. actions: {
  39824. get total() {
  39825. return scope._actions.length;
  39826. },
  39827. get inUse() {
  39828. return scope._nActiveActions;
  39829. }
  39830. },
  39831. bindings: {
  39832. get total() {
  39833. return scope._bindings.length;
  39834. },
  39835. get inUse() {
  39836. return scope._nActiveBindings;
  39837. }
  39838. },
  39839. controlInterpolants: {
  39840. get total() {
  39841. return scope._controlInterpolants.length;
  39842. },
  39843. get inUse() {
  39844. return scope._nActiveControlInterpolants;
  39845. }
  39846. }
  39847. };
  39848. }
  39849. // Memory management for AnimationAction objects
  39850. _isActiveAction( action ) {
  39851. const index = action._cacheIndex;
  39852. return index !== null && index < this._nActiveActions;
  39853. }
  39854. _addInactiveAction( action, clipUuid, rootUuid ) {
  39855. const actions = this._actions,
  39856. actionsByClip = this._actionsByClip;
  39857. let actionsForClip = actionsByClip[ clipUuid ];
  39858. if ( actionsForClip === undefined ) {
  39859. actionsForClip = {
  39860. knownActions: [ action ],
  39861. actionByRoot: {}
  39862. };
  39863. action._byClipCacheIndex = 0;
  39864. actionsByClip[ clipUuid ] = actionsForClip;
  39865. } else {
  39866. const knownActions = actionsForClip.knownActions;
  39867. action._byClipCacheIndex = knownActions.length;
  39868. knownActions.push( action );
  39869. }
  39870. action._cacheIndex = actions.length;
  39871. actions.push( action );
  39872. actionsForClip.actionByRoot[ rootUuid ] = action;
  39873. }
  39874. _removeInactiveAction( action ) {
  39875. const actions = this._actions,
  39876. lastInactiveAction = actions[ actions.length - 1 ],
  39877. cacheIndex = action._cacheIndex;
  39878. lastInactiveAction._cacheIndex = cacheIndex;
  39879. actions[ cacheIndex ] = lastInactiveAction;
  39880. actions.pop();
  39881. action._cacheIndex = null;
  39882. const clipUuid = action._clip.uuid,
  39883. actionsByClip = this._actionsByClip,
  39884. actionsForClip = actionsByClip[ clipUuid ],
  39885. knownActionsForClip = actionsForClip.knownActions,
  39886. lastKnownAction =
  39887. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39888. byClipCacheIndex = action._byClipCacheIndex;
  39889. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39890. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39891. knownActionsForClip.pop();
  39892. action._byClipCacheIndex = null;
  39893. const actionByRoot = actionsForClip.actionByRoot,
  39894. rootUuid = ( action._localRoot || this._root ).uuid;
  39895. delete actionByRoot[ rootUuid ];
  39896. if ( knownActionsForClip.length === 0 ) {
  39897. delete actionsByClip[ clipUuid ];
  39898. }
  39899. this._removeInactiveBindingsForAction( action );
  39900. }
  39901. _removeInactiveBindingsForAction( action ) {
  39902. const bindings = action._propertyBindings;
  39903. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39904. const binding = bindings[ i ];
  39905. if ( -- binding.referenceCount === 0 ) {
  39906. this._removeInactiveBinding( binding );
  39907. }
  39908. }
  39909. }
  39910. _lendAction( action ) {
  39911. // [ active actions | inactive actions ]
  39912. // [ active actions >| inactive actions ]
  39913. // s a
  39914. // <-swap->
  39915. // a s
  39916. const actions = this._actions,
  39917. prevIndex = action._cacheIndex,
  39918. lastActiveIndex = this._nActiveActions ++,
  39919. firstInactiveAction = actions[ lastActiveIndex ];
  39920. action._cacheIndex = lastActiveIndex;
  39921. actions[ lastActiveIndex ] = action;
  39922. firstInactiveAction._cacheIndex = prevIndex;
  39923. actions[ prevIndex ] = firstInactiveAction;
  39924. }
  39925. _takeBackAction( action ) {
  39926. // [ active actions | inactive actions ]
  39927. // [ active actions |< inactive actions ]
  39928. // a s
  39929. // <-swap->
  39930. // s a
  39931. const actions = this._actions,
  39932. prevIndex = action._cacheIndex,
  39933. firstInactiveIndex = -- this._nActiveActions,
  39934. lastActiveAction = actions[ firstInactiveIndex ];
  39935. action._cacheIndex = firstInactiveIndex;
  39936. actions[ firstInactiveIndex ] = action;
  39937. lastActiveAction._cacheIndex = prevIndex;
  39938. actions[ prevIndex ] = lastActiveAction;
  39939. }
  39940. // Memory management for PropertyMixer objects
  39941. _addInactiveBinding( binding, rootUuid, trackName ) {
  39942. const bindingsByRoot = this._bindingsByRootAndName,
  39943. bindings = this._bindings;
  39944. let bindingByName = bindingsByRoot[ rootUuid ];
  39945. if ( bindingByName === undefined ) {
  39946. bindingByName = {};
  39947. bindingsByRoot[ rootUuid ] = bindingByName;
  39948. }
  39949. bindingByName[ trackName ] = binding;
  39950. binding._cacheIndex = bindings.length;
  39951. bindings.push( binding );
  39952. }
  39953. _removeInactiveBinding( binding ) {
  39954. const bindings = this._bindings,
  39955. propBinding = binding.binding,
  39956. rootUuid = propBinding.rootNode.uuid,
  39957. trackName = propBinding.path,
  39958. bindingsByRoot = this._bindingsByRootAndName,
  39959. bindingByName = bindingsByRoot[ rootUuid ],
  39960. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39961. cacheIndex = binding._cacheIndex;
  39962. lastInactiveBinding._cacheIndex = cacheIndex;
  39963. bindings[ cacheIndex ] = lastInactiveBinding;
  39964. bindings.pop();
  39965. delete bindingByName[ trackName ];
  39966. if ( Object.keys( bindingByName ).length === 0 ) {
  39967. delete bindingsByRoot[ rootUuid ];
  39968. }
  39969. }
  39970. _lendBinding( binding ) {
  39971. const bindings = this._bindings,
  39972. prevIndex = binding._cacheIndex,
  39973. lastActiveIndex = this._nActiveBindings ++,
  39974. firstInactiveBinding = bindings[ lastActiveIndex ];
  39975. binding._cacheIndex = lastActiveIndex;
  39976. bindings[ lastActiveIndex ] = binding;
  39977. firstInactiveBinding._cacheIndex = prevIndex;
  39978. bindings[ prevIndex ] = firstInactiveBinding;
  39979. }
  39980. _takeBackBinding( binding ) {
  39981. const bindings = this._bindings,
  39982. prevIndex = binding._cacheIndex,
  39983. firstInactiveIndex = -- this._nActiveBindings,
  39984. lastActiveBinding = bindings[ firstInactiveIndex ];
  39985. binding._cacheIndex = firstInactiveIndex;
  39986. bindings[ firstInactiveIndex ] = binding;
  39987. lastActiveBinding._cacheIndex = prevIndex;
  39988. bindings[ prevIndex ] = lastActiveBinding;
  39989. }
  39990. // Memory management of Interpolants for weight and time scale
  39991. _lendControlInterpolant() {
  39992. const interpolants = this._controlInterpolants,
  39993. lastActiveIndex = this._nActiveControlInterpolants ++;
  39994. let interpolant = interpolants[ lastActiveIndex ];
  39995. if ( interpolant === undefined ) {
  39996. interpolant = new LinearInterpolant(
  39997. new Float32Array( 2 ), new Float32Array( 2 ),
  39998. 1, _controlInterpolantsResultBuffer );
  39999. interpolant.__cacheIndex = lastActiveIndex;
  40000. interpolants[ lastActiveIndex ] = interpolant;
  40001. }
  40002. return interpolant;
  40003. }
  40004. _takeBackControlInterpolant( interpolant ) {
  40005. const interpolants = this._controlInterpolants,
  40006. prevIndex = interpolant.__cacheIndex,
  40007. firstInactiveIndex = -- this._nActiveControlInterpolants,
  40008. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  40009. interpolant.__cacheIndex = firstInactiveIndex;
  40010. interpolants[ firstInactiveIndex ] = interpolant;
  40011. lastActiveInterpolant.__cacheIndex = prevIndex;
  40012. interpolants[ prevIndex ] = lastActiveInterpolant;
  40013. }
  40014. /**
  40015. * Returns an instance of {@link AnimationAction} for the passed clip.
  40016. *
  40017. * If an action fitting the clip and root parameters doesn't yet exist, it
  40018. * will be created by this method. Calling this method several times with the
  40019. * same clip and root parameters always returns the same action.
  40020. *
  40021. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  40022. * @param {Object3D} [optionalRoot] - An alternative root object.
  40023. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  40024. * @return {?AnimationAction} The animation action.
  40025. */
  40026. clipAction( clip, optionalRoot, blendMode ) {
  40027. const root = optionalRoot || this._root,
  40028. rootUuid = root.uuid;
  40029. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  40030. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  40031. const actionsForClip = this._actionsByClip[ clipUuid ];
  40032. let prototypeAction = null;
  40033. if ( blendMode === undefined ) {
  40034. if ( clipObject !== null ) {
  40035. blendMode = clipObject.blendMode;
  40036. } else {
  40037. blendMode = NormalAnimationBlendMode;
  40038. }
  40039. }
  40040. if ( actionsForClip !== undefined ) {
  40041. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  40042. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  40043. return existingAction;
  40044. }
  40045. // we know the clip, so we don't have to parse all
  40046. // the bindings again but can just copy
  40047. prototypeAction = actionsForClip.knownActions[ 0 ];
  40048. // also, take the clip from the prototype action
  40049. if ( clipObject === null )
  40050. clipObject = prototypeAction._clip;
  40051. }
  40052. // clip must be known when specified via string
  40053. if ( clipObject === null ) return null;
  40054. // allocate all resources required to run it
  40055. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  40056. this._bindAction( newAction, prototypeAction );
  40057. // and make the action known to the memory manager
  40058. this._addInactiveAction( newAction, clipUuid, rootUuid );
  40059. return newAction;
  40060. }
  40061. /**
  40062. * Returns an existing animation action for the passed clip.
  40063. *
  40064. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  40065. * @param {Object3D} [optionalRoot] - An alternative root object.
  40066. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  40067. */
  40068. existingAction( clip, optionalRoot ) {
  40069. const root = optionalRoot || this._root,
  40070. rootUuid = root.uuid,
  40071. clipObject = typeof clip === 'string' ?
  40072. AnimationClip.findByName( root, clip ) : clip,
  40073. clipUuid = clipObject ? clipObject.uuid : clip,
  40074. actionsForClip = this._actionsByClip[ clipUuid ];
  40075. if ( actionsForClip !== undefined ) {
  40076. return actionsForClip.actionByRoot[ rootUuid ] || null;
  40077. }
  40078. return null;
  40079. }
  40080. /**
  40081. * Deactivates all previously scheduled actions on this mixer.
  40082. *
  40083. * @return {AnimationMixer} A reference to this animation mixer.
  40084. */
  40085. stopAllAction() {
  40086. const actions = this._actions,
  40087. nActions = this._nActiveActions;
  40088. for ( let i = nActions - 1; i >= 0; -- i ) {
  40089. actions[ i ].stop();
  40090. }
  40091. return this;
  40092. }
  40093. /**
  40094. * Advances the global mixer time and updates the animation.
  40095. *
  40096. * This is usually done in the render loop by passing the delta
  40097. * time from {@link Clock} or {@link Timer}.
  40098. *
  40099. * @param {number} deltaTime - The delta time in seconds.
  40100. * @return {AnimationMixer} A reference to this animation mixer.
  40101. */
  40102. update( deltaTime ) {
  40103. deltaTime *= this.timeScale;
  40104. const actions = this._actions,
  40105. nActions = this._nActiveActions,
  40106. time = this.time += deltaTime,
  40107. timeDirection = Math.sign( deltaTime ),
  40108. accuIndex = this._accuIndex ^= 1;
  40109. // run active actions
  40110. for ( let i = 0; i !== nActions; ++ i ) {
  40111. const action = actions[ i ];
  40112. action._update( time, deltaTime, timeDirection, accuIndex );
  40113. }
  40114. // update scene graph
  40115. const bindings = this._bindings,
  40116. nBindings = this._nActiveBindings;
  40117. for ( let i = 0; i !== nBindings; ++ i ) {
  40118. bindings[ i ].apply( accuIndex );
  40119. }
  40120. return this;
  40121. }
  40122. /**
  40123. * Sets the global mixer to a specific time and updates the animation accordingly.
  40124. *
  40125. * This is useful when you need to jump to an exact time in an animation. The
  40126. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  40127. *
  40128. * @param {number} time - The time to set in seconds.
  40129. * @return {AnimationMixer} A reference to this animation mixer.
  40130. */
  40131. setTime( time ) {
  40132. this.time = 0; // Zero out time attribute for AnimationMixer object;
  40133. for ( let i = 0; i < this._actions.length; i ++ ) {
  40134. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  40135. }
  40136. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  40137. }
  40138. /**
  40139. * Returns this mixer's root object.
  40140. *
  40141. * @return {Object3D} The mixer's root object.
  40142. */
  40143. getRoot() {
  40144. return this._root;
  40145. }
  40146. /**
  40147. * Deallocates all memory resources for a clip. Before using this method make
  40148. * sure to call {@link AnimationAction#stop} for all related actions.
  40149. *
  40150. * @param {AnimationClip} clip - The clip to uncache.
  40151. */
  40152. uncacheClip( clip ) {
  40153. const actions = this._actions,
  40154. clipUuid = clip.uuid,
  40155. actionsByClip = this._actionsByClip,
  40156. actionsForClip = actionsByClip[ clipUuid ];
  40157. if ( actionsForClip !== undefined ) {
  40158. // note: just calling _removeInactiveAction would mess up the
  40159. // iteration state and also require updating the state we can
  40160. // just throw away
  40161. const actionsToRemove = actionsForClip.knownActions;
  40162. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  40163. const action = actionsToRemove[ i ];
  40164. this._deactivateAction( action );
  40165. const cacheIndex = action._cacheIndex,
  40166. lastInactiveAction = actions[ actions.length - 1 ];
  40167. action._cacheIndex = null;
  40168. action._byClipCacheIndex = null;
  40169. lastInactiveAction._cacheIndex = cacheIndex;
  40170. actions[ cacheIndex ] = lastInactiveAction;
  40171. actions.pop();
  40172. this._removeInactiveBindingsForAction( action );
  40173. }
  40174. delete actionsByClip[ clipUuid ];
  40175. }
  40176. }
  40177. /**
  40178. * Deallocates all memory resources for a root object. Before using this
  40179. * method make sure to call {@link AnimationAction#stop} for all related
  40180. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  40181. * mixer operates on a single root.
  40182. *
  40183. * @param {Object3D} root - The root object to uncache.
  40184. */
  40185. uncacheRoot( root ) {
  40186. const rootUuid = root.uuid,
  40187. actionsByClip = this._actionsByClip;
  40188. for ( const clipUuid in actionsByClip ) {
  40189. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  40190. action = actionByRoot[ rootUuid ];
  40191. if ( action !== undefined ) {
  40192. this._deactivateAction( action );
  40193. this._removeInactiveAction( action );
  40194. }
  40195. }
  40196. const bindingsByRoot = this._bindingsByRootAndName,
  40197. bindingByName = bindingsByRoot[ rootUuid ];
  40198. if ( bindingByName !== undefined ) {
  40199. for ( const trackName in bindingByName ) {
  40200. const binding = bindingByName[ trackName ];
  40201. binding.restoreOriginalState();
  40202. this._removeInactiveBinding( binding );
  40203. }
  40204. }
  40205. }
  40206. /**
  40207. * Deallocates all memory resources for an action. The action is identified by the
  40208. * given clip and an optional root object. Before using this method make
  40209. * sure to call {@link AnimationAction#stop} to deactivate the action.
  40210. *
  40211. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  40212. * @param {Object3D} [optionalRoot] - An alternative root object.
  40213. */
  40214. uncacheAction( clip, optionalRoot ) {
  40215. const action = this.existingAction( clip, optionalRoot );
  40216. if ( action !== null ) {
  40217. this._deactivateAction( action );
  40218. this._removeInactiveAction( action );
  40219. }
  40220. }
  40221. }
  40222. /**
  40223. * Represents a 3D render target.
  40224. *
  40225. * @augments RenderTarget
  40226. */
  40227. class RenderTarget3D extends RenderTarget {
  40228. /**
  40229. * Constructs a new 3D render target.
  40230. *
  40231. * @param {number} [width=1] - The width of the render target.
  40232. * @param {number} [height=1] - The height of the render target.
  40233. * @param {number} [depth=1] - The height of the render target.
  40234. * @param {RenderTarget~Options} [options] - The configuration object.
  40235. */
  40236. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  40237. super( width, height, options );
  40238. /**
  40239. * This flag can be used for type testing.
  40240. *
  40241. * @type {boolean}
  40242. * @readonly
  40243. * @default true
  40244. */
  40245. this.isRenderTarget3D = true;
  40246. this.depth = depth;
  40247. /**
  40248. * Overwritten with a different texture type.
  40249. *
  40250. * @type {Data3DTexture}
  40251. */
  40252. this.texture = new Data3DTexture( null, width, height, depth );
  40253. this._setTextureOptions( options );
  40254. this.texture.isRenderTargetTexture = true;
  40255. }
  40256. }
  40257. /**
  40258. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  40259. *
  40260. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  40261. * ```js
  40262. * uniforms: {
  40263. * time: { value: 1.0 },
  40264. * resolution: new Uniform( new Vector2() )
  40265. * };
  40266. * ```
  40267. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  40268. * in {@link WebGLRenderer}.
  40269. */
  40270. class Uniform {
  40271. /**
  40272. * Constructs a new uniform.
  40273. *
  40274. * @param {any} value - The uniform value.
  40275. */
  40276. constructor( value ) {
  40277. /**
  40278. * The uniform value.
  40279. *
  40280. * @type {any}
  40281. */
  40282. this.value = value;
  40283. }
  40284. /**
  40285. * Returns a new uniform with copied values from this instance.
  40286. * If the value has a `clone()` method, the value is cloned as well.
  40287. *
  40288. * @return {Uniform} A clone of this instance.
  40289. */
  40290. clone() {
  40291. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  40292. }
  40293. }
  40294. let _id = 0;
  40295. /**
  40296. * A class for managing multiple uniforms in a single group. The renderer will process
  40297. * such a definition as a single UBO.
  40298. *
  40299. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  40300. * in {@link WebGLRenderer}.
  40301. *
  40302. * @augments EventDispatcher
  40303. */
  40304. class UniformsGroup extends EventDispatcher {
  40305. /**
  40306. * Constructs a new uniforms group.
  40307. */
  40308. constructor() {
  40309. super();
  40310. /**
  40311. * This flag can be used for type testing.
  40312. *
  40313. * @type {boolean}
  40314. * @readonly
  40315. * @default true
  40316. */
  40317. this.isUniformsGroup = true;
  40318. /**
  40319. * The ID of the 3D object.
  40320. *
  40321. * @name UniformsGroup#id
  40322. * @type {number}
  40323. * @readonly
  40324. */
  40325. Object.defineProperty( this, 'id', { value: _id ++ } );
  40326. /**
  40327. * The name of the uniforms group.
  40328. *
  40329. * @type {string}
  40330. */
  40331. this.name = '';
  40332. /**
  40333. * The buffer usage.
  40334. *
  40335. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  40336. * @default StaticDrawUsage
  40337. */
  40338. this.usage = StaticDrawUsage;
  40339. /**
  40340. * An array holding the uniforms.
  40341. *
  40342. * @type {Array<Uniform>}
  40343. */
  40344. this.uniforms = [];
  40345. }
  40346. /**
  40347. * Adds the given uniform to this uniforms group.
  40348. *
  40349. * @param {Uniform} uniform - The uniform to add.
  40350. * @return {UniformsGroup} A reference to this uniforms group.
  40351. */
  40352. add( uniform ) {
  40353. this.uniforms.push( uniform );
  40354. return this;
  40355. }
  40356. /**
  40357. * Removes the given uniform from this uniforms group.
  40358. *
  40359. * @param {Uniform} uniform - The uniform to remove.
  40360. * @return {UniformsGroup} A reference to this uniforms group.
  40361. */
  40362. remove( uniform ) {
  40363. const index = this.uniforms.indexOf( uniform );
  40364. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  40365. return this;
  40366. }
  40367. /**
  40368. * Sets the name of this uniforms group.
  40369. *
  40370. * @param {string} name - The name to set.
  40371. * @return {UniformsGroup} A reference to this uniforms group.
  40372. */
  40373. setName( name ) {
  40374. this.name = name;
  40375. return this;
  40376. }
  40377. /**
  40378. * Sets the usage of this uniforms group.
  40379. *
  40380. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  40381. * @return {UniformsGroup} A reference to this uniforms group.
  40382. */
  40383. setUsage( value ) {
  40384. this.usage = value;
  40385. return this;
  40386. }
  40387. /**
  40388. * Frees the GPU-related resources allocated by this instance. Call this
  40389. * method whenever this instance is no longer used in your app.
  40390. *
  40391. * @fires Texture#dispose
  40392. */
  40393. dispose() {
  40394. this.dispatchEvent( { type: 'dispose' } );
  40395. }
  40396. /**
  40397. * Copies the values of the given uniforms group to this instance.
  40398. *
  40399. * @param {UniformsGroup} source - The uniforms group to copy.
  40400. * @return {UniformsGroup} A reference to this uniforms group.
  40401. */
  40402. copy( source ) {
  40403. this.name = source.name;
  40404. this.usage = source.usage;
  40405. const uniformsSource = source.uniforms;
  40406. this.uniforms.length = 0;
  40407. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  40408. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  40409. for ( let j = 0; j < uniforms.length; j ++ ) {
  40410. this.uniforms.push( uniforms[ j ].clone() );
  40411. }
  40412. }
  40413. return this;
  40414. }
  40415. /**
  40416. * Returns a new uniforms group with copied values from this instance.
  40417. *
  40418. * @return {UniformsGroup} A clone of this instance.
  40419. */
  40420. clone() {
  40421. return new this.constructor().copy( this );
  40422. }
  40423. }
  40424. /**
  40425. * An instanced version of an interleaved buffer.
  40426. *
  40427. * @augments InterleavedBuffer
  40428. */
  40429. class InstancedInterleavedBuffer extends InterleavedBuffer {
  40430. /**
  40431. * Constructs a new instanced interleaved buffer.
  40432. *
  40433. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  40434. * @param {number} stride - The number of typed-array elements per vertex.
  40435. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  40436. */
  40437. constructor( array, stride, meshPerAttribute = 1 ) {
  40438. super( array, stride );
  40439. /**
  40440. * This flag can be used for type testing.
  40441. *
  40442. * @type {boolean}
  40443. * @readonly
  40444. * @default true
  40445. */
  40446. this.isInstancedInterleavedBuffer = true;
  40447. /**
  40448. * Defines how often a value of this buffer attribute should be repeated,
  40449. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  40450. *
  40451. * @type {number}
  40452. * @default 1
  40453. */
  40454. this.meshPerAttribute = meshPerAttribute;
  40455. }
  40456. copy( source ) {
  40457. super.copy( source );
  40458. this.meshPerAttribute = source.meshPerAttribute;
  40459. return this;
  40460. }
  40461. clone( data ) {
  40462. const ib = super.clone( data );
  40463. ib.meshPerAttribute = this.meshPerAttribute;
  40464. return ib;
  40465. }
  40466. toJSON( data ) {
  40467. const json = super.toJSON( data );
  40468. json.isInstancedInterleavedBuffer = true;
  40469. json.meshPerAttribute = this.meshPerAttribute;
  40470. return json;
  40471. }
  40472. }
  40473. /**
  40474. * An alternative version of a buffer attribute with more control over the VBO.
  40475. *
  40476. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  40477. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  40478. *
  40479. * The most common use case for this class is when some kind of GPGPU calculation interferes
  40480. * or even produces the VBOs in question.
  40481. *
  40482. * Notice that this class can only be used with {@link WebGLRenderer}.
  40483. */
  40484. class GLBufferAttribute {
  40485. /**
  40486. * Constructs a new GL buffer attribute.
  40487. *
  40488. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  40489. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40490. * @param {number} itemSize - The item size.
  40491. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40492. * @param {number} count - The expected number of vertices in VBO.
  40493. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  40494. */
  40495. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  40496. /**
  40497. * This flag can be used for type testing.
  40498. *
  40499. * @type {boolean}
  40500. * @readonly
  40501. * @default true
  40502. */
  40503. this.isGLBufferAttribute = true;
  40504. /**
  40505. * The name of the buffer attribute.
  40506. *
  40507. * @type {string}
  40508. */
  40509. this.name = '';
  40510. /**
  40511. * The native WebGL buffer.
  40512. *
  40513. * @type {WebGLBuffer}
  40514. */
  40515. this.buffer = buffer;
  40516. /**
  40517. * The native data type.
  40518. *
  40519. * @type {number}
  40520. */
  40521. this.type = type;
  40522. /**
  40523. * The item size, see {@link BufferAttribute#itemSize}.
  40524. *
  40525. * @type {number}
  40526. */
  40527. this.itemSize = itemSize;
  40528. /**
  40529. * The corresponding size (in bytes) for the given `type` parameter.
  40530. *
  40531. * @type {number}
  40532. */
  40533. this.elementSize = elementSize;
  40534. /**
  40535. * The expected number of vertices in VBO.
  40536. *
  40537. * @type {number}
  40538. */
  40539. this.count = count;
  40540. /**
  40541. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  40542. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  40543. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  40544. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  40545. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  40546. *
  40547. * @type {boolean}
  40548. */
  40549. this.normalized = normalized;
  40550. /**
  40551. * A version number, incremented every time the `needsUpdate` is set to `true`.
  40552. *
  40553. * @type {number}
  40554. */
  40555. this.version = 0;
  40556. }
  40557. /**
  40558. * Flag to indicate that this attribute has changed and should be re-sent to
  40559. * the GPU. Set this to `true` when you modify the value of the array.
  40560. *
  40561. * @type {number}
  40562. * @default false
  40563. * @param {boolean} value
  40564. */
  40565. set needsUpdate( value ) {
  40566. if ( value === true ) this.version ++;
  40567. }
  40568. /**
  40569. * Sets the given native WebGL buffer.
  40570. *
  40571. * @param {WebGLBuffer} buffer - The buffer to set.
  40572. * @return {BufferAttribute} A reference to this instance.
  40573. */
  40574. setBuffer( buffer ) {
  40575. this.buffer = buffer;
  40576. return this;
  40577. }
  40578. /**
  40579. * Sets the given native data type and element size.
  40580. *
  40581. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40582. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40583. * @return {BufferAttribute} A reference to this instance.
  40584. */
  40585. setType( type, elementSize ) {
  40586. this.type = type;
  40587. this.elementSize = elementSize;
  40588. return this;
  40589. }
  40590. /**
  40591. * Sets the item size.
  40592. *
  40593. * @param {number} itemSize - The item size.
  40594. * @return {BufferAttribute} A reference to this instance.
  40595. */
  40596. setItemSize( itemSize ) {
  40597. this.itemSize = itemSize;
  40598. return this;
  40599. }
  40600. /**
  40601. * Sets the count (the expected number of vertices in VBO).
  40602. *
  40603. * @param {number} count - The count.
  40604. * @return {BufferAttribute} A reference to this instance.
  40605. */
  40606. setCount( count ) {
  40607. this.count = count;
  40608. return this;
  40609. }
  40610. }
  40611. const _matrix = /*@__PURE__*/ new Matrix4();
  40612. /**
  40613. * This class is designed to assist with raycasting. Raycasting is used for
  40614. * mouse picking (working out what objects in the 3d space the mouse is over)
  40615. * amongst other things.
  40616. */
  40617. class Raycaster {
  40618. /**
  40619. * Constructs a new raycaster.
  40620. *
  40621. * @param {Vector3} origin - The origin vector where the ray casts from.
  40622. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40623. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40624. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40625. */
  40626. constructor( origin, direction, near = 0, far = Infinity ) {
  40627. /**
  40628. * The ray used for raycasting.
  40629. *
  40630. * @type {Ray}
  40631. */
  40632. this.ray = new Ray( origin, direction );
  40633. /**
  40634. * All results returned are further away than near. Near can't be negative.
  40635. *
  40636. * @type {number}
  40637. * @default 0
  40638. */
  40639. this.near = near;
  40640. /**
  40641. * All results returned are closer than far. Far can't be lower than near.
  40642. *
  40643. * @type {number}
  40644. * @default Infinity
  40645. */
  40646. this.far = far;
  40647. /**
  40648. * The camera to use when raycasting against view-dependent objects such as
  40649. * billboarded objects like sprites. This field can be set manually or
  40650. * is set when calling `setFromCamera()`.
  40651. *
  40652. * @type {?Camera}
  40653. * @default null
  40654. */
  40655. this.camera = null;
  40656. /**
  40657. * Allows to selectively ignore 3D objects when performing intersection tests.
  40658. * The following code example ensures that only 3D objects on layer `1` will be
  40659. * honored by raycaster.
  40660. * ```js
  40661. * raycaster.layers.set( 1 );
  40662. * object.layers.enable( 1 );
  40663. * ```
  40664. *
  40665. * @type {Layers}
  40666. */
  40667. this.layers = new Layers();
  40668. /**
  40669. * A parameter object that configures the raycasting. It has the structure:
  40670. *
  40671. * ```
  40672. * {
  40673. * Mesh: {},
  40674. * Line: { threshold: 1 },
  40675. * LOD: {},
  40676. * Points: { threshold: 1 },
  40677. * Sprite: {}
  40678. * }
  40679. * ```
  40680. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40681. *
  40682. * @type {Object}
  40683. */
  40684. this.params = {
  40685. Mesh: {},
  40686. Line: { threshold: 1 },
  40687. LOD: {},
  40688. Points: { threshold: 1 },
  40689. Sprite: {}
  40690. };
  40691. }
  40692. /**
  40693. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40694. *
  40695. * @param {Vector3} origin - The origin vector where the ray casts from.
  40696. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40697. */
  40698. set( origin, direction ) {
  40699. // direction is assumed to be normalized (for accurate distance calculations)
  40700. this.ray.set( origin, direction );
  40701. }
  40702. /**
  40703. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40704. *
  40705. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40706. * X and Y components should be between `-1` and `1`.
  40707. * @param {Camera} camera - The camera from which the ray should originate.
  40708. */
  40709. setFromCamera( coords, camera ) {
  40710. if ( camera.isPerspectiveCamera ) {
  40711. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40712. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40713. this.camera = camera;
  40714. } else if ( camera.isOrthographicCamera ) {
  40715. this.ray.origin.set( coords.x, coords.y, camera.projectionMatrix.elements[ 14 ] ).unproject( camera ); // set origin in plane of camera
  40716. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40717. this.camera = camera;
  40718. } else {
  40719. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40720. }
  40721. }
  40722. /**
  40723. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40724. *
  40725. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40726. * @return {Raycaster} A reference to this raycaster.
  40727. */
  40728. setFromXRController( controller ) {
  40729. _matrix.identity().extractRotation( controller.matrixWorld );
  40730. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40731. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40732. return this;
  40733. }
  40734. /**
  40735. * The intersection point of a raycaster intersection test.
  40736. * @typedef {Object} Raycaster~Intersection
  40737. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40738. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40739. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40740. * @property {Vector3} point - The intersection point, in world coordinates.
  40741. * @property {Object} face - The face that has been intersected.
  40742. * @property {number} faceIndex - The face index.
  40743. * @property {Object3D} object - The 3D object that has been intersected.
  40744. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40745. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40746. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40747. * @property {number} instanceId - The index number of the instance where the ray
  40748. * intersects the {@link InstancedMesh}.
  40749. */
  40750. /**
  40751. * Checks all intersection between the ray and the object with or without the
  40752. * descendants. Intersections are returned sorted by distance, closest first.
  40753. *
  40754. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40755. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40756. * differently to ray casting than lines or points.
  40757. *
  40758. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40759. * to be detected; intersections of the ray passing through the back of a face will not
  40760. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40761. * to `THREE.DoubleSide`.
  40762. *
  40763. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40764. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40765. * Otherwise it only checks intersection with the object.
  40766. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40767. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40768. */
  40769. intersectObject( object, recursive = true, intersects = [] ) {
  40770. intersect( object, this, intersects, recursive );
  40771. intersects.sort( ascSort );
  40772. return intersects;
  40773. }
  40774. /**
  40775. * Checks all intersection between the ray and the objects with or without
  40776. * the descendants. Intersections are returned sorted by distance, closest first.
  40777. *
  40778. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40779. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40780. * Otherwise it only checks intersection with the object.
  40781. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40782. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40783. */
  40784. intersectObjects( objects, recursive = true, intersects = [] ) {
  40785. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40786. intersect( objects[ i ], this, intersects, recursive );
  40787. }
  40788. intersects.sort( ascSort );
  40789. return intersects;
  40790. }
  40791. }
  40792. function ascSort( a, b ) {
  40793. return a.distance - b.distance;
  40794. }
  40795. function intersect( object, raycaster, intersects, recursive ) {
  40796. let propagate = true;
  40797. if ( object.layers.test( raycaster.layers ) ) {
  40798. const result = object.raycast( raycaster, intersects );
  40799. if ( result === false ) propagate = false;
  40800. }
  40801. if ( propagate === true && recursive === true ) {
  40802. const children = object.children;
  40803. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40804. intersect( children[ i ], raycaster, intersects, true );
  40805. }
  40806. }
  40807. }
  40808. /**
  40809. * Class for keeping track of time.
  40810. *
  40811. * @deprecated since r183.
  40812. */
  40813. class Clock {
  40814. /**
  40815. * Constructs a new clock.
  40816. *
  40817. * @deprecated since 183.
  40818. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  40819. * `getDelta()` is called for the first time.
  40820. */
  40821. constructor( autoStart = true ) {
  40822. /**
  40823. * If set to `true`, the clock starts automatically when `getDelta()` is called
  40824. * for the first time.
  40825. *
  40826. * @type {boolean}
  40827. * @default true
  40828. */
  40829. this.autoStart = autoStart;
  40830. /**
  40831. * Holds the time at which the clock's `start()` method was last called.
  40832. *
  40833. * @type {number}
  40834. * @default 0
  40835. */
  40836. this.startTime = 0;
  40837. /**
  40838. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  40839. * `getDelta()` methods were last called.
  40840. *
  40841. * @type {number}
  40842. * @default 0
  40843. */
  40844. this.oldTime = 0;
  40845. /**
  40846. * Keeps track of the total time that the clock has been running.
  40847. *
  40848. * @type {number}
  40849. * @default 0
  40850. */
  40851. this.elapsedTime = 0;
  40852. /**
  40853. * Whether the clock is running or not.
  40854. *
  40855. * @type {boolean}
  40856. * @default true
  40857. */
  40858. this.running = false;
  40859. warn( 'Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183
  40860. }
  40861. /**
  40862. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  40863. * called by the class.
  40864. */
  40865. start() {
  40866. this.startTime = performance.now();
  40867. this.oldTime = this.startTime;
  40868. this.elapsedTime = 0;
  40869. this.running = true;
  40870. }
  40871. /**
  40872. * Stops the clock.
  40873. */
  40874. stop() {
  40875. this.getElapsedTime();
  40876. this.running = false;
  40877. this.autoStart = false;
  40878. }
  40879. /**
  40880. * Returns the elapsed time in seconds.
  40881. *
  40882. * @return {number} The elapsed time.
  40883. */
  40884. getElapsedTime() {
  40885. this.getDelta();
  40886. return this.elapsedTime;
  40887. }
  40888. /**
  40889. * Returns the delta time in seconds.
  40890. *
  40891. * @return {number} The delta time.
  40892. */
  40893. getDelta() {
  40894. let diff = 0;
  40895. if ( this.autoStart && ! this.running ) {
  40896. this.start();
  40897. return 0;
  40898. }
  40899. if ( this.running ) {
  40900. const newTime = performance.now();
  40901. diff = ( newTime - this.oldTime ) / 1000;
  40902. this.oldTime = newTime;
  40903. this.elapsedTime += diff;
  40904. }
  40905. return diff;
  40906. }
  40907. }
  40908. /**
  40909. * This class can be used to represent points in 3D space as
  40910. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40911. */
  40912. class Spherical {
  40913. /**
  40914. * Constructs a new spherical.
  40915. *
  40916. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40917. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40918. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40919. */
  40920. constructor( radius = 1, phi = 0, theta = 0 ) {
  40921. /**
  40922. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40923. *
  40924. * @type {number}
  40925. * @default 1
  40926. */
  40927. this.radius = radius;
  40928. /**
  40929. * The polar angle in radians from the y (up) axis.
  40930. *
  40931. * @type {number}
  40932. * @default 0
  40933. */
  40934. this.phi = phi;
  40935. /**
  40936. * The equator/azimuthal angle in radians around the y (up) axis.
  40937. *
  40938. * @type {number}
  40939. * @default 0
  40940. */
  40941. this.theta = theta;
  40942. }
  40943. /**
  40944. * Sets the spherical components by copying the given values.
  40945. *
  40946. * @param {number} radius - The radius.
  40947. * @param {number} phi - The polar angle.
  40948. * @param {number} theta - The azimuthal angle.
  40949. * @return {Spherical} A reference to this spherical.
  40950. */
  40951. set( radius, phi, theta ) {
  40952. this.radius = radius;
  40953. this.phi = phi;
  40954. this.theta = theta;
  40955. return this;
  40956. }
  40957. /**
  40958. * Copies the values of the given spherical to this instance.
  40959. *
  40960. * @param {Spherical} other - The spherical to copy.
  40961. * @return {Spherical} A reference to this spherical.
  40962. */
  40963. copy( other ) {
  40964. this.radius = other.radius;
  40965. this.phi = other.phi;
  40966. this.theta = other.theta;
  40967. return this;
  40968. }
  40969. /**
  40970. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40971. * `0.000001`.
  40972. *
  40973. * @return {Spherical} A reference to this spherical.
  40974. */
  40975. makeSafe() {
  40976. const EPS = 0.000001;
  40977. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40978. return this;
  40979. }
  40980. /**
  40981. * Sets the spherical components from the given vector which is assumed to hold
  40982. * Cartesian coordinates.
  40983. *
  40984. * @param {Vector3} v - The vector to set.
  40985. * @return {Spherical} A reference to this spherical.
  40986. */
  40987. setFromVector3( v ) {
  40988. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40989. }
  40990. /**
  40991. * Sets the spherical components from the given Cartesian coordinates.
  40992. *
  40993. * @param {number} x - The x value.
  40994. * @param {number} y - The y value.
  40995. * @param {number} z - The z value.
  40996. * @return {Spherical} A reference to this spherical.
  40997. */
  40998. setFromCartesianCoords( x, y, z ) {
  40999. this.radius = Math.sqrt( x * x + y * y + z * z );
  41000. if ( this.radius === 0 ) {
  41001. this.theta = 0;
  41002. this.phi = 0;
  41003. } else {
  41004. this.theta = Math.atan2( x, z );
  41005. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  41006. }
  41007. return this;
  41008. }
  41009. /**
  41010. * Returns a new spherical with copied values from this instance.
  41011. *
  41012. * @return {Spherical} A clone of this instance.
  41013. */
  41014. clone() {
  41015. return new this.constructor().copy( this );
  41016. }
  41017. }
  41018. /**
  41019. * This class can be used to represent points in 3D space as
  41020. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  41021. */
  41022. class Cylindrical {
  41023. /**
  41024. * Constructs a new cylindrical.
  41025. *
  41026. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  41027. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  41028. * @param {number} [y=0] - The height above the x-z plane.
  41029. */
  41030. constructor( radius = 1, theta = 0, y = 0 ) {
  41031. /**
  41032. * The distance from the origin to a point in the x-z plane.
  41033. *
  41034. * @type {number}
  41035. * @default 1
  41036. */
  41037. this.radius = radius;
  41038. /**
  41039. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  41040. *
  41041. * @type {number}
  41042. * @default 0
  41043. */
  41044. this.theta = theta;
  41045. /**
  41046. * The height above the x-z plane.
  41047. *
  41048. * @type {number}
  41049. * @default 0
  41050. */
  41051. this.y = y;
  41052. }
  41053. /**
  41054. * Sets the cylindrical components by copying the given values.
  41055. *
  41056. * @param {number} radius - The radius.
  41057. * @param {number} theta - The theta angle.
  41058. * @param {number} y - The height value.
  41059. * @return {Cylindrical} A reference to this cylindrical.
  41060. */
  41061. set( radius, theta, y ) {
  41062. this.radius = radius;
  41063. this.theta = theta;
  41064. this.y = y;
  41065. return this;
  41066. }
  41067. /**
  41068. * Copies the values of the given cylindrical to this instance.
  41069. *
  41070. * @param {Cylindrical} other - The cylindrical to copy.
  41071. * @return {Cylindrical} A reference to this cylindrical.
  41072. */
  41073. copy( other ) {
  41074. this.radius = other.radius;
  41075. this.theta = other.theta;
  41076. this.y = other.y;
  41077. return this;
  41078. }
  41079. /**
  41080. * Sets the cylindrical components from the given vector which is assumed to hold
  41081. * Cartesian coordinates.
  41082. *
  41083. * @param {Vector3} v - The vector to set.
  41084. * @return {Cylindrical} A reference to this cylindrical.
  41085. */
  41086. setFromVector3( v ) {
  41087. return this.setFromCartesianCoords( v.x, v.y, v.z );
  41088. }
  41089. /**
  41090. * Sets the cylindrical components from the given Cartesian coordinates.
  41091. *
  41092. * @param {number} x - The x value.
  41093. * @param {number} y - The x value.
  41094. * @param {number} z - The x value.
  41095. * @return {Cylindrical} A reference to this cylindrical.
  41096. */
  41097. setFromCartesianCoords( x, y, z ) {
  41098. this.radius = Math.sqrt( x * x + z * z );
  41099. this.theta = Math.atan2( x, z );
  41100. this.y = y;
  41101. return this;
  41102. }
  41103. /**
  41104. * Returns a new cylindrical with copied values from this instance.
  41105. *
  41106. * @return {Cylindrical} A clone of this instance.
  41107. */
  41108. clone() {
  41109. return new this.constructor().copy( this );
  41110. }
  41111. }
  41112. /**
  41113. * Represents a 2x2 matrix.
  41114. *
  41115. * A Note on Row-Major and Column-Major Ordering:
  41116. *
  41117. * The constructor and {@link Matrix2#set} method take arguments in
  41118. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  41119. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  41120. * This means that calling:
  41121. * ```js
  41122. * const m = new THREE.Matrix2();
  41123. * m.set( 11, 12,
  41124. * 21, 22 );
  41125. * ```
  41126. * will result in the elements array containing:
  41127. * ```js
  41128. * m.elements = [ 11, 21,
  41129. * 12, 22 ];
  41130. * ```
  41131. * and internally all calculations are performed using column-major ordering.
  41132. * However, as the actual ordering makes no difference mathematically and
  41133. * most people are used to thinking about matrices in row-major order, the
  41134. * three.js documentation shows matrices in row-major order. Just bear in
  41135. * mind that if you are reading the source code, you'll have to take the
  41136. * transpose of any matrices outlined here to make sense of the calculations.
  41137. */
  41138. class Matrix2 {
  41139. static {
  41140. /**
  41141. * This flag can be used for type testing.
  41142. *
  41143. * @type {boolean}
  41144. * @readonly
  41145. * @default true
  41146. */
  41147. Matrix2.prototype.isMatrix2 = true;
  41148. }
  41149. /**
  41150. * Constructs a new 2x2 matrix. The arguments are supposed to be
  41151. * in row-major order. If no arguments are provided, the constructor
  41152. * initializes the matrix as an identity matrix.
  41153. *
  41154. * @param {number} [n11] - 1-1 matrix element.
  41155. * @param {number} [n12] - 1-2 matrix element.
  41156. * @param {number} [n21] - 2-1 matrix element.
  41157. * @param {number} [n22] - 2-2 matrix element.
  41158. */
  41159. constructor( n11, n12, n21, n22 ) {
  41160. /**
  41161. * A column-major list of matrix values.
  41162. *
  41163. * @type {Array<number>}
  41164. */
  41165. this.elements = [
  41166. 1, 0,
  41167. 0, 1,
  41168. ];
  41169. if ( n11 !== undefined ) {
  41170. this.set( n11, n12, n21, n22 );
  41171. }
  41172. }
  41173. /**
  41174. * Sets this matrix to the 2x2 identity matrix.
  41175. *
  41176. * @return {Matrix2} A reference to this matrix.
  41177. */
  41178. identity() {
  41179. this.set(
  41180. 1, 0,
  41181. 0, 1,
  41182. );
  41183. return this;
  41184. }
  41185. /**
  41186. * Sets the elements of the matrix from the given array.
  41187. *
  41188. * @param {Array<number>} array - The matrix elements in column-major order.
  41189. * @param {number} [offset=0] - Index of the first element in the array.
  41190. * @return {Matrix2} A reference to this matrix.
  41191. */
  41192. fromArray( array, offset = 0 ) {
  41193. for ( let i = 0; i < 4; i ++ ) {
  41194. this.elements[ i ] = array[ i + offset ];
  41195. }
  41196. return this;
  41197. }
  41198. /**
  41199. * Sets the elements of the matrix.The arguments are supposed to be
  41200. * in row-major order.
  41201. *
  41202. * @param {number} n11 - 1-1 matrix element.
  41203. * @param {number} n12 - 1-2 matrix element.
  41204. * @param {number} n21 - 2-1 matrix element.
  41205. * @param {number} n22 - 2-2 matrix element.
  41206. * @return {Matrix2} A reference to this matrix.
  41207. */
  41208. set( n11, n12, n21, n22 ) {
  41209. const te = this.elements;
  41210. te[ 0 ] = n11; te[ 2 ] = n12;
  41211. te[ 1 ] = n21; te[ 3 ] = n22;
  41212. return this;
  41213. }
  41214. }
  41215. const _vector$4 = /*@__PURE__*/ new Vector2();
  41216. /**
  41217. * Represents an axis-aligned bounding box (AABB) in 2D space.
  41218. */
  41219. class Box2 {
  41220. /**
  41221. * Constructs a new bounding box.
  41222. *
  41223. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  41224. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  41225. */
  41226. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  41227. /**
  41228. * This flag can be used for type testing.
  41229. *
  41230. * @type {boolean}
  41231. * @readonly
  41232. * @default true
  41233. */
  41234. this.isBox2 = true;
  41235. /**
  41236. * The lower boundary of the box.
  41237. *
  41238. * @type {Vector2}
  41239. */
  41240. this.min = min;
  41241. /**
  41242. * The upper boundary of the box.
  41243. *
  41244. * @type {Vector2}
  41245. */
  41246. this.max = max;
  41247. }
  41248. /**
  41249. * Sets the lower and upper boundaries of this box.
  41250. * Please note that this method only copies the values from the given objects.
  41251. *
  41252. * @param {Vector2} min - The lower boundary of the box.
  41253. * @param {Vector2} max - The upper boundary of the box.
  41254. * @return {Box2} A reference to this bounding box.
  41255. */
  41256. set( min, max ) {
  41257. this.min.copy( min );
  41258. this.max.copy( max );
  41259. return this;
  41260. }
  41261. /**
  41262. * Sets the upper and lower bounds of this box so it encloses the position data
  41263. * in the given array.
  41264. *
  41265. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  41266. * @return {Box2} A reference to this bounding box.
  41267. */
  41268. setFromPoints( points ) {
  41269. this.makeEmpty();
  41270. for ( let i = 0, il = points.length; i < il; i ++ ) {
  41271. this.expandByPoint( points[ i ] );
  41272. }
  41273. return this;
  41274. }
  41275. /**
  41276. * Centers this box on the given center vector and sets this box's width, height and
  41277. * depth to the given size values.
  41278. *
  41279. * @param {Vector2} center - The center of the box.
  41280. * @param {Vector2} size - The x and y dimensions of the box.
  41281. * @return {Box2} A reference to this bounding box.
  41282. */
  41283. setFromCenterAndSize( center, size ) {
  41284. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  41285. this.min.copy( center ).sub( halfSize );
  41286. this.max.copy( center ).add( halfSize );
  41287. return this;
  41288. }
  41289. /**
  41290. * Returns a new box with copied values from this instance.
  41291. *
  41292. * @return {Box2} A clone of this instance.
  41293. */
  41294. clone() {
  41295. return new this.constructor().copy( this );
  41296. }
  41297. /**
  41298. * Copies the values of the given box to this instance.
  41299. *
  41300. * @param {Box2} box - The box to copy.
  41301. * @return {Box2} A reference to this bounding box.
  41302. */
  41303. copy( box ) {
  41304. this.min.copy( box.min );
  41305. this.max.copy( box.max );
  41306. return this;
  41307. }
  41308. /**
  41309. * Makes this box empty which means in encloses a zero space in 2D.
  41310. *
  41311. * @return {Box2} A reference to this bounding box.
  41312. */
  41313. makeEmpty() {
  41314. this.min.x = this.min.y = + Infinity;
  41315. this.max.x = this.max.y = - Infinity;
  41316. return this;
  41317. }
  41318. /**
  41319. * Returns true if this box includes zero points within its bounds.
  41320. * Note that a box with equal lower and upper bounds still includes one
  41321. * point, the one both bounds share.
  41322. *
  41323. * @return {boolean} Whether this box is empty or not.
  41324. */
  41325. isEmpty() {
  41326. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  41327. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  41328. }
  41329. /**
  41330. * Returns the center point of this box.
  41331. *
  41332. * @param {Vector2} target - The target vector that is used to store the method's result.
  41333. * @return {Vector2} The center point.
  41334. */
  41335. getCenter( target ) {
  41336. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  41337. }
  41338. /**
  41339. * Returns the dimensions of this box.
  41340. *
  41341. * @param {Vector2} target - The target vector that is used to store the method's result.
  41342. * @return {Vector2} The size.
  41343. */
  41344. getSize( target ) {
  41345. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  41346. }
  41347. /**
  41348. * Expands the boundaries of this box to include the given point.
  41349. *
  41350. * @param {Vector2} point - The point that should be included by the bounding box.
  41351. * @return {Box2} A reference to this bounding box.
  41352. */
  41353. expandByPoint( point ) {
  41354. this.min.min( point );
  41355. this.max.max( point );
  41356. return this;
  41357. }
  41358. /**
  41359. * Expands this box equilaterally by the given vector. The width of this
  41360. * box will be expanded by the x component of the vector in both
  41361. * directions. The height of this box will be expanded by the y component of
  41362. * the vector in both directions.
  41363. *
  41364. * @param {Vector2} vector - The vector that should expand the bounding box.
  41365. * @return {Box2} A reference to this bounding box.
  41366. */
  41367. expandByVector( vector ) {
  41368. this.min.sub( vector );
  41369. this.max.add( vector );
  41370. return this;
  41371. }
  41372. /**
  41373. * Expands each dimension of the box by the given scalar. If negative, the
  41374. * dimensions of the box will be contracted.
  41375. *
  41376. * @param {number} scalar - The scalar value that should expand the bounding box.
  41377. * @return {Box2} A reference to this bounding box.
  41378. */
  41379. expandByScalar( scalar ) {
  41380. this.min.addScalar( - scalar );
  41381. this.max.addScalar( scalar );
  41382. return this;
  41383. }
  41384. /**
  41385. * Returns `true` if the given point lies within or on the boundaries of this box.
  41386. *
  41387. * @param {Vector2} point - The point to test.
  41388. * @return {boolean} Whether the bounding box contains the given point or not.
  41389. */
  41390. containsPoint( point ) {
  41391. return point.x >= this.min.x && point.x <= this.max.x &&
  41392. point.y >= this.min.y && point.y <= this.max.y;
  41393. }
  41394. /**
  41395. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  41396. * If this box and the given one are identical, this function also returns `true`.
  41397. *
  41398. * @param {Box2} box - The bounding box to test.
  41399. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  41400. */
  41401. containsBox( box ) {
  41402. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  41403. this.min.y <= box.min.y && box.max.y <= this.max.y;
  41404. }
  41405. /**
  41406. * Returns a point as a proportion of this box's width and height.
  41407. *
  41408. * @param {Vector2} point - A point in 2D space.
  41409. * @param {Vector2} target - The target vector that is used to store the method's result.
  41410. * @return {Vector2} A point as a proportion of this box's width and height.
  41411. */
  41412. getParameter( point, target ) {
  41413. // This can potentially have a divide by zero if the box
  41414. // has a size dimension of 0.
  41415. return target.set(
  41416. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  41417. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  41418. );
  41419. }
  41420. /**
  41421. * Returns `true` if the given bounding box intersects with this bounding box.
  41422. *
  41423. * @param {Box2} box - The bounding box to test.
  41424. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  41425. */
  41426. intersectsBox( box ) {
  41427. // using 4 splitting planes to rule out intersections
  41428. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  41429. box.max.y >= this.min.y && box.min.y <= this.max.y;
  41430. }
  41431. /**
  41432. * Clamps the given point within the bounds of this box.
  41433. *
  41434. * @param {Vector2} point - The point to clamp.
  41435. * @param {Vector2} target - The target vector that is used to store the method's result.
  41436. * @return {Vector2} The clamped point.
  41437. */
  41438. clampPoint( point, target ) {
  41439. return target.copy( point ).clamp( this.min, this.max );
  41440. }
  41441. /**
  41442. * Returns the euclidean distance from any edge of this box to the specified point. If
  41443. * the given point lies inside of this box, the distance will be `0`.
  41444. *
  41445. * @param {Vector2} point - The point to compute the distance to.
  41446. * @return {number} The euclidean distance.
  41447. */
  41448. distanceToPoint( point ) {
  41449. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  41450. }
  41451. /**
  41452. * Computes the intersection of this bounding box and the given one, setting the upper
  41453. * bound of this box to the lesser of the two boxes' upper bounds and the
  41454. * lower bound of this box to the greater of the two boxes' lower bounds. If
  41455. * there's no overlap, makes this box empty.
  41456. *
  41457. * @param {Box2} box - The bounding box to intersect with.
  41458. * @return {Box2} A reference to this bounding box.
  41459. */
  41460. intersect( box ) {
  41461. this.min.max( box.min );
  41462. this.max.min( box.max );
  41463. if ( this.isEmpty() ) this.makeEmpty();
  41464. return this;
  41465. }
  41466. /**
  41467. * Computes the union of this box and another and the given one, setting the upper
  41468. * bound of this box to the greater of the two boxes' upper bounds and the
  41469. * lower bound of this box to the lesser of the two boxes' lower bounds.
  41470. *
  41471. * @param {Box2} box - The bounding box that will be unioned with this instance.
  41472. * @return {Box2} A reference to this bounding box.
  41473. */
  41474. union( box ) {
  41475. this.min.min( box.min );
  41476. this.max.max( box.max );
  41477. return this;
  41478. }
  41479. /**
  41480. * Adds the given offset to both the upper and lower bounds of this bounding box,
  41481. * effectively moving it in 2D space.
  41482. *
  41483. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  41484. * @return {Box2} A reference to this bounding box.
  41485. */
  41486. translate( offset ) {
  41487. this.min.add( offset );
  41488. this.max.add( offset );
  41489. return this;
  41490. }
  41491. /**
  41492. * Returns `true` if this bounding box is equal with the given one.
  41493. *
  41494. * @param {Box2} box - The box to test for equality.
  41495. * @return {boolean} Whether this bounding box is equal with the given one.
  41496. */
  41497. equals( box ) {
  41498. return box.min.equals( this.min ) && box.max.equals( this.max );
  41499. }
  41500. }
  41501. const _startP = /*@__PURE__*/ new Vector3();
  41502. const _startEnd = /*@__PURE__*/ new Vector3();
  41503. const _d1 = /*@__PURE__*/ new Vector3();
  41504. const _d2 = /*@__PURE__*/ new Vector3();
  41505. const _r = /*@__PURE__*/ new Vector3();
  41506. const _c1 = /*@__PURE__*/ new Vector3();
  41507. const _c2 = /*@__PURE__*/ new Vector3();
  41508. /**
  41509. * An analytical line segment in 3D space represented by a start and end point.
  41510. */
  41511. class Line3 {
  41512. /**
  41513. * Constructs a new line segment.
  41514. *
  41515. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  41516. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  41517. */
  41518. constructor( start = new Vector3(), end = new Vector3() ) {
  41519. /**
  41520. * Start of the line segment.
  41521. *
  41522. * @type {Vector3}
  41523. */
  41524. this.start = start;
  41525. /**
  41526. * End of the line segment.
  41527. *
  41528. * @type {Vector3}
  41529. */
  41530. this.end = end;
  41531. }
  41532. /**
  41533. * Sets the start and end values by copying the given vectors.
  41534. *
  41535. * @param {Vector3} start - The start point.
  41536. * @param {Vector3} end - The end point.
  41537. * @return {Line3} A reference to this line segment.
  41538. */
  41539. set( start, end ) {
  41540. this.start.copy( start );
  41541. this.end.copy( end );
  41542. return this;
  41543. }
  41544. /**
  41545. * Copies the values of the given line segment to this instance.
  41546. *
  41547. * @param {Line3} line - The line segment to copy.
  41548. * @return {Line3} A reference to this line segment.
  41549. */
  41550. copy( line ) {
  41551. this.start.copy( line.start );
  41552. this.end.copy( line.end );
  41553. return this;
  41554. }
  41555. /**
  41556. * Returns the center of the line segment.
  41557. *
  41558. * @param {Vector3} target - The target vector that is used to store the method's result.
  41559. * @return {Vector3} The center point.
  41560. */
  41561. getCenter( target ) {
  41562. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  41563. }
  41564. /**
  41565. * Returns the delta vector of the line segment's start and end point.
  41566. *
  41567. * @param {Vector3} target - The target vector that is used to store the method's result.
  41568. * @return {Vector3} The delta vector.
  41569. */
  41570. delta( target ) {
  41571. return target.subVectors( this.end, this.start );
  41572. }
  41573. /**
  41574. * Returns the squared Euclidean distance between the line' start and end point.
  41575. *
  41576. * @return {number} The squared Euclidean distance.
  41577. */
  41578. distanceSq() {
  41579. return this.start.distanceToSquared( this.end );
  41580. }
  41581. /**
  41582. * Returns the Euclidean distance between the line' start and end point.
  41583. *
  41584. * @return {number} The Euclidean distance.
  41585. */
  41586. distance() {
  41587. return this.start.distanceTo( this.end );
  41588. }
  41589. /**
  41590. * Returns a vector at a certain position along the line segment.
  41591. *
  41592. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41593. * @param {Vector3} target - The target vector that is used to store the method's result.
  41594. * @return {Vector3} The delta vector.
  41595. */
  41596. at( t, target ) {
  41597. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41598. }
  41599. /**
  41600. * Returns a point parameter based on the closest point as projected on the line segment.
  41601. *
  41602. * @param {Vector3} point - The point for which to return a point parameter.
  41603. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41604. * @return {number} The point parameter.
  41605. */
  41606. closestPointToPointParameter( point, clampToLine ) {
  41607. _startP.subVectors( point, this.start );
  41608. _startEnd.subVectors( this.end, this.start );
  41609. const startEnd2 = _startEnd.dot( _startEnd );
  41610. if ( startEnd2 === 0 ) return 0;
  41611. const startEnd_startP = _startEnd.dot( _startP );
  41612. let t = startEnd_startP / startEnd2;
  41613. if ( clampToLine ) {
  41614. t = clamp( t, 0, 1 );
  41615. }
  41616. return t;
  41617. }
  41618. /**
  41619. * Returns the closest point on the line for a given point.
  41620. *
  41621. * @param {Vector3} point - The point to compute the closest point on the line for.
  41622. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41623. * @param {Vector3} target - The target vector that is used to store the method's result.
  41624. * @return {Vector3} The closest point on the line.
  41625. */
  41626. closestPointToPoint( point, clampToLine, target ) {
  41627. const t = this.closestPointToPointParameter( point, clampToLine );
  41628. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41629. }
  41630. /**
  41631. * Returns the closest squared distance between this line segment and the given one.
  41632. *
  41633. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41634. * @param {Vector3} [c1] - The closest point on this line segment.
  41635. * @param {Vector3} [c2] - The closest point on the given line segment.
  41636. * @return {number} The squared distance between this line segment and the given one.
  41637. */
  41638. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41639. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41640. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41641. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41642. // distance between between S1(s) and S2(t)
  41643. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41644. let s, t;
  41645. const p1 = this.start;
  41646. const p2 = line.start;
  41647. const q1 = this.end;
  41648. const q2 = line.end;
  41649. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41650. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41651. _r.subVectors( p1, p2 );
  41652. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41653. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41654. const f = _d2.dot( _r );
  41655. // Check if either or both segments degenerate into points
  41656. if ( a <= EPSILON && e <= EPSILON ) {
  41657. // Both segments degenerate into points
  41658. c1.copy( p1 );
  41659. c2.copy( p2 );
  41660. c1.sub( c2 );
  41661. return c1.dot( c1 );
  41662. }
  41663. if ( a <= EPSILON ) {
  41664. // First segment degenerates into a point
  41665. s = 0;
  41666. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41667. t = clamp( t, 0, 1 );
  41668. } else {
  41669. const c = _d1.dot( _r );
  41670. if ( e <= EPSILON ) {
  41671. // Second segment degenerates into a point
  41672. t = 0;
  41673. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41674. } else {
  41675. // The general nondegenerate case starts here
  41676. const b = _d1.dot( _d2 );
  41677. const denom = a * e - b * b; // Always nonnegative
  41678. // If segments not parallel, compute closest point on L1 to L2 and
  41679. // clamp to segment S1. Else pick arbitrary s (here 0)
  41680. if ( denom !== 0 ) {
  41681. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41682. } else {
  41683. s = 0;
  41684. }
  41685. // Compute point on L2 closest to S1(s) using
  41686. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41687. t = ( b * s + f ) / e;
  41688. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41689. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41690. // and clamp s to [0, 1]
  41691. if ( t < 0 ) {
  41692. t = 0.;
  41693. s = clamp( - c / a, 0, 1 );
  41694. } else if ( t > 1 ) {
  41695. t = 1;
  41696. s = clamp( ( b - c ) / a, 0, 1 );
  41697. }
  41698. }
  41699. }
  41700. c1.copy( p1 ).addScaledVector( _d1, s );
  41701. c2.copy( p2 ).addScaledVector( _d2, t );
  41702. return c1.distanceToSquared( c2 );
  41703. }
  41704. /**
  41705. * Applies a 4x4 transformation matrix to this line segment.
  41706. *
  41707. * @param {Matrix4} matrix - The transformation matrix.
  41708. * @return {Line3} A reference to this line segment.
  41709. */
  41710. applyMatrix4( matrix ) {
  41711. this.start.applyMatrix4( matrix );
  41712. this.end.applyMatrix4( matrix );
  41713. return this;
  41714. }
  41715. /**
  41716. * Returns `true` if this line segment is equal with the given one.
  41717. *
  41718. * @param {Line3} line - The line segment to test for equality.
  41719. * @return {boolean} Whether this line segment is equal with the given one.
  41720. */
  41721. equals( line ) {
  41722. return line.start.equals( this.start ) && line.end.equals( this.end );
  41723. }
  41724. /**
  41725. * Returns a new line segment with copied values from this instance.
  41726. *
  41727. * @return {Line3} A clone of this instance.
  41728. */
  41729. clone() {
  41730. return new this.constructor().copy( this );
  41731. }
  41732. }
  41733. const _vector$3 = /*@__PURE__*/ new Vector3();
  41734. /**
  41735. * This displays a cone shaped helper object for a {@link SpotLight}.
  41736. *
  41737. * When the spot light or its target are transformed or light properties are
  41738. * changed, it's necessary to call the `update()` method of the respective helper.
  41739. *
  41740. * ```js
  41741. * const spotLight = new THREE.SpotLight( 0xffffff );
  41742. * spotLight.position.set( 10, 10, 10 );
  41743. * scene.add( spotLight );
  41744. *
  41745. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41746. * scene.add( spotLightHelper );
  41747. * ```
  41748. *
  41749. * @augments Object3D
  41750. */
  41751. class SpotLightHelper extends Object3D {
  41752. /**
  41753. * Constructs a new spot light helper.
  41754. *
  41755. * @param {HemisphereLight} light - The light to be visualized.
  41756. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41757. * the color of the light.
  41758. */
  41759. constructor( light, color ) {
  41760. super();
  41761. /**
  41762. * The light being visualized.
  41763. *
  41764. * @type {SpotLight}
  41765. */
  41766. this.light = light;
  41767. this.matrixAutoUpdate = false;
  41768. /**
  41769. * The color parameter passed in the constructor.
  41770. * If not set, the helper will take the color of the light.
  41771. *
  41772. * @type {number|Color|string}
  41773. */
  41774. this.color = color;
  41775. this.type = 'SpotLightHelper';
  41776. const geometry = new BufferGeometry();
  41777. const positions = [
  41778. 0, 0, 0, 0, 0, 1,
  41779. 0, 0, 0, 1, 0, 1,
  41780. 0, 0, 0, -1, 0, 1,
  41781. 0, 0, 0, 0, 1, 1,
  41782. 0, 0, 0, 0, -1, 1
  41783. ];
  41784. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41785. const p1 = ( i / l ) * Math.PI * 2;
  41786. const p2 = ( j / l ) * Math.PI * 2;
  41787. positions.push(
  41788. Math.cos( p1 ), Math.sin( p1 ), 1,
  41789. Math.cos( p2 ), Math.sin( p2 ), 1
  41790. );
  41791. }
  41792. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41793. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41794. this.cone = new LineSegments( geometry, material );
  41795. this.add( this.cone );
  41796. this.update();
  41797. }
  41798. /**
  41799. * Frees the GPU-related resources allocated by this instance. Call this
  41800. * method whenever this instance is no longer used in your app.
  41801. */
  41802. dispose() {
  41803. this.cone.geometry.dispose();
  41804. this.cone.material.dispose();
  41805. }
  41806. /**
  41807. * Updates the helper to match the position and direction of the
  41808. * light being visualized.
  41809. */
  41810. update() {
  41811. this.light.updateWorldMatrix( true, false );
  41812. this.light.target.updateWorldMatrix( true, false );
  41813. // update the local matrix based on the parent and light target transforms
  41814. if ( this.parent ) {
  41815. this.parent.updateWorldMatrix( true );
  41816. this.matrix
  41817. .copy( this.parent.matrixWorld )
  41818. .invert()
  41819. .multiply( this.light.matrixWorld );
  41820. } else {
  41821. this.matrix.copy( this.light.matrixWorld );
  41822. }
  41823. this.matrixWorldNeedsUpdate = true;
  41824. const coneLength = this.light.distance ? this.light.distance : 1000;
  41825. const coneWidth = coneLength * Math.tan( this.light.angle );
  41826. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41827. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41828. this.cone.lookAt( _vector$3 );
  41829. if ( this.color !== undefined ) {
  41830. this.cone.material.color.set( this.color );
  41831. } else {
  41832. this.cone.material.color.copy( this.light.color );
  41833. }
  41834. }
  41835. }
  41836. const _vector$2 = /*@__PURE__*/ new Vector3();
  41837. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41838. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41839. /**
  41840. * A helper object to assist with visualizing a {@link Skeleton}.
  41841. *
  41842. * ```js
  41843. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41844. * scene.add( helper );
  41845. * ```
  41846. *
  41847. * @augments LineSegments
  41848. */
  41849. class SkeletonHelper extends LineSegments {
  41850. /**
  41851. * Constructs a new skeleton helper.
  41852. *
  41853. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41854. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41855. */
  41856. constructor( object ) {
  41857. const bones = getBoneList( object );
  41858. const geometry = new BufferGeometry();
  41859. const vertices = [];
  41860. const colors = [];
  41861. for ( let i = 0; i < bones.length; i ++ ) {
  41862. const bone = bones[ i ];
  41863. if ( bone.parent && bone.parent.isBone ) {
  41864. vertices.push( 0, 0, 0 );
  41865. vertices.push( 0, 0, 0 );
  41866. colors.push( 0, 0, 0 );
  41867. colors.push( 0, 0, 0 );
  41868. }
  41869. }
  41870. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41871. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41872. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41873. super( geometry, material );
  41874. /**
  41875. * This flag can be used for type testing.
  41876. *
  41877. * @type {boolean}
  41878. * @readonly
  41879. * @default true
  41880. */
  41881. this.isSkeletonHelper = true;
  41882. this.type = 'SkeletonHelper';
  41883. /**
  41884. * The object being visualized.
  41885. *
  41886. * @type {Object3D}
  41887. */
  41888. this.root = object;
  41889. /**
  41890. * The list of bones that the helper visualizes.
  41891. *
  41892. * @type {Array<Bone>}
  41893. */
  41894. this.bones = bones;
  41895. this.matrix = object.matrixWorld;
  41896. this.matrixAutoUpdate = false;
  41897. // colors
  41898. const color1 = new Color( 0x0000ff );
  41899. const color2 = new Color( 0x00ff00 );
  41900. this.setColors( color1, color2 );
  41901. }
  41902. updateMatrixWorld( force ) {
  41903. const bones = this.bones;
  41904. const geometry = this.geometry;
  41905. const position = geometry.getAttribute( 'position' );
  41906. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41907. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41908. const bone = bones[ i ];
  41909. if ( bone.parent && bone.parent.isBone ) {
  41910. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41911. _vector$2.setFromMatrixPosition( _boneMatrix );
  41912. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41913. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41914. _vector$2.setFromMatrixPosition( _boneMatrix );
  41915. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41916. j += 2;
  41917. }
  41918. }
  41919. geometry.getAttribute( 'position' ).needsUpdate = true;
  41920. super.updateMatrixWorld( force );
  41921. }
  41922. /**
  41923. * Defines the colors of the helper.
  41924. *
  41925. * @param {Color} color1 - The first line color for each bone.
  41926. * @param {Color} color2 - The second line color for each bone.
  41927. * @return {SkeletonHelper} A reference to this helper.
  41928. */
  41929. setColors( color1, color2 ) {
  41930. const geometry = this.geometry;
  41931. const colorAttribute = geometry.getAttribute( 'color' );
  41932. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41933. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41934. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41935. }
  41936. colorAttribute.needsUpdate = true;
  41937. return this;
  41938. }
  41939. /**
  41940. * Frees the GPU-related resources allocated by this instance. Call this
  41941. * method whenever this instance is no longer used in your app.
  41942. */
  41943. dispose() {
  41944. this.geometry.dispose();
  41945. this.material.dispose();
  41946. }
  41947. }
  41948. function getBoneList( object ) {
  41949. const boneList = [];
  41950. if ( object.isBone === true ) {
  41951. boneList.push( object );
  41952. }
  41953. for ( let i = 0; i < object.children.length; i ++ ) {
  41954. boneList.push( ...getBoneList( object.children[ i ] ) );
  41955. }
  41956. return boneList;
  41957. }
  41958. /**
  41959. * This displays a helper object consisting of a spherical mesh for
  41960. * visualizing an instance of {@link PointLight}.
  41961. *
  41962. * ```js
  41963. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41964. * pointLight.position.set( 10, 10, 10 );
  41965. * scene.add( pointLight );
  41966. *
  41967. * const sphereSize = 1;
  41968. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41969. * scene.add( pointLightHelper );
  41970. * ```
  41971. *
  41972. * @augments Mesh
  41973. */
  41974. class PointLightHelper extends Mesh {
  41975. /**
  41976. * Constructs a new point light helper.
  41977. *
  41978. * @param {PointLight} light - The light to be visualized.
  41979. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41980. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41981. * the color of the light.
  41982. */
  41983. constructor( light, sphereSize, color ) {
  41984. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41985. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41986. super( geometry, material );
  41987. /**
  41988. * The light being visualized.
  41989. *
  41990. * @type {PointLight}
  41991. */
  41992. this.light = light;
  41993. /**
  41994. * The color parameter passed in the constructor.
  41995. * If not set, the helper will take the color of the light.
  41996. *
  41997. * @type {number|Color|string}
  41998. */
  41999. this.color = color;
  42000. this.type = 'PointLightHelper';
  42001. this.matrix = this.light.matrixWorld;
  42002. this.matrixAutoUpdate = false;
  42003. this.update();
  42004. }
  42005. /**
  42006. * Frees the GPU-related resources allocated by this instance. Call this
  42007. * method whenever this instance is no longer used in your app.
  42008. */
  42009. dispose() {
  42010. this.geometry.dispose();
  42011. this.material.dispose();
  42012. }
  42013. /**
  42014. * Updates the helper to match the position of the
  42015. * light being visualized.
  42016. */
  42017. update() {
  42018. this.matrixWorldNeedsUpdate = true;
  42019. this.light.updateWorldMatrix( true, false );
  42020. if ( this.color !== undefined ) {
  42021. this.material.color.set( this.color );
  42022. } else {
  42023. this.material.color.copy( this.light.color );
  42024. }
  42025. /*
  42026. const d = this.light.distance;
  42027. if ( d === 0.0 ) {
  42028. this.lightDistance.visible = false;
  42029. } else {
  42030. this.lightDistance.visible = true;
  42031. this.lightDistance.scale.set( d, d, d );
  42032. }
  42033. */
  42034. }
  42035. }
  42036. const _vector$1 = /*@__PURE__*/ new Vector3();
  42037. const _color1 = /*@__PURE__*/ new Color();
  42038. const _color2 = /*@__PURE__*/ new Color();
  42039. /**
  42040. * Creates a visual aid consisting of a spherical mesh for a
  42041. * given {@link HemisphereLight}.
  42042. *
  42043. * When the hemisphere light is transformed or its light properties are changed,
  42044. * it's necessary to call the `update()` method of the respective helper.
  42045. *
  42046. * ```js
  42047. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  42048. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  42049. * scene.add( helper );
  42050. * ```
  42051. *
  42052. * @augments Object3D
  42053. */
  42054. class HemisphereLightHelper extends Object3D {
  42055. /**
  42056. * Constructs a new hemisphere light helper.
  42057. *
  42058. * @param {HemisphereLight} light - The light to be visualized.
  42059. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  42060. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  42061. * the color of the light.
  42062. */
  42063. constructor( light, size, color ) {
  42064. super();
  42065. /**
  42066. * The light being visualized.
  42067. *
  42068. * @type {HemisphereLight}
  42069. */
  42070. this.light = light;
  42071. this.matrix = light.matrixWorld;
  42072. this.matrixAutoUpdate = false;
  42073. /**
  42074. * The color parameter passed in the constructor.
  42075. * If not set, the helper will take the color of the light.
  42076. *
  42077. * @type {number|Color|string}
  42078. */
  42079. this.color = color;
  42080. this.type = 'HemisphereLightHelper';
  42081. const geometry = new OctahedronGeometry( size );
  42082. geometry.rotateY( Math.PI * 0.5 );
  42083. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  42084. if ( this.color === undefined ) this.material.vertexColors = true;
  42085. const position = geometry.getAttribute( 'position' );
  42086. const colors = new Float32Array( position.count * 3 );
  42087. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  42088. this.add( new Mesh( geometry, this.material ) );
  42089. this.update();
  42090. }
  42091. /**
  42092. * Frees the GPU-related resources allocated by this instance. Call this
  42093. * method whenever this instance is no longer used in your app.
  42094. */
  42095. dispose() {
  42096. this.children[ 0 ].geometry.dispose();
  42097. this.children[ 0 ].material.dispose();
  42098. }
  42099. /**
  42100. * Updates the helper to match the position and direction of the
  42101. * light being visualized.
  42102. */
  42103. update() {
  42104. const mesh = this.children[ 0 ];
  42105. if ( this.color !== undefined ) {
  42106. this.material.color.set( this.color );
  42107. } else {
  42108. const colors = mesh.geometry.getAttribute( 'color' );
  42109. _color1.copy( this.light.color );
  42110. _color2.copy( this.light.groundColor );
  42111. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  42112. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  42113. colors.setXYZ( i, color.r, color.g, color.b );
  42114. }
  42115. colors.needsUpdate = true;
  42116. }
  42117. this.matrixWorldNeedsUpdate = true;
  42118. this.light.updateWorldMatrix( true, false );
  42119. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  42120. }
  42121. }
  42122. /**
  42123. * The helper is an object to define grids. Grids are two-dimensional
  42124. * arrays of lines.
  42125. *
  42126. * ```js
  42127. * const size = 10;
  42128. * const divisions = 10;
  42129. *
  42130. * const gridHelper = new THREE.GridHelper( size, divisions );
  42131. * scene.add( gridHelper );
  42132. * ```
  42133. *
  42134. * @augments LineSegments
  42135. */
  42136. class GridHelper extends LineSegments {
  42137. /**
  42138. * Constructs a new grid helper.
  42139. *
  42140. * @param {number} [size=10] - The size of the grid.
  42141. * @param {number} [divisions=10] - The number of divisions across the grid.
  42142. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  42143. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  42144. */
  42145. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  42146. color1 = new Color( color1 );
  42147. color2 = new Color( color2 );
  42148. const center = divisions / 2;
  42149. const step = size / divisions;
  42150. const halfSize = size / 2;
  42151. const vertices = [], colors = [];
  42152. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  42153. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  42154. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  42155. const color = i === center ? color1 : color2;
  42156. color.toArray( colors, j ); j += 3;
  42157. color.toArray( colors, j ); j += 3;
  42158. color.toArray( colors, j ); j += 3;
  42159. color.toArray( colors, j ); j += 3;
  42160. }
  42161. const geometry = new BufferGeometry();
  42162. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42163. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42164. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42165. super( geometry, material );
  42166. this.type = 'GridHelper';
  42167. }
  42168. /**
  42169. * Frees the GPU-related resources allocated by this instance. Call this
  42170. * method whenever this instance is no longer used in your app.
  42171. */
  42172. dispose() {
  42173. this.geometry.dispose();
  42174. this.material.dispose();
  42175. }
  42176. }
  42177. /**
  42178. * This helper is an object to define polar grids. Grids are
  42179. * two-dimensional arrays of lines.
  42180. *
  42181. * ```js
  42182. * const radius = 10;
  42183. * const sectors = 16;
  42184. * const rings = 8;
  42185. * const divisions = 64;
  42186. *
  42187. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  42188. * scene.add( helper );
  42189. * ```
  42190. *
  42191. * @augments LineSegments
  42192. */
  42193. class PolarGridHelper extends LineSegments {
  42194. /**
  42195. * Constructs a new polar grid helper.
  42196. *
  42197. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  42198. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  42199. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  42200. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  42201. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  42202. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  42203. */
  42204. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  42205. color1 = new Color( color1 );
  42206. color2 = new Color( color2 );
  42207. const vertices = [];
  42208. const colors = [];
  42209. // create the sectors
  42210. if ( sectors > 1 ) {
  42211. for ( let i = 0; i < sectors; i ++ ) {
  42212. const v = ( i / sectors ) * ( Math.PI * 2 );
  42213. const x = Math.sin( v ) * radius;
  42214. const z = Math.cos( v ) * radius;
  42215. vertices.push( 0, 0, 0 );
  42216. vertices.push( x, 0, z );
  42217. const color = ( i & 1 ) ? color1 : color2;
  42218. colors.push( color.r, color.g, color.b );
  42219. colors.push( color.r, color.g, color.b );
  42220. }
  42221. }
  42222. // create the rings
  42223. for ( let i = 0; i < rings; i ++ ) {
  42224. const color = ( i & 1 ) ? color1 : color2;
  42225. const r = radius - ( radius / rings * i );
  42226. for ( let j = 0; j < divisions; j ++ ) {
  42227. // first vertex
  42228. let v = ( j / divisions ) * ( Math.PI * 2 );
  42229. let x = Math.sin( v ) * r;
  42230. let z = Math.cos( v ) * r;
  42231. vertices.push( x, 0, z );
  42232. colors.push( color.r, color.g, color.b );
  42233. // second vertex
  42234. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  42235. x = Math.sin( v ) * r;
  42236. z = Math.cos( v ) * r;
  42237. vertices.push( x, 0, z );
  42238. colors.push( color.r, color.g, color.b );
  42239. }
  42240. }
  42241. const geometry = new BufferGeometry();
  42242. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42243. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42244. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42245. super( geometry, material );
  42246. this.type = 'PolarGridHelper';
  42247. }
  42248. /**
  42249. * Frees the GPU-related resources allocated by this instance. Call this
  42250. * method whenever this instance is no longer used in your app.
  42251. */
  42252. dispose() {
  42253. this.geometry.dispose();
  42254. this.material.dispose();
  42255. }
  42256. }
  42257. const _v1 = /*@__PURE__*/ new Vector3();
  42258. const _v2 = /*@__PURE__*/ new Vector3();
  42259. const _v3 = /*@__PURE__*/ new Vector3();
  42260. /**
  42261. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  42262. * effect on the scene. This consists of a plane and a line representing the
  42263. * light's position and direction.
  42264. *
  42265. * When the directional light or its target are transformed or light properties
  42266. * are changed, it's necessary to call the `update()` method of the respective helper.
  42267. *
  42268. * ```js
  42269. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  42270. * scene.add( light );
  42271. *
  42272. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  42273. * scene.add( helper );
  42274. * ```
  42275. *
  42276. * @augments Object3D
  42277. */
  42278. class DirectionalLightHelper extends Object3D {
  42279. /**
  42280. * Constructs a new directional light helper.
  42281. *
  42282. * @param {DirectionalLight} light - The light to be visualized.
  42283. * @param {number} [size=1] - The dimensions of the plane.
  42284. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  42285. * the color of the light.
  42286. */
  42287. constructor( light, size, color ) {
  42288. super();
  42289. /**
  42290. * The light being visualized.
  42291. *
  42292. * @type {DirectionalLight}
  42293. */
  42294. this.light = light;
  42295. this.matrix = light.matrixWorld;
  42296. this.matrixAutoUpdate = false;
  42297. /**
  42298. * The color parameter passed in the constructor.
  42299. * If not set, the helper will take the color of the light.
  42300. *
  42301. * @type {number|Color|string}
  42302. */
  42303. this.color = color;
  42304. this.type = 'DirectionalLightHelper';
  42305. if ( size === undefined ) size = 1;
  42306. let geometry = new BufferGeometry();
  42307. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  42308. - size, size, 0,
  42309. size, size, 0,
  42310. size, - size, 0,
  42311. - size, - size, 0,
  42312. - size, size, 0
  42313. ], 3 ) );
  42314. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  42315. /**
  42316. * Contains the line showing the location of the directional light.
  42317. *
  42318. * @type {Line}
  42319. */
  42320. this.lightPlane = new Line( geometry, material );
  42321. this.add( this.lightPlane );
  42322. geometry = new BufferGeometry();
  42323. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  42324. /**
  42325. * Represents the target line of the directional light.
  42326. *
  42327. * @type {Line}
  42328. */
  42329. this.targetLine = new Line( geometry, material );
  42330. this.add( this.targetLine );
  42331. this.update();
  42332. }
  42333. /**
  42334. * Frees the GPU-related resources allocated by this instance. Call this
  42335. * method whenever this instance is no longer used in your app.
  42336. */
  42337. dispose() {
  42338. this.lightPlane.geometry.dispose();
  42339. this.lightPlane.material.dispose();
  42340. this.targetLine.geometry.dispose();
  42341. this.targetLine.material.dispose();
  42342. }
  42343. /**
  42344. * Updates the helper to match the position and direction of the
  42345. * light being visualized.
  42346. */
  42347. update() {
  42348. this.matrixWorldNeedsUpdate = true;
  42349. this.light.updateWorldMatrix( true, false );
  42350. this.light.target.updateWorldMatrix( true, false );
  42351. _v1.setFromMatrixPosition( this.light.matrixWorld );
  42352. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  42353. _v3.subVectors( _v2, _v1 );
  42354. this.lightPlane.lookAt( _v2 );
  42355. if ( this.color !== undefined ) {
  42356. this.lightPlane.material.color.set( this.color );
  42357. this.targetLine.material.color.set( this.color );
  42358. } else {
  42359. this.lightPlane.material.color.copy( this.light.color );
  42360. this.targetLine.material.color.copy( this.light.color );
  42361. }
  42362. this.targetLine.lookAt( _v2 );
  42363. this.targetLine.scale.z = _v3.length();
  42364. }
  42365. }
  42366. const _vector = /*@__PURE__*/ new Vector3();
  42367. const _camera = /*@__PURE__*/ new Camera();
  42368. /**
  42369. * This helps with visualizing what a camera contains in its frustum. It
  42370. * visualizes the frustum of a camera using a line segments.
  42371. *
  42372. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  42373. *
  42374. * `CameraHelper` must be a child of the scene.
  42375. *
  42376. * When the camera is transformed or its projection matrix is changed, it's necessary
  42377. * to call the `update()` method of the respective helper.
  42378. *
  42379. * ```js
  42380. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  42381. * const helper = new THREE.CameraHelper( camera );
  42382. * scene.add( helper );
  42383. * ```
  42384. *
  42385. * @augments LineSegments
  42386. */
  42387. class CameraHelper extends LineSegments {
  42388. /**
  42389. * Constructs a new arrow helper.
  42390. *
  42391. * @param {Camera} camera - The camera to visualize.
  42392. */
  42393. constructor( camera ) {
  42394. const geometry = new BufferGeometry();
  42395. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  42396. const vertices = [];
  42397. const colors = [];
  42398. const pointMap = {};
  42399. // near
  42400. addLine( 'n1', 'n2' );
  42401. addLine( 'n2', 'n4' );
  42402. addLine( 'n4', 'n3' );
  42403. addLine( 'n3', 'n1' );
  42404. // far
  42405. addLine( 'f1', 'f2' );
  42406. addLine( 'f2', 'f4' );
  42407. addLine( 'f4', 'f3' );
  42408. addLine( 'f3', 'f1' );
  42409. // sides
  42410. addLine( 'n1', 'f1' );
  42411. addLine( 'n2', 'f2' );
  42412. addLine( 'n3', 'f3' );
  42413. addLine( 'n4', 'f4' );
  42414. // cone
  42415. addLine( 'p', 'n1' );
  42416. addLine( 'p', 'n2' );
  42417. addLine( 'p', 'n3' );
  42418. addLine( 'p', 'n4' );
  42419. // up
  42420. addLine( 'u1', 'u2' );
  42421. addLine( 'u2', 'u3' );
  42422. addLine( 'u3', 'u1' );
  42423. // target
  42424. addLine( 'c', 't' );
  42425. addLine( 'p', 'c' );
  42426. // cross
  42427. addLine( 'cn1', 'cn2' );
  42428. addLine( 'cn3', 'cn4' );
  42429. addLine( 'cf1', 'cf2' );
  42430. addLine( 'cf3', 'cf4' );
  42431. function addLine( a, b ) {
  42432. addPoint( a );
  42433. addPoint( b );
  42434. }
  42435. function addPoint( id ) {
  42436. vertices.push( 0, 0, 0 );
  42437. colors.push( 0, 0, 0 );
  42438. if ( pointMap[ id ] === undefined ) {
  42439. pointMap[ id ] = [];
  42440. }
  42441. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  42442. }
  42443. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42444. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42445. super( geometry, material );
  42446. this.type = 'CameraHelper';
  42447. /**
  42448. * The camera being visualized.
  42449. *
  42450. * @type {Camera}
  42451. */
  42452. this.camera = camera;
  42453. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  42454. this.matrix = camera.matrixWorld;
  42455. this.matrixAutoUpdate = false;
  42456. /**
  42457. * This contains the points used to visualize the camera.
  42458. *
  42459. * @type {Object<string,Array<number>>}
  42460. */
  42461. this.pointMap = pointMap;
  42462. this.update();
  42463. // colors
  42464. const colorFrustum = new Color( 0xffaa00 );
  42465. const colorCone = new Color( 0xff0000 );
  42466. const colorUp = new Color( 0x00aaff );
  42467. const colorTarget = new Color( 0xffffff );
  42468. const colorCross = new Color( 0x333333 );
  42469. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  42470. }
  42471. /**
  42472. * Defines the colors of the helper.
  42473. *
  42474. * @param {Color} frustum - The frustum line color.
  42475. * @param {Color} cone - The cone line color.
  42476. * @param {Color} up - The up line color.
  42477. * @param {Color} target - The target line color.
  42478. * @param {Color} cross - The cross line color.
  42479. * @return {CameraHelper} A reference to this helper.
  42480. */
  42481. setColors( frustum, cone, up, target, cross ) {
  42482. const geometry = this.geometry;
  42483. const colorAttribute = geometry.getAttribute( 'color' );
  42484. // near
  42485. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  42486. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  42487. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  42488. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  42489. // far
  42490. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  42491. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  42492. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  42493. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  42494. // sides
  42495. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  42496. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  42497. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  42498. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  42499. // cone
  42500. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  42501. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  42502. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  42503. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  42504. // up
  42505. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  42506. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  42507. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  42508. // target
  42509. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  42510. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  42511. // cross
  42512. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  42513. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  42514. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  42515. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  42516. colorAttribute.needsUpdate = true;
  42517. return this;
  42518. }
  42519. /**
  42520. * Updates the helper based on the projection matrix of the camera.
  42521. */
  42522. update() {
  42523. const geometry = this.geometry;
  42524. const pointMap = this.pointMap;
  42525. const w = 1, h = 1;
  42526. let nearZ, farZ;
  42527. // we need just camera projection matrix inverse
  42528. // world matrix must be identity
  42529. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  42530. // Adjust z values based on coordinate system
  42531. if ( this.camera.reversedDepth === true ) {
  42532. nearZ = 1;
  42533. farZ = 0;
  42534. } else {
  42535. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  42536. nearZ = -1;
  42537. farZ = 1;
  42538. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  42539. nearZ = 0;
  42540. farZ = 1;
  42541. } else {
  42542. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  42543. }
  42544. }
  42545. // center / target
  42546. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  42547. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  42548. // near
  42549. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  42550. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  42551. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  42552. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  42553. // far
  42554. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  42555. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  42556. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  42557. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  42558. // up
  42559. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  42560. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  42561. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  42562. // cross
  42563. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  42564. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  42565. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  42566. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  42567. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  42568. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  42569. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  42570. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  42571. geometry.getAttribute( 'position' ).needsUpdate = true;
  42572. }
  42573. /**
  42574. * Frees the GPU-related resources allocated by this instance. Call this
  42575. * method whenever this instance is no longer used in your app.
  42576. */
  42577. dispose() {
  42578. this.geometry.dispose();
  42579. this.material.dispose();
  42580. }
  42581. }
  42582. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42583. _vector.set( x, y, z ).unproject( camera );
  42584. const points = pointMap[ point ];
  42585. if ( points !== undefined ) {
  42586. const position = geometry.getAttribute( 'position' );
  42587. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42588. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42589. }
  42590. }
  42591. }
  42592. const _box = /*@__PURE__*/ new Box3();
  42593. /**
  42594. * Helper object to graphically show the world-axis-aligned bounding box
  42595. * around an object. The actual bounding box is handled with {@link Box3},
  42596. * this is just a visual helper for debugging. It can be automatically
  42597. * resized with {@link BoxHelper#update} when the object it's created from
  42598. * is transformed. Note that the object must have a geometry for this to work,
  42599. * so it won't work with sprites.
  42600. *
  42601. * ```js
  42602. * const sphere = new THREE.SphereGeometry();
  42603. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42604. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42605. * scene.add( box );
  42606. * ```
  42607. *
  42608. * @augments LineSegments
  42609. */
  42610. class BoxHelper extends LineSegments {
  42611. /**
  42612. * Constructs a new box helper.
  42613. *
  42614. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42615. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42616. */
  42617. constructor( object, color = 0xffff00 ) {
  42618. 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 ] );
  42619. const positions = new Float32Array( 8 * 3 );
  42620. const geometry = new BufferGeometry();
  42621. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42622. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42623. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42624. /**
  42625. * The 3D object being visualized.
  42626. *
  42627. * @type {Object3D}
  42628. */
  42629. this.object = object;
  42630. this.type = 'BoxHelper';
  42631. this.matrixAutoUpdate = false;
  42632. this.update();
  42633. }
  42634. /**
  42635. * Updates the helper's geometry to match the dimensions of the object,
  42636. * including any children.
  42637. */
  42638. update() {
  42639. if ( this.object !== undefined ) {
  42640. _box.setFromObject( this.object );
  42641. }
  42642. if ( _box.isEmpty() ) return;
  42643. const min = _box.min;
  42644. const max = _box.max;
  42645. /*
  42646. 5____4
  42647. 1/___0/|
  42648. | 6__|_7
  42649. 2/___3/
  42650. 0: max.x, max.y, max.z
  42651. 1: min.x, max.y, max.z
  42652. 2: min.x, min.y, max.z
  42653. 3: max.x, min.y, max.z
  42654. 4: max.x, max.y, min.z
  42655. 5: min.x, max.y, min.z
  42656. 6: min.x, min.y, min.z
  42657. 7: max.x, min.y, min.z
  42658. */
  42659. const position = this.geometry.attributes.position;
  42660. const array = position.array;
  42661. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42662. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42663. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42664. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42665. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42666. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42667. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42668. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42669. position.needsUpdate = true;
  42670. this.geometry.computeBoundingSphere();
  42671. }
  42672. /**
  42673. * Updates the wireframe box for the passed object.
  42674. *
  42675. * @param {Object3D} object - The 3D object to create the helper for.
  42676. * @return {BoxHelper} A reference to this instance.
  42677. */
  42678. setFromObject( object ) {
  42679. this.object = object;
  42680. this.update();
  42681. return this;
  42682. }
  42683. copy( source, recursive ) {
  42684. super.copy( source, recursive );
  42685. this.object = source.object;
  42686. return this;
  42687. }
  42688. /**
  42689. * Frees the GPU-related resources allocated by this instance. Call this
  42690. * method whenever this instance is no longer used in your app.
  42691. */
  42692. dispose() {
  42693. this.geometry.dispose();
  42694. this.material.dispose();
  42695. }
  42696. }
  42697. /**
  42698. * A helper object to visualize an instance of {@link Box3}.
  42699. *
  42700. * ```js
  42701. * const box = new THREE.Box3();
  42702. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42703. *
  42704. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42705. * scene.add( helper )
  42706. * ```
  42707. *
  42708. * @augments LineSegments
  42709. */
  42710. class Box3Helper extends LineSegments {
  42711. /**
  42712. * Constructs a new box3 helper.
  42713. *
  42714. * @param {Box3} box - The box to visualize.
  42715. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42716. */
  42717. constructor( box, color = 0xffff00 ) {
  42718. 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 ] );
  42719. 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 ];
  42720. const geometry = new BufferGeometry();
  42721. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42722. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42723. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42724. /**
  42725. * The box being visualized.
  42726. *
  42727. * @type {Box3}
  42728. */
  42729. this.box = box;
  42730. this.type = 'Box3Helper';
  42731. this.geometry.computeBoundingSphere();
  42732. }
  42733. updateMatrixWorld( force ) {
  42734. const box = this.box;
  42735. if ( box.isEmpty() ) return;
  42736. box.getCenter( this.position );
  42737. box.getSize( this.scale );
  42738. this.scale.multiplyScalar( 0.5 );
  42739. super.updateMatrixWorld( force );
  42740. }
  42741. /**
  42742. * Frees the GPU-related resources allocated by this instance. Call this
  42743. * method whenever this instance is no longer used in your app.
  42744. */
  42745. dispose() {
  42746. this.geometry.dispose();
  42747. this.material.dispose();
  42748. }
  42749. }
  42750. /**
  42751. * A helper object to visualize an instance of {@link Plane}.
  42752. *
  42753. * ```js
  42754. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42755. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42756. * scene.add( helper );
  42757. * ```
  42758. *
  42759. * @augments Line
  42760. */
  42761. class PlaneHelper extends Line {
  42762. /**
  42763. * Constructs a new plane helper.
  42764. *
  42765. * @param {Plane} plane - The plane to be visualized.
  42766. * @param {number} [size=1] - The side length of plane helper.
  42767. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42768. */
  42769. constructor( plane, size = 1, hex = 0xffff00 ) {
  42770. const color = hex;
  42771. 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 ];
  42772. const geometry = new BufferGeometry();
  42773. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42774. geometry.computeBoundingSphere();
  42775. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42776. this.type = 'PlaneHelper';
  42777. /**
  42778. * The plane being visualized.
  42779. *
  42780. * @type {Plane}
  42781. */
  42782. this.plane = plane;
  42783. /**
  42784. * The side length of plane helper.
  42785. *
  42786. * @type {number}
  42787. * @default 1
  42788. */
  42789. this.size = size;
  42790. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42791. const geometry2 = new BufferGeometry();
  42792. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42793. geometry2.computeBoundingSphere();
  42794. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42795. }
  42796. updateMatrixWorld( force ) {
  42797. this.position.set( 0, 0, 0 );
  42798. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42799. this.lookAt( this.plane.normal );
  42800. this.translateZ( - this.plane.constant );
  42801. super.updateMatrixWorld( force );
  42802. }
  42803. /**
  42804. * Updates the helper to match the position and direction of the
  42805. * light being visualized.
  42806. */
  42807. dispose() {
  42808. this.geometry.dispose();
  42809. this.material.dispose();
  42810. this.children[ 0 ].geometry.dispose();
  42811. this.children[ 0 ].material.dispose();
  42812. }
  42813. }
  42814. const _axis = /*@__PURE__*/ new Vector3();
  42815. let _lineGeometry, _coneGeometry;
  42816. /**
  42817. * An 3D arrow object for visualizing directions.
  42818. *
  42819. * ```js
  42820. * const dir = new THREE.Vector3( 1, 2, 0 );
  42821. *
  42822. * //normalize the direction vector (convert to vector of length 1)
  42823. * dir.normalize();
  42824. *
  42825. * const origin = new THREE.Vector3( 0, 0, 0 );
  42826. * const length = 1;
  42827. * const hex = 0xffff00;
  42828. *
  42829. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42830. * scene.add( arrowHelper );
  42831. * ```
  42832. *
  42833. * @augments Object3D
  42834. */
  42835. class ArrowHelper extends Object3D {
  42836. /**
  42837. * Constructs a new arrow helper.
  42838. *
  42839. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42840. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42841. * @param {number} [length=1] - Length of the arrow in world units.
  42842. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42843. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42844. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42845. */
  42846. 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 ) {
  42847. super();
  42848. this.type = 'ArrowHelper';
  42849. if ( _lineGeometry === undefined ) {
  42850. _lineGeometry = new BufferGeometry();
  42851. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42852. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42853. _coneGeometry.translate( 0, -0.5, 0 );
  42854. }
  42855. this.position.copy( origin );
  42856. /**
  42857. * The line part of the arrow helper.
  42858. *
  42859. * @type {Line}
  42860. */
  42861. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42862. this.line.matrixAutoUpdate = false;
  42863. this.add( this.line );
  42864. /**
  42865. * The cone part of the arrow helper.
  42866. *
  42867. * @type {Mesh}
  42868. */
  42869. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42870. this.cone.matrixAutoUpdate = false;
  42871. this.add( this.cone );
  42872. this.setDirection( dir );
  42873. this.setLength( length, headLength, headWidth );
  42874. }
  42875. /**
  42876. * Sets the direction of the helper.
  42877. *
  42878. * @param {Vector3} dir - The normalized direction vector.
  42879. */
  42880. setDirection( dir ) {
  42881. // dir is assumed to be normalized
  42882. if ( dir.y > 0.99999 ) {
  42883. this.quaternion.set( 0, 0, 0, 1 );
  42884. } else if ( dir.y < -0.99999 ) {
  42885. this.quaternion.set( 1, 0, 0, 0 );
  42886. } else {
  42887. _axis.set( dir.z, 0, - dir.x ).normalize();
  42888. const radians = Math.acos( dir.y );
  42889. this.quaternion.setFromAxisAngle( _axis, radians );
  42890. }
  42891. }
  42892. /**
  42893. * Sets the length of the helper.
  42894. *
  42895. * @param {number} length - Length of the arrow in world units.
  42896. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42897. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42898. */
  42899. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42900. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42901. this.line.updateMatrix();
  42902. this.cone.scale.set( headWidth, headLength, headWidth );
  42903. this.cone.position.y = length;
  42904. this.cone.updateMatrix();
  42905. }
  42906. /**
  42907. * Sets the color of the helper.
  42908. *
  42909. * @param {number|Color|string} color - The color to set.
  42910. */
  42911. setColor( color ) {
  42912. this.line.material.color.set( color );
  42913. this.cone.material.color.set( color );
  42914. }
  42915. copy( source ) {
  42916. super.copy( source, false );
  42917. this.line.copy( source.line );
  42918. this.cone.copy( source.cone );
  42919. return this;
  42920. }
  42921. /**
  42922. * Frees the GPU-related resources allocated by this instance. Call this
  42923. * method whenever this instance is no longer used in your app.
  42924. */
  42925. dispose() {
  42926. this.line.geometry.dispose();
  42927. this.line.material.dispose();
  42928. this.cone.geometry.dispose();
  42929. this.cone.material.dispose();
  42930. }
  42931. }
  42932. /**
  42933. * An axis object to visualize the 3 axes in a simple way.
  42934. * The X axis is red. The Y axis is green. The Z axis is blue.
  42935. *
  42936. * ```js
  42937. * const axesHelper = new THREE.AxesHelper( 5 );
  42938. * scene.add( axesHelper );
  42939. * ```
  42940. *
  42941. * @augments LineSegments
  42942. */
  42943. class AxesHelper extends LineSegments {
  42944. /**
  42945. * Constructs a new axes helper.
  42946. *
  42947. * @param {number} [size=1] - Size of the lines representing the axes.
  42948. */
  42949. constructor( size = 1 ) {
  42950. const vertices = [
  42951. 0, 0, 0, size, 0, 0,
  42952. 0, 0, 0, 0, size, 0,
  42953. 0, 0, 0, 0, 0, size
  42954. ];
  42955. const colors = [
  42956. 1, 0, 0, 1, 0.6, 0,
  42957. 0, 1, 0, 0.6, 1, 0,
  42958. 0, 0, 1, 0, 0.6, 1
  42959. ];
  42960. const geometry = new BufferGeometry();
  42961. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42962. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42963. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42964. super( geometry, material );
  42965. this.type = 'AxesHelper';
  42966. }
  42967. /**
  42968. * Defines the colors of the axes helper.
  42969. *
  42970. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42971. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42972. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42973. * @return {AxesHelper} A reference to this axes helper.
  42974. */
  42975. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42976. const color = new Color();
  42977. const array = this.geometry.attributes.color.array;
  42978. color.set( xAxisColor );
  42979. color.toArray( array, 0 );
  42980. color.toArray( array, 3 );
  42981. color.set( yAxisColor );
  42982. color.toArray( array, 6 );
  42983. color.toArray( array, 9 );
  42984. color.set( zAxisColor );
  42985. color.toArray( array, 12 );
  42986. color.toArray( array, 15 );
  42987. this.geometry.attributes.color.needsUpdate = true;
  42988. return this;
  42989. }
  42990. /**
  42991. * Frees the GPU-related resources allocated by this instance. Call this
  42992. * method whenever this instance is no longer used in your app.
  42993. */
  42994. dispose() {
  42995. this.geometry.dispose();
  42996. this.material.dispose();
  42997. }
  42998. }
  42999. /**
  43000. * This class is used to convert a series of paths to an array of
  43001. * shapes. It is specifically used in context of fonts and SVG.
  43002. */
  43003. class ShapePath {
  43004. /**
  43005. * Constructs a new shape path.
  43006. */
  43007. constructor() {
  43008. this.type = 'ShapePath';
  43009. /**
  43010. * The color of the shape.
  43011. *
  43012. * @type {Color}
  43013. */
  43014. this.color = new Color();
  43015. /**
  43016. * The paths that have been generated for this shape.
  43017. *
  43018. * @type {Array<Path>}
  43019. * @default null
  43020. */
  43021. this.subPaths = [];
  43022. /**
  43023. * The current path that is being generated.
  43024. *
  43025. * @type {?Path}
  43026. * @default null
  43027. */
  43028. this.currentPath = null;
  43029. /**
  43030. * An object that can be used to store custom data about the shape path.
  43031. * Mainly used by SVGLoader to store style information.
  43032. *
  43033. * @type {Object}
  43034. */
  43035. this.userData = {};
  43036. }
  43037. /**
  43038. * Creates a new path and moves it current point to the given one.
  43039. *
  43040. * @param {number} x - The x coordinate.
  43041. * @param {number} y - The y coordinate.
  43042. * @return {ShapePath} A reference to this shape path.
  43043. */
  43044. moveTo( x, y ) {
  43045. this.currentPath = new Path();
  43046. this.subPaths.push( this.currentPath );
  43047. this.currentPath.moveTo( x, y );
  43048. return this;
  43049. }
  43050. /**
  43051. * Adds an instance of {@link LineCurve} to the path by connecting
  43052. * the current point with the given one.
  43053. *
  43054. * @param {number} x - The x coordinate of the end point.
  43055. * @param {number} y - The y coordinate of the end point.
  43056. * @return {ShapePath} A reference to this shape path.
  43057. */
  43058. lineTo( x, y ) {
  43059. this.currentPath.lineTo( x, y );
  43060. return this;
  43061. }
  43062. /**
  43063. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  43064. * the current point with the given one.
  43065. *
  43066. * @param {number} aCPx - The x coordinate of the control point.
  43067. * @param {number} aCPy - The y coordinate of the control point.
  43068. * @param {number} aX - The x coordinate of the end point.
  43069. * @param {number} aY - The y coordinate of the end point.
  43070. * @return {ShapePath} A reference to this shape path.
  43071. */
  43072. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  43073. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  43074. return this;
  43075. }
  43076. /**
  43077. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  43078. * the current point with the given one.
  43079. *
  43080. * @param {number} aCP1x - The x coordinate of the first control point.
  43081. * @param {number} aCP1y - The y coordinate of the first control point.
  43082. * @param {number} aCP2x - The x coordinate of the second control point.
  43083. * @param {number} aCP2y - The y coordinate of the second control point.
  43084. * @param {number} aX - The x coordinate of the end point.
  43085. * @param {number} aY - The y coordinate of the end point.
  43086. * @return {ShapePath} A reference to this shape path.
  43087. */
  43088. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  43089. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  43090. return this;
  43091. }
  43092. /**
  43093. * Adds an instance of {@link SplineCurve} to the path by connecting
  43094. * the current point with the given list of points.
  43095. *
  43096. * @param {Array<Vector2>} pts - An array of points in 2D space.
  43097. * @return {ShapePath} A reference to this shape path.
  43098. */
  43099. splineThru( pts ) {
  43100. this.currentPath.splineThru( pts );
  43101. return this;
  43102. }
  43103. /**
  43104. * Converts the paths into an array of shapes.
  43105. *
  43106. * @return {Array<Shape>} An array of shapes.
  43107. */
  43108. toShapes() {
  43109. // Point-in-polygon test using the even-odd ray-casting rule. Valid for
  43110. // simple (non self-intersecting) polygons.
  43111. function pointInPolygon( p, polygon ) {
  43112. let inside = false;
  43113. const n = polygon.length;
  43114. for ( let i = 0, j = n - 1; i < n; j = i ++ ) {
  43115. const a = polygon[ i ];
  43116. const b = polygon[ j ];
  43117. if ( ( a.y > p.y ) !== ( b.y > p.y ) &&
  43118. p.x < ( b.x - a.x ) * ( p.y - a.y ) / ( b.y - a.y ) + a.x ) {
  43119. inside = ! inside;
  43120. }
  43121. }
  43122. return inside;
  43123. }
  43124. // Returns a point guaranteed to be strictly inside the given simple
  43125. // polygon. First tries the bounding-box center; if that falls outside
  43126. // the polygon, casts a horizontal ray at the center's y and picks the
  43127. // midpoint between the first two sorted intercepts.
  43128. //
  43129. // Port of paper.js' Path#getInteriorPoint()
  43130. // https://github.com/paperjs/paper.js/blob/develop/src/path/PathItem.Boolean.js
  43131. function getInteriorPoint( polygon, boundingBox ) {
  43132. const point = boundingBox.getCenter( new Vector2() );
  43133. if ( pointInPolygon( point, polygon ) ) return point;
  43134. const y = point.y;
  43135. const intercepts = [];
  43136. const n = polygon.length;
  43137. for ( let i = 0; i < n; i ++ ) {
  43138. const a = polygon[ i ];
  43139. const b = polygon[ ( i + 1 ) % n ];
  43140. // Half-open crossing rule — counts each vertex exactly once and
  43141. // skips horizontal edges.
  43142. if ( ( a.y > y ) !== ( b.y > y ) ) {
  43143. const x = a.x + ( y - a.y ) * ( b.x - a.x ) / ( b.y - a.y );
  43144. intercepts.push( x );
  43145. }
  43146. }
  43147. if ( intercepts.length > 1 ) {
  43148. intercepts.sort( ( a, b ) => a - b );
  43149. point.x = ( intercepts[ 0 ] + intercepts[ 1 ] ) / 2;
  43150. }
  43151. return point;
  43152. }
  43153. // Resolve fill-rule. Defaults to 'nonzero'.
  43154. let fillRule = ( this.userData.style && this.userData.style.fillRule ) || 'nonzero';
  43155. if ( fillRule !== 'nonzero' && fillRule !== 'evenodd' ) {
  43156. warn( 'Fill-rule "' + fillRule + '" is not supported, falling back to "nonzero".' );
  43157. fillRule = 'nonzero';
  43158. }
  43159. // Predicate that decides whether a winding number falls inside the fill
  43160. // region, per the SVG fill-rule spec. Works for negative windings too,
  43161. // because JavaScript's bitwise AND preserves odd/even under two's
  43162. // complement.
  43163. const isInside = fillRule === 'nonzero'
  43164. ? ( w => w !== 0 )
  43165. : ( w => ( w & 1 ) !== 0 );
  43166. // Build an entry per usable subpath. Self-winding follows the standard
  43167. // convention used by ShapeUtils: counter-clockwise (signed area > 0)
  43168. // contributes +1 to the winding number at an interior point,
  43169. // clockwise contributes -1.
  43170. const entries = [];
  43171. for ( const subPath of this.subPaths ) {
  43172. const points = subPath.getPoints();
  43173. if ( points.length < 3 ) continue;
  43174. const area = ShapeUtils.area( points );
  43175. if ( area === 0 ) continue;
  43176. const boundingBox = new Box2();
  43177. for ( let i = 0; i < points.length; i ++ ) boundingBox.expandByPoint( points[ i ] );
  43178. entries.push( {
  43179. subPath: subPath,
  43180. points: points,
  43181. boundingBox: boundingBox,
  43182. interiorPoint: getInteriorPoint( points, boundingBox ),
  43183. absArea: Math.abs( area ),
  43184. winding: area < 0 ? -1 : 1,
  43185. container: null,
  43186. exclude: false,
  43187. role: null
  43188. } );
  43189. }
  43190. // Sort by area descending. This guarantees that any subpath that could
  43191. // contain `entries[i]` is located at a smaller index and has already
  43192. // been processed when it's entries[i]'s turn. Port of paper.js'
  43193. // reorientPaths() algorithm.
  43194. entries.sort( ( a, b ) => b.absArea - a.absArea );
  43195. // Walk already-processed entries from closest-in-size to largest,
  43196. // stopping at the innermost container. Accumulate the container's
  43197. // cumulative winding into this entry's winding so that the final value
  43198. // equals the winding number at this entry's interior point.
  43199. //
  43200. // A subpath only contributes to the fill boundary when crossing it
  43201. // actually flips the "insideness" per the fill rule; otherwise it's a
  43202. // redundant overlap and gets excluded to avoid double-counting.
  43203. for ( let i = 0; i < entries.length; i ++ ) {
  43204. const entry = entries[ i ];
  43205. let containerWinding = 0;
  43206. for ( let j = i - 1; j >= 0; j -- ) {
  43207. const candidate = entries[ j ];
  43208. if ( ! candidate.boundingBox.containsPoint( entry.interiorPoint ) ) continue;
  43209. if ( ! pointInPolygon( entry.interiorPoint, candidate.points ) ) continue;
  43210. entry.container = candidate.exclude ? candidate.container : candidate;
  43211. containerWinding = candidate.winding;
  43212. entry.winding += containerWinding;
  43213. break;
  43214. }
  43215. if ( isInside( entry.winding ) === isInside( containerWinding ) ) {
  43216. entry.exclude = true;
  43217. }
  43218. }
  43219. // Classify retained entries. An entry is an outer shape if it has no
  43220. // container or if its container is itself a hole (a solid nested inside
  43221. // a hole becomes a new top-level shape); otherwise it's a hole in its
  43222. // container. Entries were already sorted outermost-first, so each
  43223. // container's role is known by the time we look at it.
  43224. for ( const entry of entries ) {
  43225. if ( entry.exclude ) continue;
  43226. entry.role = ( entry.container === null || entry.container.role === 'hole' ) ? 'outer' : 'hole';
  43227. }
  43228. // Build Shapes for outers first, then attach holes to their container's
  43229. // Shape.
  43230. const shapes = [];
  43231. const shapeByEntry = new Map();
  43232. for ( const entry of entries ) {
  43233. if ( entry.exclude || entry.role !== 'outer' ) continue;
  43234. const shape = new Shape();
  43235. shape.curves = entry.subPath.curves;
  43236. shapes.push( shape );
  43237. shapeByEntry.set( entry, shape );
  43238. }
  43239. for ( const entry of entries ) {
  43240. if ( entry.exclude || entry.role !== 'hole' ) continue;
  43241. const shape = shapeByEntry.get( entry.container );
  43242. if ( ! shape ) continue;
  43243. const hole = new Path();
  43244. hole.curves = entry.subPath.curves;
  43245. shape.holes.push( hole );
  43246. }
  43247. return shapes;
  43248. }
  43249. }
  43250. /**
  43251. * Abstract base class for controls.
  43252. *
  43253. * @abstract
  43254. * @augments EventDispatcher
  43255. */
  43256. class Controls extends EventDispatcher {
  43257. /**
  43258. * Constructs a new controls instance.
  43259. *
  43260. * @param {Object3D} object - The object that is managed by the controls.
  43261. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  43262. */
  43263. constructor( object, domElement = null ) {
  43264. super();
  43265. /**
  43266. * The object that is managed by the controls.
  43267. *
  43268. * @type {Object3D}
  43269. */
  43270. this.object = object;
  43271. /**
  43272. * The HTML element used for event listeners.
  43273. *
  43274. * @type {?HTMLElement}
  43275. * @default null
  43276. */
  43277. this.domElement = domElement;
  43278. /**
  43279. * Whether the controls responds to user input or not.
  43280. *
  43281. * @type {boolean}
  43282. * @default true
  43283. */
  43284. this.enabled = true;
  43285. /**
  43286. * The internal state of the controls.
  43287. *
  43288. * @type {number}
  43289. * @default -1
  43290. */
  43291. this.state = -1;
  43292. /**
  43293. * This object defines the keyboard input of the controls.
  43294. *
  43295. * @type {Object}
  43296. */
  43297. this.keys = {};
  43298. /**
  43299. * This object defines what type of actions are assigned to the available mouse buttons.
  43300. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  43301. *
  43302. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  43303. */
  43304. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  43305. /**
  43306. * This object defines what type of actions are assigned to what kind of touch interaction.
  43307. * It depends on the control implementation what kind of touch interaction and actions are supported.
  43308. *
  43309. * @type {{ONE: ?number, TWO: ?number}}
  43310. */
  43311. this.touches = { ONE: null, TWO: null };
  43312. }
  43313. /**
  43314. * Connects the controls to the DOM. This method has so called "side effects" since
  43315. * it adds the module's event listeners to the DOM.
  43316. *
  43317. * @param {HTMLElement} element - The DOM element to connect to.
  43318. */
  43319. connect( element ) {
  43320. if ( element === undefined ) {
  43321. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  43322. return;
  43323. }
  43324. if ( this.domElement !== null ) this.disconnect();
  43325. this.domElement = element;
  43326. }
  43327. /**
  43328. * Disconnects the controls from the DOM.
  43329. */
  43330. disconnect() {}
  43331. /**
  43332. * Call this method if you no longer want use to the controls. It frees all internal
  43333. * resources and removes all event listeners.
  43334. */
  43335. dispose() {}
  43336. /**
  43337. * Controls should implement this method if they have to update their internal state
  43338. * per simulation step.
  43339. *
  43340. * @param {number} [delta] - The time delta in seconds.
  43341. */
  43342. update( /* delta */ ) {}
  43343. }
  43344. /**
  43345. * Scales the texture as large as possible within its surface without cropping
  43346. * or stretching the texture. The method preserves the original aspect ratio of
  43347. * the texture. Akin to CSS `object-fit: contain`
  43348. *
  43349. * @param {Texture} texture - The texture.
  43350. * @param {number} aspect - The texture's aspect ratio.
  43351. * @return {Texture} The updated texture.
  43352. */
  43353. function contain( texture, aspect ) {
  43354. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  43355. if ( imageAspect > aspect ) {
  43356. texture.repeat.x = 1;
  43357. texture.repeat.y = imageAspect / aspect;
  43358. texture.offset.x = 0;
  43359. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  43360. } else {
  43361. texture.repeat.x = aspect / imageAspect;
  43362. texture.repeat.y = 1;
  43363. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  43364. texture.offset.y = 0;
  43365. }
  43366. return texture;
  43367. }
  43368. /**
  43369. * Scales the texture to the smallest possible size to fill the surface, leaving
  43370. * no empty space. The method preserves the original aspect ratio of the texture.
  43371. * Akin to CSS `object-fit: cover`.
  43372. *
  43373. * @param {Texture} texture - The texture.
  43374. * @param {number} aspect - The texture's aspect ratio.
  43375. * @return {Texture} The updated texture.
  43376. */
  43377. function cover( texture, aspect ) {
  43378. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  43379. if ( imageAspect > aspect ) {
  43380. texture.repeat.x = aspect / imageAspect;
  43381. texture.repeat.y = 1;
  43382. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  43383. texture.offset.y = 0;
  43384. } else {
  43385. texture.repeat.x = 1;
  43386. texture.repeat.y = imageAspect / aspect;
  43387. texture.offset.x = 0;
  43388. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  43389. }
  43390. return texture;
  43391. }
  43392. /**
  43393. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43394. *
  43395. * @param {Texture} texture - The texture.
  43396. * @return {Texture} The updated texture.
  43397. */
  43398. function fill( texture ) {
  43399. texture.repeat.x = 1;
  43400. texture.repeat.y = 1;
  43401. texture.offset.x = 0;
  43402. texture.offset.y = 0;
  43403. return texture;
  43404. }
  43405. /**
  43406. * Determines how many bytes must be used to represent the texture.
  43407. *
  43408. * @param {number} width - The width of the texture.
  43409. * @param {number} height - The height of the texture.
  43410. * @param {number} format - The texture's format.
  43411. * @param {number} type - The texture's type.
  43412. * @return {number} The byte length.
  43413. */
  43414. function getByteLength( width, height, format, type ) {
  43415. const typeByteLength = getTextureTypeByteLength( type );
  43416. switch ( format ) {
  43417. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  43418. case AlphaFormat:
  43419. return width * height;
  43420. case RedFormat:
  43421. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43422. case RedIntegerFormat:
  43423. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43424. case RGFormat:
  43425. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43426. case RGIntegerFormat:
  43427. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43428. case RGBFormat:
  43429. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43430. case RGBAFormat:
  43431. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43432. case RGBAIntegerFormat:
  43433. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43434. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  43435. case RGB_S3TC_DXT1_Format:
  43436. case RGBA_S3TC_DXT1_Format:
  43437. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43438. case RGBA_S3TC_DXT3_Format:
  43439. case RGBA_S3TC_DXT5_Format:
  43440. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43441. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  43442. case RGB_PVRTC_2BPPV1_Format:
  43443. case RGBA_PVRTC_2BPPV1_Format:
  43444. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  43445. case RGB_PVRTC_4BPPV1_Format:
  43446. case RGBA_PVRTC_4BPPV1_Format:
  43447. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  43448. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  43449. case RGB_ETC1_Format:
  43450. case RGB_ETC2_Format:
  43451. case R11_EAC_Format:
  43452. case SIGNED_R11_EAC_Format:
  43453. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43454. case RGBA_ETC2_EAC_Format:
  43455. case RG11_EAC_Format:
  43456. case SIGNED_RG11_EAC_Format:
  43457. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43458. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  43459. case RGBA_ASTC_4x4_Format:
  43460. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43461. case RGBA_ASTC_5x4_Format:
  43462. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43463. case RGBA_ASTC_5x5_Format:
  43464. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43465. case RGBA_ASTC_6x5_Format:
  43466. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43467. case RGBA_ASTC_6x6_Format:
  43468. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43469. case RGBA_ASTC_8x5_Format:
  43470. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43471. case RGBA_ASTC_8x6_Format:
  43472. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43473. case RGBA_ASTC_8x8_Format:
  43474. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43475. case RGBA_ASTC_10x5_Format:
  43476. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43477. case RGBA_ASTC_10x6_Format:
  43478. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43479. case RGBA_ASTC_10x8_Format:
  43480. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43481. case RGBA_ASTC_10x10_Format:
  43482. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43483. case RGBA_ASTC_12x10_Format:
  43484. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43485. case RGBA_ASTC_12x12_Format:
  43486. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  43487. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  43488. case RGBA_BPTC_Format:
  43489. case RGB_BPTC_SIGNED_Format:
  43490. case RGB_BPTC_UNSIGNED_Format:
  43491. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43492. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  43493. case RED_RGTC1_Format:
  43494. case SIGNED_RED_RGTC1_Format:
  43495. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  43496. case RED_GREEN_RGTC2_Format:
  43497. case SIGNED_RED_GREEN_RGTC2_Format:
  43498. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43499. }
  43500. throw new Error(
  43501. `Unable to determine texture byte length for ${format} format.`,
  43502. );
  43503. }
  43504. function getTextureTypeByteLength( type ) {
  43505. switch ( type ) {
  43506. case UnsignedByteType:
  43507. case ByteType:
  43508. return { byteLength: 1, components: 1 };
  43509. case UnsignedShortType:
  43510. case ShortType:
  43511. case HalfFloatType:
  43512. return { byteLength: 2, components: 1 };
  43513. case UnsignedShort4444Type:
  43514. case UnsignedShort5551Type:
  43515. return { byteLength: 2, components: 4 };
  43516. case UnsignedIntType:
  43517. case IntType:
  43518. case FloatType:
  43519. return { byteLength: 4, components: 1 };
  43520. case UnsignedInt5999Type:
  43521. case UnsignedInt101111Type:
  43522. return { byteLength: 4, components: 3 };
  43523. }
  43524. throw new Error( `THREE.TextureUtils: Unknown texture type ${type}.` );
  43525. }
  43526. /**
  43527. * A class containing utility functions for textures.
  43528. *
  43529. * @hideconstructor
  43530. */
  43531. class TextureUtils {
  43532. /**
  43533. * Scales the texture as large as possible within its surface without cropping
  43534. * or stretching the texture. The method preserves the original aspect ratio of
  43535. * the texture. Akin to CSS `object-fit: contain`
  43536. *
  43537. * @param {Texture} texture - The texture.
  43538. * @param {number} aspect - The texture's aspect ratio.
  43539. * @return {Texture} The updated texture.
  43540. */
  43541. static contain( texture, aspect ) {
  43542. return contain( texture, aspect );
  43543. }
  43544. /**
  43545. * Scales the texture to the smallest possible size to fill the surface, leaving
  43546. * no empty space. The method preserves the original aspect ratio of the texture.
  43547. * Akin to CSS `object-fit: cover`.
  43548. *
  43549. * @param {Texture} texture - The texture.
  43550. * @param {number} aspect - The texture's aspect ratio.
  43551. * @return {Texture} The updated texture.
  43552. */
  43553. static cover( texture, aspect ) {
  43554. return cover( texture, aspect );
  43555. }
  43556. /**
  43557. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43558. *
  43559. * @param {Texture} texture - The texture.
  43560. * @return {Texture} The updated texture.
  43561. */
  43562. static fill( texture ) {
  43563. return fill( texture );
  43564. }
  43565. /**
  43566. * Determines how many bytes must be used to represent the texture.
  43567. *
  43568. * @param {number} width - The width of the texture.
  43569. * @param {number} height - The height of the texture.
  43570. * @param {number} format - The texture's format.
  43571. * @param {number} type - The texture's type.
  43572. * @return {number} The byte length.
  43573. */
  43574. static getByteLength( width, height, format, type ) {
  43575. return getByteLength( width, height, format, type );
  43576. }
  43577. }
  43578. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43579. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43580. revision: REVISION,
  43581. } } ) );
  43582. }
  43583. if ( typeof window !== 'undefined' ) {
  43584. if ( window.__THREE__ ) {
  43585. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43586. } else {
  43587. window.__THREE__ = REVISION;
  43588. }
  43589. }
  43590. 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号